Restructure of pester test layout

This restructuring moves tests to a directory name which matches the module
in which the cmdlet resides which should improve the discoverability of a
specific test.
For tests which are not about cmdlets in a module, new directories have been
created to make those tests easier to find as well
This commit is contained in:
James Truher authored and Andrew Schwartzmeyer committed 2016-06-29 12:05:41 -07:00
1 parent ef32e2339e
commit 1e1c4b7dc0
126 files changed
+10 -6

No files matched your search

@@ -0,0 +1,24 @@
Describe "Import-Module" {
$moduleName = "Microsoft.PowerShell.Security"
BeforeEach {
Remove-Module -Name $moduleName -Force
(Get-Module -Name $moduleName).Name | Should BeNullOrEmpty
}
AfterEach {
Import-Module -Name $moduleName -Force
(Get-Module -Name $moduleName).Name | Should Be $moduleName
}
It "should be able to add a module with using Name switch" {
{ Import-Module -Name $moduleName } | Should Not Throw
(Get-Module -Name $moduleName).Name | Should Be $moduleName
}
It "should be able to add a module with using ModuleInfo switch" {
$a = Get-Module -ListAvailable $moduleName
{ Import-Module -ModuleInfo $a } | Should Not Throw
(Get-Module -Name $moduleName).Name | Should Be $moduleName
}
}
@@ -0,0 +1,23 @@
Describe "Remove-Module" {
$moduleName = "Microsoft.PowerShell.Security"
BeforeEach {
Import-Module -Name $moduleName -Force
(Get-Module -Name $moduleName).Name | Should be $moduleName
}
It "should be able to remove a module with using Name switch" {
{ Remove-Module -Name $moduleName } | Should Not Throw
(Get-Module -Name $moduleName).Name | Should BeNullOrEmpty
}
It "should be able to remove a module with using ModuleInfo switch" {
$a = Get-Module -Name $moduleName
{ Remove-Module -ModuleInfo $a } | Should Not Throw
(Get-Module -Name $moduleName).Name | Should BeNullOrEmpty
}
AfterEach {
Import-Module -Name $moduleName -Force
}
}
@@ -0,0 +1,17 @@
Describe "Set-PSDebug" {
Context "Tracing can be used" {
AfterEach {
Set-PSDebug -Off
}
It "Should be able to go through the tracing options" -Skip:($env:APPVEYOR -eq "TRUE") {
{ Set-PSDebug -Trace 0 } | Should Not Throw
{ Set-PSDebug -Trace 1 } | Should Not Throw
{ Set-PSDebug -Trace 2 } | Should Not Throw
}
It "Should be able to set strict" -Skip:($env:APPVEYOR -eq "TRUE") {
{ Set-PSDebug -Strict } | Should Not Throw
}
}
}
@@ -0,0 +1,50 @@
Describe "Add-Content cmdlet tests" -Tags:DRT {
$file1 = "file1.txt"
Setup -File "$file1"
Context "Add-Content should actually add content" {
It "should Add-Content to testdrive:\$file1" {
$result=add-content -path testdrive:\$file1 -value "ExpectedContent" -passthru
$result| Should be "ExpectedContent"
}
It "should return expected string from testdrive:\$file1" {
$result = get-content -path testdrive:\$file1
$result | Should BeExactly "ExpectedContent"
}
It "should Add-Content to testdrive:\dynamicfile.txt with dynamic parameters" -Pending:($IsLinux -Or $IsOSX) {#https://github.com/PowerShell/PowerShell/issues/891
$result=add-content -path testdrive:\dynamicfile.txt -value "ExpectedContent" -passthru
$result| Should BeExactly "ExpectedContent"
}
It "should return expected string from testdrive:\dynamicfile.txt" -Pending:($IsLinux -Or $IsOSX) {#https://github.com/PowerShell/PowerShell/issues/891
$result = get-content -path testdrive:\dynamicfile.txt
$result | Should BeExactly "ExpectedContent"
}
It "should Add-Content to testdrive:\$file1 even when -Value is `$null" {
$AsItWas=get-content testdrive:\$file1
{add-content -path testdrive:\$file1 -value $null -ea stop} | Should Not Throw
get-content testdrive:\$file1 | Should BeExactly $AsItWas
}
It "should throw 'ParameterArgumentValidationErrorNullNotAllowed' when -Path is `$null" {
Try {add-content -path $null -value "ShouldNotWorkBecausePathIsNull" -ea stop; Throw "Previous statement unexpectedly succeeded..."
} Catch {$_.FullyQualifiedErrorId | Should Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.AddContentCommand"}
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 903880)]
It "should throw `"Cannot bind argument to parameter 'Path'`" when -Path is `$()" {
Try {add-content -path $() -value "ShouldNotWorkBecausePathIsInvalid" -ea stop; Throw "Previous statement unexpectedly succeeded..."
} Catch {$_.FullyQualifiedErrorId | Should Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.AddContentCommand"}
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 906022)]
It "should throw 'NotSupportedException' when you add-content to an unsupported provider" -Skip:($IsLinux -Or $IsOSX) {
Try {add-content -path HKLM:\\software\\microsoft -value "ShouldNotWorkBecausePathIsUnsupported" -ea stop; Throw "Previous statement unexpectedly succeeded..."
} Catch {$_.FullyQualifiedErrorId | Should Be "NotSupported,Microsoft.PowerShell.Commands.AddContentCommand"}
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 9058182)]
It "should be able to pass multiple [string]`$objects to Add-Content through the pipeline to output a dynamic Path file" -Pending:($IsLinux -Or $IsOSX) {#https://github.com/PowerShell/PowerShell/issues/891
"hello","world"|add-content testdrive:\dynamicfile2.txt
$result=get-content testdrive:\dynamicfile2.txt
$result.length |Should be 2
$result[0] |Should be "hello"
$result[1] |Should be "world"
}
}
}
@@ -0,0 +1,26 @@
Describe "Clear-Content cmdlet tests" -Tags:DRT {
$file1 = "file1.txt"
Setup -File "$file1"
Context "Clear-Content should actually clear content" {
It "should clear-Content of testdrive:\$file1" {
set-content -path testdrive:\$file1 -value "ExpectedContent" -passthru | Should be "ExpectedContent"
clear-content -Path testdrive:\$file1
}
It "shouldn't get any content from testdrive:\$file1" {
$result = get-content -path testdrive:\$file1
$result | Should BeExactly $null
}
It "should throw `"Cannot bind argument to parameter 'Path'`" when -Path is `$null" {
{clear-content -path $null -ea stop} | Should Throw "Cannot bind argument to parameter 'Path'"
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 903880)]
It "should throw `"Cannot bind argument to parameter 'Path'`" when -Path is `$()" {
{clear-content -path $() -ea stop} | Should Throw "Cannot bind argument to parameter 'Path'"
}
#[DRT][BugId(BugDatabase.WindowsOutOfBandReleases, 906022)]
It "should throw 'PSNotSupportedException' when you set-content to an unsupported provider" -Skip:($IsLinux -Or $IsOSX) {
{clear-content -path HKLM:\\software\\microsoft -ea stop} | Should Throw "IContentCmdletProvider interface is not implemented"
}
}
}
@@ -0,0 +1,31 @@
if ($IsWindows) {
#check to see whether we're running as admin in Windows...
$windowsIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
$windowsPrincipal = new-object 'Security.Principal.WindowsPrincipal' $windowsIdentity
if ($windowsPrincipal.IsInRole("Administrators") -eq $true) {
$NonWinAdmin=$false
} else {$NonWinAdmin=$true}
Describe "Clear-EventLog cmdlet tests" -Tags:DRT {
#DRT - CmdLet is NYI - change to -Skip:($NonWinAdmin) when implemented
It "should be able to Clear-EventLog" -Pending:($True -Or $NonWinAdmin) {
Remove-EventLog -LogName TestLog -ea Ignore
{New-EventLog -LogName TestLog -Source TestSource -ea Stop} | Should Not Throw
{Write-EventLog -LogName TestLog -Source TestSource -Message "Test" -EventID 1 -ea stop } | Should Not Throw
{$result=Get-EventLog -LogName TestLog} | Should Not Throw
($result.Count) | Should be 1
{Clear-EventLog -LogName TestLog} | Should Not Throw
$result=Get-EventLog -LogName TestLog -ea Ignore
($result.Count) | Should be 0
{Remove-EventLog -LogName TestLog -ea Stop} | Should Not Throw
}
It "should throw 'The Log name 'MissingTestLog' does not exist' when asked to clear a log that does not exist" -Pending:($True -Or $NonWinAdmin) {
Remove-EventLog -LogName MissingTestLog -ea Ignore
try {Clear-EventLog -LogName MissingTestLog -ea stop; Throw "Previous statement unexpectedly succeeded..."
} catch {$_.FullyQualifiedErrorId | Should Be "Microsoft.PowerShell.Commands.ClearEventLogCommand"}
}
It "should throw 'System.InvalidOperationException' when asked to clear a log that does not exist" -Pending:($True -Or $NonWinAdmin) {
try {Clear-EventLog -LogName MissingTestLog -ea stop; Throw "Previous statement unexpectedly succeeded..."
} catch {$_.FullyQualifiedErrorId | Should Be "Microsoft.PowerShell.Commands.ClearEventLogCommand"}
}
}
}
@@ -0,0 +1,36 @@
Describe "Get-ChildItem" {
It "Should list the contents of the current folder" {
(Get-ChildItem .).Name.Length | Should BeGreaterThan 0
}
It "Should list the contents of the home directory" {
pushd $HOME
(Get-ChildItem .).Name.Length | Should BeGreaterThan 0
popd
}
It "Should have a the proper fields and be populated" {
$var = Get-Childitem .
$var.Name.Length | Should BeGreaterThan 0
$var.Mode.Length | Should BeGreaterThan 0
$var.LastWriteTime | Should BeGreaterThan 0
$var.Length.Length | Should BeGreaterThan 0
}
It "Should list files in sorted order" {
New-Item -Path $TestDrive -Name "a" -ItemType "File" -Force
New-Item -Path $TestDrive -Name "B" -ItemType "File" -Force
New-Item -Path $TestDrive -Name "c" -ItemType "File" -Force
New-Item -Path $TestDrive -Name "D" -ItemType "File" -Force
New-Item -Path $TestDrive -Name "E" -ItemType "Directory" -Force
$files = Get-ChildItem -Path $TestDrive
$files[0].Name | Should Be "E"
$files[1].Name | Should Be "a"
$files[2].Name | Should Be "B"
$files[3].Name | Should Be "c"
$files[4].Name | Should Be "D"
}
}
@@ -0,0 +1,134 @@
Describe "Get-Content" -Tags:DRT {
$testString = "This is a test content for a file"
$nl = [Environment]::NewLine
$firstline = "Here's a first line "
$secondline = " here's a second line"
$thirdline = "more text"
$fourthline = "just to make sure"
$fifthline = "there's plenty to work with"
$testString2 = $firstline + $nl + $secondline + $nl + $thirdline + $nl + $fourthline + $nl + $fifthline
$testPath = Join-Path -Path $TestDrive -ChildPath testfile1
$testPath2 = Join-Path -Path $TestDrive -ChildPath testfile2
BeforeEach {
New-Item -Path $testPath -ItemType file -Force -Value $testString
New-Item -Path $testPath2 -ItemType file -Force -Value $testString2
}
AfterEach {
Remove-Item -Path $testPath -Force
Remove-Item -Path $testPath2 -Force
}
It "Should throw an error on a directory " {# also tests that -erroraction SilentlyContinue will work.
Get-Content . -ErrorAction SilentlyContinue | Should Throw
}
It "Should return an Object when listing only a single line" {
(Get-Content -Path $testPath).GetType().BaseType.Name | Should Be "Object"
}
It "Should deliver an array object when listing a file with multiple lines" {
(Get-Content -Path $testPath2).GetType().BaseType.Name | Should Be "Array"
}
It "Should return the correct information from a file" {
(Get-Content -Path $testPath) | Should Be $testString
}
It "Should be able to call using the gc alias" {
{ gc -Path $testPath } | Should Not Throw
}
It "Should be able to call using the type alias" {
{ type -Path $testPath } | Should Not Throw
}
It "Should return the same values for aliases" {
$getContentAlias = Get-Content -Path $testPath
$gcAlias = gc -Path $testPath
$typeAlias = type -Path $testPath
$getContentAlias | Should Be $gcAlias
$getContentAlias | Should Be $typeAlias
}
It "Should be able to return a specific line from a file" {
(Get-Content -Path $testPath2)[1] | Should be $secondline
}
It "Should be able to specify the number of lines to get the content of using the TotalCount switch" {
$returnArray = (Get-Content -Path $testPath2 -TotalCount 2)
$returnArray[0] | Should Be $firstline
$returnArray[1] | Should Be $secondline
}
It "Should be able to specify the number of lines to get the content of using the Head switch" {
$returnArray = (Get-Content -Path $testPath2 -Head 2)
$returnArray[0] | Should Be $firstline
$returnArray[1] | Should Be $secondline
}
It "Should be able to specify the number of lines to get the content of using the First switch" {
$returnArray = (Get-Content -Path $testPath2 -First 2)
$returnArray[0] | Should Be $firstline
$returnArray[1] | Should Be $secondline
}
It "Should return the last line of a file using the Tail switch" {
Get-Content -Path $testPath -Tail 1 | Should Be $testString
}
It "Should return the last lines of a file using the Last alias" {
Get-Content -Path $testPath2 -Last 1 | Should Be $fifthline
}
It "Should be able to get content within a different drive" {
pushd env:
$expectedoutput = [Environment]::GetEnvironmentVariable("PATH");
{ Get-Content PATH } | Should Not Throw
Get-Content PATH | Should Be $expectedoutput
popd
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 906022)]
It "should throw 'PSNotSupportedException' when you set-content to an unsupported provider" -Skip:($IsLinux -Or $IsOSX) {
{get-content -path HKLM:\\software\\microsoft -ea stop} | Should Throw "IContentCmdletProvider interface is not implemented"
}
It "should Get-Content with a variety of -Tail and -ReadCount values" {#[DRT]
set-content -path $testPath "Hello,World","Hello2,World2","Hello3,World3","Hello4,World4"
$result=get-content -path $testPath -readcount:-1 -tail 5
$result.Length | Should Be 4
$expected = "Hello,World","Hello2,World2","Hello3,World3","Hello4,World4"
for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should BeExactly $expected[$i]}
$result=get-content -path $testPath -readcount 0 -tail 3
$result.Length | Should Be 3
$expected = "Hello2,World2","Hello3,World3","Hello4,World4"
for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should BeExactly $expected[$i]}
$result=get-content -path $testPath -readcount 1 -tail 3
$result.Length | Should Be 3
$expected = "Hello2,World2","Hello3,World3","Hello4,World4"
for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should BeExactly $expected[$i]}
$result=get-content -path $testPath -readcount 99999 -tail 3
$result.Length | Should Be 3
$expected = "Hello2,World2","Hello3,World3","Hello4,World4"
for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should BeExactly $expected[$i]}
$result=get-content -path $testPath -readcount 2 -tail 3
$result.Length | Should Be 2
$expected = "Hello2,World2","Hello3,World3"
$expected = $expected,"Hello4,World4"
for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should BeExactly $expected[$i]}
$result=get-content -path $testPath -readcount 2 -tail 2
$result.Length | Should Be 2
$expected = "Hello3,World3","Hello4,World4"
for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should BeExactly $expected[$i]}
$result=get-content -path $testPath -delimiter "," -tail 2
$result.Length | Should Be 2
if ($IsWindows) {$expected = "World3`r`nHello4,","World4`r`n"
} else {$expected = "World3`nHello4,","World4`n"}
for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should BeExactly $expected[$i]}
$result=get-content -path $testPath -delimiter "o" -tail 3
$result.Length | Should Be 3
if ($IsWindows) {$expected = "rld3`r`nHello","4,Wo","rld4"
} else {$expected = "rld3`nHello","4,Wo","rld4"}
for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i].Trim() | Should BeExactly $expected[$i]}
$result=get-content -path $testPath -encoding:Byte -tail 10
$result.Length | Should Be 10
if ($IsWindows) {
$expected = "52","44","87","111","114","108","100","52","13","10"
for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should BeExactly $expected[$i]}
}
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 905829)]
It "should get-content that matches the input string"{
set-content $testPath "Hello,llllWorlld","Hello2,llllWorlld2"
$result=get-content $testPath -delimiter "ll"
$result.Length | Should Be 9
if ($IsWindows) {$expected = "Hell","o,ll","ll","Worll","d`r`nHell","o2,ll","ll","Worll","d2`r`n"
} else {$expected = "Hell","o,ll","ll","Worll","d`nHell","o2,ll","ll","Worll","d2`n"}
for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should BeExactly $expected[$i]}
}
}
@@ -0,0 +1,44 @@
if ($IsWindows) {
#check to see whether we're running as admin in Windows...
$windowsIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
$windowsPrincipal = new-object 'Security.Principal.WindowsPrincipal' $windowsIdentity
if ($windowsPrincipal.IsInRole("Administrators") -eq $true) {
$NonWinAdmin=$false
} else {exit}
Describe "Get-EventLog cmdlet tests" -Tags:DRT {
#CmdLets are not yet implemented, so these cases are -Pending:($True) for now...
It "should return an array of eventlogs objects when called with -AsString parameter" -Pending:($True) {
{$result=Get-EventLog -AsString -ea stop} | Should Not Throw
$result.GetType().BaseType.Name | Should Be "Array"
$result -eq "Application" | Should Be "Application"
$result.Count -ge 3 | Should Be $true
}
It "should return a list of eventlog objects when called with -List parameter" -Pending:($True) {
{$result=Get-EventLog -List -ea stop} | Should Not Throw
$result.GetType().BaseType.Name | Should Be "array"
{$logs=$result|Select -ExpandProperty Log} | Should Not Throw
$logs -eq "System" | Should Be "System"
$logs.Count -ge 3 | Should Be $true
}
It "should be able to Get-EventLog -LogName Application -Newest 100" -Pending:($True) {
{$result=get-eventlog -LogName Application -Newest 100 -ea stop} | Should Not Throw
$result | Should Not BeNullOrEmpty
$result.Length -le 100 | Should Be $true
$result[0].GetType().Name | Should Be "EventLogEntry"
}
It "should throw 'AmbiguousParameterSetException' when called with both -LogName and -List parameters" -Pending:($True) {
try {Get-EventLog -LogName System -List -ea stop; Throw "Previous statement unexpectedly succeeded..."
} catch {echo $_.FullyQualifiedErrorId | Should Be "AmbiguousParameterSet,Microsoft.PowerShell.Commands.GetEventLogCommand"}
}
It "should be able to Get-EventLog -LogName * with multiple matches" -Pending:($True) {
{$result=get-eventlog -LogName * -ea stop} | Should Not Throw
$result | Should Not BeNullOrEmpty
$result -eq "Security" | Should Be "Security"
$result.Count -ge 3 | Should Be $true
}
It "should throw 'InvalidOperationException' when asked to get a log that does not exist" -Pending:($True) {
try {Get-EventLog -LogName MissingTestLog -ea stop; Throw "Previous statement unexpectedly succeeded..."
} catch {echo $_.FullyQualifiedErrorId | Should Be "System.InvalidOperationException,Microsoft.PowerShell.Commands.GetEventLogCommand"}
}
}
}
@@ -0,0 +1,20 @@
Describe "Get-Item" {
It "Should list all the items in the current working directory when asterisk is used" {
(Get-Item (Join-Path -Path $PSScriptRoot -ChildPath "*")).GetType().BaseType | Should Be 'array'
(Get-Item (Join-Path -Path $PSScriptRoot -ChildPath "*")).GetType().Name | Should Be 'Object[]'
}
It "Should return the name of the current working directory when a dot is used" {
(Get-Item $PSScriptRoot).GetType().BaseType | Should Be 'System.IO.FileSystemInfo'
(Get-Item $PSScriptRoot).Name | Should Be (Split-Path $PSScriptRoot -Leaf)
}
It "Should return the proper Name and BaseType for directory objects vs file system objects" {
(Get-Item $PSScriptRoot).GetType().Name | Should Be 'DirectoryInfo'
(Get-Item (Join-Path -Path $PSScriptRoot -ChildPath Get-Item.Tests.ps1)).GetType().Name | Should Be 'FileInfo'
}
It "Should have mode flags set" {
Get-ChildItem $PSScriptRoot | foreach-object { $_.Mode | Should Not BeNullOrEmpty }
}
}
@@ -0,0 +1,52 @@
Describe "Get-ItemProperty" {
$currentDirectory = Split-Path $PSScriptRoot -Leaf
$parentDirectory = Split-Path (Join-Path -Path $PSScriptRoot -ChildPath "..") -Leaf
$tempDirectory = $TestDrive
$testprovider = (Get-Item $tempDirectory).PSDrive.Name
$testfile = Join-Path -Path $tempDirectory -ChildPath testfile1
New-Item $testfile -ItemType file -Force
It "Should be able to be called on in the current directory" {
$(Get-ItemProperty $PSScriptRoot).Name | Should Be $currentDirectory
}
It "Should be able to be called on a parent directory" {
(Get-ItemProperty $PSScriptRoot/..).Name | Should Be $parentDirectory
}
It "Should be able to be called on a directory using the path switch" {
{ Get-ItemProperty -Path $tempDirectory } | Should Not Throw
}
It "Should be able to be called on a file using the path switch" {
{ Get-ItemProperty -Path $testfile } | Should Not Throw
}
It "Should be able to access a property using the Path and name switches" {
{ Get-ItemProperty -Path $testfile -Name fullname } | Should Not Throw
$output = Get-ItemProperty -Path $testfile -Name fullname
$output.PSPath | Should Not BeNullOrEmpty
$output.PSDrive | Should Be $testprovider
$output.PSProvider.Name | Should Be "FileSystem"
}
It "Should be able to use the gp alias without error" {
{ gp . } | Should Not Throw
{ gp .. } | Should Not Throw
}
It "Should have the same results between alias and cmdlet" {
$alias = gp -Path $testfile -Name fullname
$cmdlet = Get-ItemProperty -Path $testfile -Name fullname
$alias.PSPath | Should Be $cmdlet.PSPath
$alias.PSDrive | Should Be $cmdlet.PSDrive
$alias.PSProvider.Name | Should Be $cmdlet.PSProvider.Name
}
}
@@ -0,0 +1,19 @@
Describe "Get-Location" {
$currentDirectory=[System.IO.Directory]::GetCurrentDirectory()
BeforeEach {
pushd $currentDirectory
}
AfterEach {
popd
}
It "Should list the output of the current working directory" {
(Get-Location).Path | Should Be $currentDirectory
}
It "Should do exactly the same thing as its alias" {
(pwd).Path | Should Be (Get-Location).Path
}
}
@@ -0,0 +1,47 @@
Describe "Get-PSDrive" {
It "Should not throw" {
Get-PSDrive | Should Not BeNullOrEmpty
}
It "Should have a name and a length property" {
(Get-PSDrive).Name | Should Not BeNullOrEmpty
(Get-PSDrive).Root.Length | Should Not BeLessThan 1
}
It "Should be able to be called with the gdr alias" {
{ gdr } | Should Not Throw
gdr | Should Not BeNullOrEmpty
}
It "Should be the same output between Get-PSDrive and gdr" {
$alias = gdr
$actual = Get-PSDrive
$alias | Should Be $actual
}
It "Should return drive info"{
(Get-PSDrive Env).Name | Should Be Env
(Get-PSDrive Cert).Root | Should Be \
if ($IsWindows)
{
(Get-PSDrive C).Provider.Name | Should Be FileSystem
}
else
{
(Get-PSDrive /).Provider.Name | Should Be FileSystem
}
}
It "Should be able to access a drive using the PSProvider switch" {
(Get-PSDrive -PSProvider FileSystem).Name.Length | Should BeGreaterThan 0
}
It "Should return true that a drive that does not exist"{
!(Get-PSDrive fake -ErrorAction SilentlyContinue) | Should Be $True
Get-PSDrive fake -ErrorAction SilentlyContinue | Should BeNullOrEmpty
}
}
@@ -0,0 +1,25 @@
Describe "Get-PSProvider" {
It "Should be able to call with no parameters without error" {
{ Get-PSProvider } | Should Not Throw
}
It "Should be able to call the filesystem provider" {
{ Get-PSProvider FileSystem } | Should Not Throw
$actual = Get-PSProvider FileSystem
$actual.Name | Should Be "FileSystem"
$actual.Capabilities | Should Be "Filter, ShouldProcess, Credentials"
}
It "Should be able to call a provider with a wildcard expression" {
{ Get-PSProvider File*m } | Should Not Throw
}
It "Should be able to pipe the output" {
$actual = Get-PSProvider
{ $actual | Format-List } | Should Not Throw
}
}
@@ -0,0 +1,11 @@
Describe "Get-Process" {
# These tests are no good, please replace!
It "Should return a type of Object[] for Get-Process cmdlet" -Pending:$IsOSX {
(Get-Process).GetType().BaseType | Should Be 'array'
(Get-Process).GetType().Name | Should Be Object[]
}
It "Should have not empty Name flags set for Get-Process object" -Pending:$IsOSX {
Get-Process | foreach-object { $_.Name | Should Not BeNullOrEmpty }
}
}
@@ -0,0 +1,46 @@
Describe "Hierarchical paths" {
BeforeAll {
$data = "Hello World"
Setup -File testFile.txt -Content $data
}
It "should work with Join-Path " {
$testPath = Join-Path $TestDrive testFile.txt
Get-Content $testPath | Should Be $data
}
It "should work with platform's slashes" {
$testPath = "$TestDrive$([IO.Path]::DirectorySeparatorChar)testFile.txt"
Get-Content $testPath | Should Be $data
}
It "should work with forward slashes" {
$testPath = "$TestDrive/testFile.txt"
Get-Content $testPath | Should Be $data
}
It "should work with backward slashes" {
$testPath = "$TestDrive\testFile.txt"
Get-Content $testPath | Should Be $data
}
It "should work with backward slashes for each separator" {
$testPath = "$TestDrive\testFile.txt".Replace("/","\")
Get-Content $testPath | should be $data
}
It "should work with forward slashes for each separator" {
$testPath = "$TestDrive/testFile.txt".Replace("\","/")
Get-Content $testPath | should be $data
}
It "should work even if there are too many forward slashes" {
$testPath = "$TestDrive//////testFile.txt"
Get-Content $testPath | should be $data
}
It "should work even if there are too many backward slashes" {
$testPath = "$TestDrive\\\\\\\testFile.txt"
Get-Content $testPath | should be $data
}
}
@@ -0,0 +1,46 @@
Describe "Join-Path cmdlet tests" -Tags DRT {
$SepChar=[io.path]::DirectorySeparatorChar
BeforeAll {
$StartingLocation = Get-Location
}
AfterEach {
Set-Location $StartingLocation
}
It "should output multiple paths when called with multiple -Path targets" {
Setup -Dir SubDir1
(Join-Path -Path TestDrive:,$TestDrive -ChildPath "SubDir1" -resolve).Length | Should be 2
}
It "should throw 'DriveNotFound' when called with -Resolve and drive does not exist" {
try {Join-Path bogusdrive:\\somedir otherdir -resolve -ea stop; Throw "Previous statement unexpectedly succeeded..."
} catch {$_.FullyQualifiedErrorId | Should Be "DriveNotFound,Microsoft.PowerShell.Commands.JoinPathCommand"}
}
It "should throw 'PathNotFound' when called with -Resolve and item does not exist" {
try {Join-Path "Bogus" "Path" -resolve -ea stop; Throw "Previous statement unexpectedly succeeded..."
} catch {$_.FullyQualifiedErrorId | Should Be "PathNotFound,Microsoft.PowerShell.Commands.JoinPathCommand"}
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 905237)] Note: Result should be the same on non-Windows platforms too
It "should return one object when called with a Windows FileSystem::Redirector" {
set-location ("env:"+$SepChar)
$result=join-path FileSystem::windir system32
$result.Count | Should be 1
$result | Should BeExactly ("FileSystem::windir"+$SepChar+"system32")
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 913084)]
It "should be able to join-path special string 'Variable:' with 'foo'" {
$result=Join-Path "Variable:" "foo"
$result.Count | Should be 1
$result | Should BeExactly ("Variable:"+$SepChar+"foo")
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 913084)]
It "should be able to join-path special string 'Alias:' with 'foo'" {
$result=Join-Path "Alias:" "foo"
$result.Count | Should be 1
$result | Should BeExactly ("Alias:"+$SepChar+"foo")
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 913084)]
It "should be able to join-path special string 'Env:' with 'foo'" {
$result=Join-Path "Env:" "foo"
$result.Count | Should be 1
$result | Should BeExactly ("Env:"+$SepChar+"foo")
}
}
@@ -0,0 +1,47 @@
if ($IsWindows) {
#check to see whether we're running as admin in Windows...
$windowsIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
$windowsPrincipal = new-object 'Security.Principal.WindowsPrincipal' $windowsIdentity
if ($windowsPrincipal.IsInRole("Administrators") -eq $true) {
$NonWinAdmin=$false
} else {$NonWinAdmin=$true}
Describe "New-EventLog cmdlet tests" -Tags DRT {
BeforeEach {
Remove-EventLog -LogName TestLog -ea Ignore
}
It "should be able to create a New-EventLog with a -Source paramter" -Skip:($True -Or $NonWinAdmin) {
{New-EventLog -LogName TestLog -Source TestSource -ea stop} | Should Not Throw
{Write-EventLog -LogName TestLog -Source TestSource -Message "Test" -EventID 1 -ea stop} | Should Not Throw
$result=Get-EventLog -LogName TestLog
$result.Count | Should be 1
}
It "should be able to create a New-EventLog with a -ComputerName paramter" -Skip:($True -Or $NonWinAdmin) {
{New-EventLog -LogName TestLog -Source TestSource -ComputerName $env:COMPUTERNAME -ea stop} | Should Not Throw
{Write-EventLog -LogName TestLog -Source TestSource -Message "Test" -EventID 1 -ea stop} | Should Not Throw
$result=Get-EventLog -LogName TestLog
$result.Count | Should be 1
$result.EventID | Should be 1
}
It "should be able to create a New-EventLog with a -CategoryResourceFile paramter" -Skip:($True -Or $NonWinAdmin) {
{New-EventLog -LogName TestLog -Source TestSource -CategoryResourceFile "CategoryMessageFile" -ea stop} | Should Not Throw
{Write-EventLog -LogName TestLog -Source TestSource -Message "Test" -EventID 2 -ea stop} | Should Not Throw
$result=Get-EventLog -LogName TestLog
$result.Count | Should be 1
$result.EventID | Should be 2
}
It "should be able to create a New-EventLog with a -MessageResourceFile paramter" -Skip:($True -Or $NonWinAdmin) {
{New-EventLog -LogName TestLog -Source TestSource -MessageResourceFile "ResourceMessageFile" -ea stop} | Should Not Throw
{Write-EventLog -LogName TestLog -Source TestSource -Message "Test" -EventID 3 -ea stop} | Should Not Throw
$result=Get-EventLog -LogName TestLog
$result.Count | Should be 1
$result.EventID | Should be 3
}
It "should be able to create a New-EventLog with a -ParameterResourceFile paramter" -Skip:($True -Or $NonWinAdmin) {
{New-EventLog -LogName TestLog -Source TestSource -ParameterResourceFile "ParameterMessageFile" -ea stop} | Should Not Throw
{Write-EventLog -LogName TestLog -Source TestSource -Message "Test" -EventID 4 -ea stop} | Should Not Throw
$result=Get-EventLog -LogName TestLog
$result.Count | Should be 1
$result.EventID | Should be 4
}
}
}
@@ -0,0 +1,159 @@
function Clean-State
{
if (Test-Path $FullyQualifiedLink)
{
Remove-Item $FullyQualifiedLink -Force
}
if (Test-Path $FullyQualifiedFile)
{
Remove-Item $FullyQualifiedFile -Force
}
if (Test-Path $FullyQualifiedFolder)
{
Remove-Item $FullyQualifiedFolder -Force
}
}
Describe "New-Item" {
$tmpDirectory = $TestDrive
$testfile = "testfile.txt"
$testfolder = "newDirectory"
$testlink = "testlink"
$FullyQualifiedFile = Join-Path -Path $tmpDirectory -ChildPath $testfile
$FullyQualifiedFolder = Join-Path -Path $tmpDirectory -ChildPath $testfolder
$FullyQualifiedLink = Join-Path -Path $tmpDirectory -ChildPath $testlink
BeforeEach {
Clean-State
}
It "should call the function without error" {
{ New-Item -Name $testfile -Path $tmpDirectory -ItemType file } | Should Not Throw
}
It "Should create a file without error" {
New-Item -Name $testfile -Path $tmpDirectory -ItemType file
Test-Path $FullyQualifiedFile | Should Be $true
$fileInfo = Get-ChildItem $FullyQualifiedFile
$fileInfo.Target | Should Be $null
$fileInfo.LinkType | Should Be $null
}
It "Should create a folder without an error" {
New-Item -Name newDirectory -Path $tmpDirectory -ItemType directory
Test-Path $FullyQualifiedFolder | Should Be $true
}
It "Should create a file using the ni alias" {
ni -Name $testfile -Path $tmpDirectory -ItemType file
Test-Path $FullyQualifiedFile | Should Be $true
}
It "Should create a file using the Type alias instead of ItemType" {
New-Item -Name $testfile -Path $tmpDirectory -Type file
Test-Path $FullyQualifiedFile | Should Be $true
}
It "Should create a file with sample text inside the file using the Value switch" {
$expected = "This is test string"
New-Item -Name $testfile -Path $tmpDirectory -ItemType file -Value $expected
Test-Path $FullyQualifiedFile | Should Be $true
Get-Content $FullyQualifiedFile | Should Be $expected
}
It "Should not create a file when the Name switch is not used and only a directory specified" {
#errorAction used because permissions issue in Windows
New-Item -Path $tmpDirectory -ItemType file -ErrorAction SilentlyContinue
Test-Path $FullyQualifiedFile | Should Be $false
}
It "Should create a file when the Name switch is not used but a fully qualified path is specified" {
New-Item -Path $FullyQualifiedFile -ItemType file
Test-Path $FullyQualifiedFile | Should Be $true
}
It "Should be able to create a multiple items in different directories" {
$FullyQualifiedFile2 = Join-Path -Path $tmpDirectory -ChildPath test2.txt
New-Item -ItemType file -Path $FullyQualifiedFile, $FullyQualifiedFile2
Test-Path $FullyQualifiedFile | Should Be $true
Test-Path $FullyQualifiedFile2 | Should Be $true
Remove-Item $FullyQualifiedFile2
}
It "Should be able to call the whatif switch without error" {
{ New-Item -Name testfile.txt -Path $tmpDirectory -ItemType file -WhatIf } | Should Not Throw
}
It "Should not create a new file when the whatif switch is used" {
New-Item -Name $testfile -Path $tmpDirectory -ItemType file -WhatIf
Test-Path $FullyQualifiedFile | Should Be $false
}
It "Should create a symbolic link of a file without error" {
New-Item -Name $testfile -Path $tmpDirectory -ItemType file
Test-Path $FullyQualifiedFile | Should Be $true
New-Item -ItemType SymbolicLink -Target $FullyQualifiedFile -Name $testlink -Path $tmpDirectory
Test-Path $FullyQualifiedLink | Should Be $true
$fileInfo = Get-ChildItem $FullyQualifiedLink
$fileInfo.Target | Should Be $FullyQualifiedFile
$fileInfo.LinkType | Should Be "SymbolicLink"
}
It "Should create a symbolic link to a non-existing file without error" {
$target = Join-Path $tmpDirectory "totallyBogusFile"
New-Item -ItemType SymbolicLink -Target $target -Name $testlink -Path $tmpDirectory
Test-Path $FullyQualifiedLink | Should Be $true
$fileInfo = Get-ChildItem $FullyQualifiedLink
$fileInfo.Target | Should Be $target
Test-Path $fileInfo.Target | Should be $false
$fileInfo.LinkType | Should Be "SymbolicLink"
}
It "Should create a symbolic link from directory without error" {
New-Item -Name $testFolder -Path $tmpDirectory -ItemType directory
Test-Path $FullyQualifiedFolder | Should Be $true
New-Item -ItemType SymbolicLink -Target $FullyQualifiedFolder -Name $testlink -Path $tmpDirectory
Test-Path $FullyQualifiedLink | Should Be $true
$fileInfo = Get-ChildItem $FullyQualifiedLink
$fileInfo.Target | Should Be $FullyQualifiedFolder
$fileInfo.LinkType | Should Be "SymbolicLink"
# Remove the link explicitly to avoid broken symlink issue
Remove-Item $FullyQualifiedLink -Force
}
It "Should create a hard link of a file without error" {
New-Item -Name $testfile -Path $tmpDirectory -ItemType file
Test-Path $FullyQualifiedFile | Should Be $true
New-Item -ItemType HardLink -Target $FullyQualifiedFile -Name $testlink -Path $tmpDirectory
Test-Path $FullyQualifiedLink | Should Be $true
$fileInfo = Get-ChildItem $FullyQualifiedLink
$fileInfo.Target | Should Be $null
$fileInfo.LinkType | Should Be "HardLink"
}
}
@@ -0,0 +1,28 @@
Describe "Pop-Location" {
$startDirectory = $(Get-Location).Path
BeforeEach { Set-Location $startDirectory }
It "Should be able to be called without error" {
{ Pop-Location } | Should Not Throw
}
It "Should not take a parameter" {
{ Pop-Location .. } | Should Throw
}
It "Should be able pop multiple times" {
Push-Location ..
Push-Location ..
Push-Location ..
Pop-Location
Pop-Location
Pop-Location
$(Get-Location).Path | Should Be $startDirectory
}
Set-Location $startDirectory
}
@@ -0,0 +1,55 @@
Describe "Test-Push-Location" {
New-Variable -Name startDirectory -Value $(Get-Location).Path -Scope Global -Force
BeforeEach { cd $startDirectory }
It "Should be called without error" {
{ Push-Location } | Should Not Throw
}
It "Should be able to push to the root directory" {
# this works cross-platform
{ Push-Location / } | Should Not Throw
}
It "Should be able to use relative path to parent" {
{ Push-Location .. } | Should Not Throw
}
It "Should be able to use relative path to grandparent" {
Test-Path ../.. | Should Be $true
{ Push-Location ../.. } | Should Not Throw
}
It "Should be able to push twice" {
{ Push-Location .. } | Should Not Throw
{ Push-Location .. } | Should Not Throw
}
It "Should be able to take a piped variable" {
{ ".." | Push-Location } | Should Not Throw
}
It "Should be able to call the pushd alias" {
{ pushd } | Should Not Throw
}
It "Should be able to push to the same location between the alias and the cmdlet" {
pushd ..
$aliasDirectory = $(Get-Location).Path
cd $startDirectory
Push-Location ..
$cmdletDirectory = $(Get-Location).Path
$aliasDirectory | Should Be $cmdletDirectory
}
It "Should produce a pathinfo object when the passthru parameter is used" {
Push-Location .. -PassThru | ForEach-Object { $_.GetType().Name | Should Be PathInfo }
}
# final cleanup
cd $startDirectory
}
@@ -0,0 +1,31 @@
if ($IsWindows) {
#check to see whether we're running as admin in Windows...
$windowsIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
$windowsPrincipal = new-object 'Security.Principal.WindowsPrincipal' $windowsIdentity
if ($windowsPrincipal.IsInRole("Administrators") -eq $true) {
$NonWinAdmin=$false
} else {$NonWinAdmin=$true}
Describe "New-EventLog cmdlet tests" -Tags DRT {
BeforeEach{
Remove-EventLog -LogName TestLog -ea Ignore
{New-EventLog -LogName TestLog -Source TestSource -ea Stop} | Should Not Throw
{Write-EventLog -LogName TestLog -Source TestSource -Message "Test" -EventID 1 -ea Stop} | Should Not Throw
}
#CmdLet is NYI - change to -Skip:($NonWinAdmin) when implemented
It "should be able to Remove-EventLog -LogName <string> -ComputerName <string>" -Pending:($True -Or $NonWinAdmin) {
{Remove-EventLog -LogName TestLog -ComputerName $env:COMPUTERNAME -ea Stop} | Should Not Throw
try {Write-EventLog -LogName TestLog -Source TestSource -Message "Test" -EventID 1 -ea Stop; Throw "Previous statement unexpectedly succeeded..."
} catch {$_.FullyQualifiedErrorId | Should Be "Microsoft.PowerShell.Commands.WriteEventLogCommand"}
try {Get-EventLog -LogName TestLog -ea Stop; Throw "Previous statement unexpectedly succeeded..."
} catch {$_.FullyQualifiedErrorId | Should Be "System.InvalidOperationException,Microsoft.PowerShell.Commands.GetEventLogCommand"}
}
#CmdLet is NYI - change to -Skip:($NonWinAdmin) when implemented
It "should be able to Remove-EventLog -Source <string> -ComputerName <string>" -Pending:($True -Or $NonWinAdmin) {
{Remove-EventLog -Source TestSource -ComputerName $env:COMPUTERNAME -ea Stop} | Should Not Throw
try {Write-EventLog -LogName TestLog -Source TestSource -Message "Test" -EventID 1 -ea Stop; Throw "Previous statement unexpectedly succeeded..."
} catch {$_.FullyQualifiedErrorId | Should Be "Microsoft.PowerShell.Commands.WriteEventLogCommand"}
try {Get-EventLog -LogName TestLog -ea Stop; Throw "Previous statement unexpectedly succeeded..."
} catch {$_.FullyQualifiedErrorId | Should Be "System.InvalidOperationException,Microsoft.PowerShell.Commands.GetEventLogCommand"}
}
}
}
@@ -0,0 +1,139 @@
Describe "Remove-Item" {
$testpath = $TestDrive
$testfile = "testfile.txt"
$testfilepath = Join-Path -Path $testpath -ChildPath $testfile
Context "File removal Tests" {
BeforeEach {
New-Item -Name $testfile -Path $testpath -ItemType "file" -Value "lorem ipsum" -Force
Test-Path $testfilepath | Should Be $true
}
It "Should be able to be called on a regular file without error using the Path switch" {
{ Remove-Item -Path $testfilepath } | Should Not Throw
Test-Path $testfilepath | Should Be $false
}
It "Should be able to be called on a file without the Path switch" {
{ Remove-Item $testfilepath } | Should Not Throw
Test-Path $testfilepath | Should Be $false
}
It "Should be able to call the rm alias" {
{ rm $testfilepath } | Should Not Throw
Test-Path $testfilepath | Should Be $false
}
It "Should be able to call the del alias" {
{ del $testfilepath } | Should Not Throw
Test-Path $testfilepath | Should Be $false
}
It "Should be able to call the erase alias" {
{ erase $testfilepath } | Should Not Throw
Test-Path $testfilepath | Should Be $false
}
It "Should be able to call the ri alias" {
{ ri $testfilepath } | Should Not Throw
Test-Path $testfilepath | Should Be $false
}
It "Should not be able to remove a read-only document without using the force switch" {
# Set to read only
Set-ItemProperty -Path $testfilepath -Name IsReadOnly -Value $true
# attempt to remove the file
{ Remove-Item $testfilepath -ErrorAction SilentlyContinue } | Should Not Throw
# validate
Test-Path $testfilepath | Should Be $true
# remove using the -force switch on the readonly object
Remove-Item $testfilepath -Force
# Validate
Test-Path $testfilepath | Should Be $false
}
It "Should be able to remove all files matching a regular expression with the include switch" {
# Create multiple files with specific string
New-Item -Name file1.txt -Path $testpath -ItemType "file" -Value "lorem ipsum"
New-Item -Name file2.txt -Path $testpath -ItemType "file" -Value "lorem ipsum"
New-Item -Name file3.txt -Path $testpath -ItemType "file" -Value "lorem ipsum"
# Create a single file that does not match that string - already done in BeforeEach
# Delete the specific string
Remove-Item (Join-Path -Path $testpath -ChildPath "*") -Include file*.txt
# validate that the string under test was deleted, and the nonmatching strings still exist
Test-path (Join-Path -Path $testpath -ChildPath file1.txt) | Should Be $false
Test-path (Join-Path -Path $testpath -ChildPath file2.txt) | Should Be $false
Test-path (Join-Path -Path $testpath -ChildPath file3.txt) | Should Be $false
Test-Path $testfilepath | Should Be $true
# Delete the non-matching strings
Remove-Item $testfilepath
Test-Path $testfilepath | Should Be $false
}
It "Should be able to not remove any files matching a regular expression with the exclude switch" {
# Create multiple files with specific string
New-Item -Name file1.wav -Path $testpath -ItemType "file" -Value "lorem ipsum"
New-Item -Name file2.wav -Path $testpath -ItemType "file" -Value "lorem ipsum"
# Create a single file that does not match that string
New-Item -Name file1.txt -Path $testpath -ItemType "file" -Value "lorem ipsum"
# Delete the specific string
Remove-Item (Join-Path -Path $testpath -ChildPath "file*") -Exclude *.wav -Include *.txt
# validate that the string under test was deleted, and the nonmatching strings still exist
Test-Path (Join-Path -Path $testpath -ChildPath file1.wav) | Should Be $true
Test-Path (Join-Path -Path $testpath -ChildPath file2.wav) | Should Be $true
Test-Path (Join-Path -Path $testpath -ChildPath file1.txt) | Should Be $false
# Delete the non-matching strings
Remove-Item (Join-Path -Path $testpath -ChildPath file1.wav)
Remove-Item (Join-Path -Path $testpath -ChildPath file2.wav)
Test-Path (Join-Path -Path $testpath -ChildPath file1.wav) | Should Be $false
Test-Path (Join-Path -Path $testpath -ChildPath file2.wav) | Should Be $false
}
}
Context "Directory Removal Tests" {
$testdirectory = Join-Path -Path $testpath -ChildPath testdir
$testsubdirectory = Join-Path -Path $testdirectory -ChildPath subd
BeforeEach {
New-Item -Name "testdir" -Path $testpath -ItemType "directory" -Force
Test-Path $testdirectory | Should Be $true
}
It "Should be able to remove a directory" {
{ Remove-Item $testdirectory } | Should Not Throw
Test-Path $testdirectory | Should Be $false
}
It "Should be able to recursively delete subfolders" {
New-Item -Name "subd" -Path $testdirectory -ItemType "directory"
New-Item -Name $testfile -Path $testsubdirectory -ItemType "file" -Value "lorem ipsum"
$complexDirectory = Join-Path -Path $testsubdirectory -ChildPath $testfile
test-path $complexDirectory | Should Be $true
{ Remove-Item $testdirectory -Recurse} | Should Not Throw
Test-Path $testdirectory | Should Be $false
}
}
}
@@ -0,0 +1,51 @@
Describe "Set-Content cmdlet tests" -Tags:DRT {
$file1 = "file1.txt"
Setup -File "$file1" -Content $file1
Context "Set-Content should actually set content" {
It "should set-Content of testdrive:\$file1" {
$result=set-content -path testdrive:\$file1 -value "ExpectedContent" -passthru
$result| Should be "ExpectedContent"
}
It "should return expected string from testdrive:\$file1" {
$result = get-content -path testdrive:\$file1
$result | Should BeExactly "ExpectedContent"
}
It "should Set-Content to testdrive:\dynamicfile.txt with dynamic parameters" -Pending:($IsLinux -Or $IsOSX) {#https://github.com/PowerShell/PowerShell/issues/891
$result=set-content -path testdrive:\dynamicfile.txt -value "ExpectedContent" -passthru
$result| Should BeExactly "ExpectedContent"
}
It "should return expected string from testdrive:\dynamicfile.txt" -Pending:($IsLinux -Or $IsOSX) {#https://github.com/PowerShell/PowerShell/issues/891
$result = get-content -path testdrive:\dynamicfile.txt
$result | Should BeExactly "ExpectedContent"
}
It "should remove existing content from testdrive:\$file1 when the -Value is `$null" {
$AsItWas=get-content testdrive:\$file1
$AsItWas |Should BeExactly "ExpectedContent"
{set-content -path testdrive:\$file1 -value $null -ea stop} | Should Not Throw
$AsItIs=get-content testdrive:\$file1
$AsItIs| Should Not Be $AsItWas
}
It "should throw 'ParameterArgumentValidationErrorNullNotAllowed' when -Path is `$null" {
Try {set-content -path $null -value "ShouldNotWorkBecausePathIsNull" -ea stop; Throw "Previous statement unexpectedly succeeded..."
} Catch {$_.FullyQualifiedErrorId | Should Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.SetContentCommand"}
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 903880)]
It "should throw 'ParameterArgumentValidationErrorNullNotAllowed' when -Path is `$()" {
Try {set-content -path $() -value "ShouldNotWorkBecausePathIsInvalid" -ea stop; Throw "Previous statement unexpectedly succeeded..."
} Catch {$_.FullyQualifiedErrorId | Should Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.SetContentCommand"}
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 906022)]
It "should throw 'PSNotSupportedException' when you set-content to an unsupported provider" -Skip:($IsLinux -Or $IsOSX) {
Try {set-content -path HKLM:\\software\\microsoft -value "ShouldNotWorkBecausePathIsUnsupported" -ea stop; Throw "Previous statement unexpectedly succeeded..."
} Catch {$_.FullyQualifiedErrorId | Should Be "NotSupported,Microsoft.PowerShell.Commands.SetContentCommand"}
}
#[BugId(BugDatabase.WindowsOutOfBandReleases, 9058182)]
It "should be able to pass multiple [string]`$objects to Set-Content through the pipeline to output a dynamic Path file" -Pending:($IsLinux -Or $IsOSX) {#https://github.com/PowerShell/PowerShell/issues/891
"hello","world"|set-content testdrive:\dynamicfile2.txt
$result=get-content testdrive:\dynamicfile2.txt
$result.length |Should be 2
$result[0] |Should be "hello"
$result[1] |Should be "world"
}
}
}
@@ -0,0 +1,67 @@
Describe "Set-Location" {
$startDirectory = Get-Location
if ($IsWindows)
{
$target = "C:\"
}
else
{
$target = "/"
}
It "Should be able to be called without error" {
{ Set-Location $target } | Should Not Throw
}
It "Should be able to be called on different providers" {
{ Set-Location alias: } | Should Not Throw
{ Set-Location env: } | Should Not Throw
}
It "Should be able use the cd alias without error" {
{ cd $target } | Should Not Throw
}
It "Should be able to use the chdir alias without error" {
{ chdir $target } | Should Not Throw
}
It "Should be able to use the sl alias without error" {
{ sl $target } | Should Not Throw
}
It "Should have the correct current location when using the set-location cmdlet" {
Set-Location $startDirectory
$(Get-Location).Path | Should Be $startDirectory.Path
}
It "Should have the correct current location when using the cd alias" {
cd $target
$(Get-Location).Path | Should Be $target
}
It "Should have the correct current location when using the chdir alias" {
chdir $target
$(Get-Location).Path | Should Be $target
}
It "Should have the correct current location when using the chdir alias" {
sl $target
$(Get-Location).Path | Should Be $target
}
It "Should be able to use the Path switch" {
{ Set-Location -Path $target } | Should Not Throw
}
It "Should generate a pathinfo object when using the Passthru switch" {
$(Set-Location $target -PassThru).GetType().Name | Should Be PathInfo
}
Set-Location $startDirectory
}
@@ -0,0 +1,106 @@
Describe "Split-Path" {
if ($IsWindows)
{
$qualifier = "C:"
}
else
{
$qualifier = "/"
}
It "Should return a string object when invoked" {
( Split-Path . ).GetType().Name | Should Be "String"
( Split-Path . -Leaf ).GetType().Name | Should Be "String"
( Split-Path . -Resolve ).GetType().Name | Should Be "String"
}
It "Should return the name of the drive when the qualifier switch is used" {
Split-Path $qualifier -Qualifier | Should Be "$qualifier"
Split-Path ${qualifier}usr/bin -Qualifier | Should Be "$qualifier"
}
It "Should error when using the qualifier switch for a Windows path while on a non-Windows machine" {
# ErrorAction SilentlyContinue merely suppresses the error from the console.
# Throwing exceptions still seen by Pester.
if ($qualifier -eq "/")
{
Split-Path "C:\Users" -Qualifier -ErrorAction SilentlyContinue | Should Throw
}
else
{
Split-Path "/Users" -Qualifier -ErrorAction SilentlyContinue | Should Throw
}
}
It "Should error when no directory separator characters are used with a qualifier" {
Split-Path "abadTest" -Qualifier -ErrorAction SilentlyContinue | Should Throw
}
It "Should return the path when the noqualifier switch is used on a Linux system" {
{ Split-Path ${qualifier}usr/bin -NoQualifier } | Should Not Throw
if ($IsWindows)
{
Split-Path ${qualifier}usr/bin -NoQualifier | Should Be "usr/bin"
}
else
{
Split-Path ${qualifier}usr/bin -NoQualifier | Should Be "/usr/bin"
}
}
It "Should return the base name when the leaf switch is used" {
Split-Path ${qualifier}usr/bin -Leaf | Should be "bin"
Split-Path ${qualifier}usr/local/bin -Leaf | Should be "bin"
Split-Path usr/bin -Leaf | Should be "bin"
Split-Path ./bin -Leaf | Should be "bin"
Split-Path bin -Leaf | Should be "bin"
}
It "Should be able to accept regular expression input and output an array for multiple objects" {
$testDir = $TestDrive
$testFile1 = "testfile1.ps1"
$testFile2 = "testfile2.ps1"
$testFilePath1 = Join-Path -Path $testDir -ChildPath $testFile1
$testFilePath2 = Join-Path -Path $testDir -ChildPath $testFile2
New-Item -ItemType file -Path $testFilePath1, $testFilePath2 -Force
Test-Path $testFilePath1 | Should Be $true
Test-Path $testFilePath2 | Should Be $true
$actual = ( Split-Path (Join-Path -Path $testDir -ChildPath "*file*.ps1") -Leaf -Resolve ) | Sort-Object
$actual.GetType().BaseType.Name | Should Be "Array"
$actual[0] | Should Be $testFile1
$actual[1] | Should Be $testFile2
}
It "Should be able to tell if a given path is an absolute path" {
( Split-Path ${qualifier}usr/bin -IsAbsolute ) | Should be $true
( Split-Path .. -IsAbsolute ) | Should be $false
( Split-Path ${qualifier}usr/.. -IsAbsolute ) | Should be $true
( Split-Path ${qualifier}usr/../ -IsAbsolute ) | Should be $true
( Split-Path ../ -IsAbsolute ) | Should be $false
( Split-Path . -IsAbsolute ) | Should be $false
( Split-Path ~/ -IsAbsolute ) | Should be $false
( Split-Path ~/.. -IsAbsolute ) | Should be $false
( Split-Path ~/../.. -IsAbsolute ) | Should be $false
}
It "Should support piping" {
$path = "${qualifier}usr/bin"
( $path | Split-Path ) | Should Be "${qualifier}usr"
}
It "Should return the path up to the parent of the directory when Parent switch is used" {
Split-Path "${qualifier}usr/bin" -Parent | Should Be "${qualifier}usr"
Split-Path "${qualifier}usr/local/bin" -Parent | Should Be $(Join-Path "${qualifier}usr" -ChildPath "local")
Split-Path "usr/local/bin" -Parent | Should Be $(Join-Path "usr" -ChildPath "local")
}
It "Should throw if a parameterSetName is incorrect" {
{ Split-Path "${qualifier}usr/bin/" -Parentaoeu } | Should Throw "A parameter cannot be found that matches parameter name"
}
}
@@ -0,0 +1,73 @@
Describe "Start-Process" {
$pingCommand = (Get-Command -CommandType Application ping)[0].Definition
$pingDirectory = Split-Path $pingCommand -Parent
$tempFile = Join-Path -Path $TestDrive -ChildPath PSTest
$assetsFile = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath assets) -ChildPath SortTest.txt
if ($IsWindows) {
$pingParam = "-n 2 localhost"
}
elseif ($IsLinux -Or $IsOSX) {
$pingParam = "-c 2 localhost"
}
# Note that ProcessName may still be `powershell` due to dotnet/corefx#5378
# This has been fixed on Linux, but not on OS X
It "Should process arguments without error" {
$process = Start-Process ping -ArgumentList $pingParam -PassThru
$process.Length | Should Be 1
$process.Id | Should BeGreaterThan 1
# $process.ProcessName | Should Be "ping"
}
It "Should work correctly when used with full path name" {
$process = Start-Process $pingCommand -ArgumentList $pingParam -PassThru
$process.Length | Should Be 1
$process.Id | Should BeGreaterThan 1
# $process.ProcessName | Should Be "ping"
}
It "Should invoke correct path when used with FilePath argument" {
$process = Start-Process -FilePath $pingCommand -ArgumentList $pingParam -PassThru
$process.Length | Should Be 1
$process.Id | Should BeGreaterThan 1
# $process.ProcessName | Should Be "ping"
}
It "Should wait for command completion if used with Wait argument" {
$process = Start-Process ping -ArgumentList $pingParam -Wait -PassThru
}
It "Should work correctly with WorkingDirectory argument" {
$process = Start-Process ping -WorkingDirectory $pingDirectory -ArgumentList $pingParam -PassThru
$process.Length | Should Be 1
$process.Id | Should BeGreaterThan 1
# $process.ProcessName | Should Be "ping"
}
It "Should should handle stderr redirection without error" {
$process = Start-Process ping -ArgumentList $pingParam -PassThru -RedirectStandardError $tempFile
$process.Length | Should Be 1
$process.Id | Should BeGreaterThan 1
# $process.ProcessName | Should Be "ping"
}
It "Should should handle stdout redirection without error" {
$process = Start-Process ping -ArgumentList $pingParam -Wait -RedirectStandardOutput $tempFile
$dirEntry = dir $tempFile
$dirEntry.Length | Should BeGreaterThan 0
}
It "Should should handle stdin redirection without error" {
$process = Start-Process sort -Wait -RedirectStandardOutput $tempFile -RedirectStandardInput $assetsFile
$dirEntry = dir $tempFile
$dirEntry.Length | Should BeGreaterThan 0
}
Remove-Item -Path $tempFile -Force
}
@@ -0,0 +1,122 @@
Describe "Test-Path" {
BeforeAll {
$testdirectory = $TestDrive
$testfilename = New-Item -path $testdirectory -Name testfile.txt -ItemType file -Value 1 -force
# populate with additional files
New-Item -Path $testdirectory -Name datestfile -value 1 -ItemType file | Out-Null
New-Item -Path $testdirectory -Name gatestfile -value 1 -ItemType file | Out-Null
New-Item -Path $testdirectory -Name usr -value 1 -ItemType directory | Out-Null
$nonExistantDir = Join-Path -Path (Join-Path -Path $testdirectory -ChildPath usr) -ChildPath bin
$nonExistantPath = Join-Path -Path (Join-Path -Path (Join-Path -Path $testdirectory -ChildPath usr) -ChildPath bin) -ChildPath error
}
It "Should be called on an existing path without error" {
{ Test-Path $testdirectory } | Should Not Throw
{ Test-Path -Path $testdirectory } | Should Not Throw
{ Test-Path -LiteralPath $testdirectory } | Should Not Throw
}
It "Should allow piping objects to it" {
{ $testdirectory | Test-Path } | Should Not Throw
$testdirectory | Test-Path | Should Be $true
$nonExistantDir | Test-Path | Should Be $false
}
It "Should be called on a nonexistant path without error" {
{ Test-Path -Path $nonExistantPath } | Should Not Throw
}
It "Should return false for a nonexistant path" {
Test-Path -Path $nonExistantPath | Should Be $false
}
It "Should return true for an existing path" {
{ Test-Path -Path $testdirectory } | Should Be $true
}
It "Should be able to accept a regular expression" {
{ Test-Path -Path (Join-Path -Path $testdirectory -ChildPath "u*") } | Should Not Throw
{ Test-Path -Path (Join-Path -Path $testdirectory -ChildPath "u[a-z]r") } | Should Not Throw
}
It "Should be able to return the correct result when a regular expression is used" {
Test-Path -Path (Join-Path -Path $testdirectory -ChildPath "u*") | Should Be $true
Test-Path -Path (Join-Path -Path $testdirectory -ChildPath "u[a-z]*") | Should Be $true
Test-Path -Path (Join-Path -Path $testdirectory -ChildPath "aoeu*") | Should Be $false
Test-Path -Path (Join-Path -Path $testdirectory -ChildPath "u[A-Z]") | Should Be $false
}
It "Should return false when the Leaf pathtype is used on a directory" {
Test-Path -Path $testdirectory -PathType Leaf | Should Be $false
}
It "Should return true when the Leaf pathtype is used on an existing endpoint" {
Test-Path -Path $testfilename -PathType Leaf | Should Be $true
}
It "Should return false when the Leaf pathtype is used on a nonexistant file" {
Test-Path -Path "aoeu" -PathType Leaf | Should Be $false
}
It "Should return true when the Leaf pathtype is used on a file using the Type alias instead of PathType" {
Test-Path -Path $testfilename -Type Leaf | Should Be $true
}
It "Should be able to search multiple regular expressions using the include switch" {
{ Test-Path -Path (Join-Path -Path $testdirectory -ChildPath "*") -Include t* } | Should Be $true
}
It "Should be able to exclude a regular expression using the exclude switch" {
{ Test-Path -Path (Join-Path -Path $testdirectory -ChildPath "*") -Exclude v* } | Should Be $true
}
It "Should be able to exclude multiple regular expressions using the exclude switch" {
# tests whether there's any files in the usr directory that don't start with 'd' or 'g'
{ Test-Path -Path $testfilename -Exclude d*, g* } | Should Be $true
}
It "Should return true if the syntax of the path is correct when using the IsValid switch" {
{ Test-Path -Path $nonExistantPath -IsValid } | Should Be $true
}
It "Should return false if the syntax of the path is incorrect when using the IsValid switch" {
$badPath = " :;!@#$%^&*(){}?+|_-"
Test-Path -Path $badPath -IsValid | Should Be $false
}
It "Should return true on paths containing spaces when the path is surrounded in quotes" {
Test-Path -Path "/totally a valid/path" -IsValid | Should Be $true
}
It "Should throw on paths containing spaces when the path is not surrounded in quotes" {
{ Test-Path -Path /a path/without quotes/around/it -IsValid } | Should Throw
}
It "Should return true if a directory leads or trails with a space when surrounded by quotes" {
Test-Path -Path "/a path / with/funkyspaces" -IsValid | Should Be $true
}
It "Should return true on a valid path when the LiteralPath switch is used" {
Test-Path -LiteralPath $testfilename | Should Be $true
}
It "Should return false if regular expressions are used with the LiteralPath switch" {
Test-Path -LiteralPath (Join-Path -Path $testdirectory -ChildPath "u*") | Should Be $false
Test-Path -LiteralPath (Join-Path -Path $testdirectory -ChildPath "u[a-z]r") | Should Be $false
}
It "Should return false if regular expressions are used with the LiteralPath alias PSPath switch" {
Test-Path -PSPath (Join-Path -Path $testdirectory -ChildPath "u*") | Should Be $false
Test-Path -PSPath (Join-Path -Path $testdirectory -ChildPath "u[a-z]r") | Should Be $false
}
It "Should return true if used on components other than filesystem objects" {
Test-Path Alias:\gci | Should Be $true
Test-Path Env:\PATH | Should Be $true
}
}
@@ -0,0 +1,5 @@
5
10
3
4
8
@@ -0,0 +1,24 @@
Describe "ExecutionPolicy" {
Context "Check Get-ExecutionPolicy behavior" {
It "Should throw PlatformNotSupported when not on Windows" -Skip:$IsWindows {
{ Get-ExecutionPolicy } | Should Throw "Operation is not supported on this platform."
}
It "Should return Microsoft.Powershell.ExecutionPolicy PSObject on Windows" -Skip:($IsLinux -Or $IsOSX) {
(Get-ExecutionPolicy).GetType() | Should Be Microsoft.Powershell.ExecutionPolicy
}
}
Context "Check Set-ExecutionPolicy behavior" {
It "Should throw PlatformNotSupported when not on Windows" -Skip:$IsWindows {
{ Set-ExecutionPolicy Unrestricted } | Should Throw "Operation is not supported on this platform."
}
It "Should succeed on Windows" -Skip:($IsLinux -Or $IsOSX) {
# We use the Process scope to avoid affecting the system
# Unrestricted is assumed "safe", otherwise these tests would not be running
{ Set-ExecutionPolicy -Force -Scope Process -ExecutionPolicy Unrestricted } | Should Not Throw
}
}
}
@@ -0,0 +1,299 @@
Describe "Add-Member DRT Unit Tests" -Tags DRT{
It "Mandatory parameters should not be null nor empty" {
# when Name is null
try
{
Add-Member -Name $null
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.AddMemberCommand"
}
# when Name is empty
try
{
Add-Member -Name ""
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.AddMemberCommand"
}
# when MemberType is null
try
{
Add-Member -MemberType $null
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.AddMemberCommand"
}
# when MemberType is empty
try
{
Add-Member -MemberType ""
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.AddMemberCommand"
}
# when InputObject is null
try
{
Add-Member -InputObject $null
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.AddMemberCommand"
}
}
# It only support on AliasProperty, ScriptProperty, CodeProperty and CodeMethod
It "Should Not Have Value2" {
$memberTypesWhereV1CannotBeNull = "CodeMethod", "MemberSet", "PropertySet", "ScriptMethod", "NoteProperty"
foreach ($memberType in $memberTypesWhereV1CannotBeNull)
{
try
{
Add-Member -InputObject a -memberType $memberType -Name Name -Value something -SecondValue somethingElse
Throw "Execution OK"
}
catch{
$_.FullyQualifiedErrorId | Should Be "Value2ShouldNotBeSpecified,Microsoft.PowerShell.Commands.AddMemberCommand"
}
}
}
It "Cannot Add PS Property Or PS Method" {
$membersYouCannotAdd = "Method", "Property", "ParameterizedProperty"
foreach ($member in $membersYouCannotAdd)
{
try
{
Add-Member -InputObject a -memberType $member -Name Name
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "CannotAddMemberType,Microsoft.PowerShell.Commands.AddMemberCommand"
}
}
try
{
Add-Member -InputObject a -memberType AnythingElse -Name Name
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.AddMemberCommand"
}
}
It "Value1 And Value2 Should Not Both Null" {
$memberTypes = "CodeProperty", "ScriptProperty"
foreach ($memberType in $memberTypes)
{
try
{
Add-Member -memberType $memberType -Name PropertyName -Value $null -SecondValue $null -InputObject a
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "Value1AndValue2AreNotBothNull,Microsoft.PowerShell.Commands.AddMemberCommand"
}
}
}
It "Fail to add unexisting type" {
try
{
Add-Member -InputObject a -MemberType AliasProperty -Name Name -Value something -SecondValue unexistingType
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "InvalidCastFromStringToType,Microsoft.PowerShell.Commands.AddMemberCommand"
}
}
It "Successful alias, no type" {
$results = Add-Member -InputObject a -MemberType AliasProperty -Name Cnt -Value Length -passthru
$results.Cnt.GetType().Name | Should Be 'Int32'
$results.Cnt | Should Be 1
}
It "Successful alias, with type" {
$results = add-member -InputObject a -MemberType AliasProperty -Name Cnt -Value Length -SecondValue String -passthru
$results.Cnt.GetType().Name | Should Be 'String'
$results.Cnt | Should Be '1'
}
It "CodeProperty Reference Wrong Type" {
try
{
add-member -InputObject a -MemberType CodeProperty -Name Name -Value something
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "ConvertToFinalInvalidCastException,Microsoft.PowerShell.Commands.AddMemberCommand"
}
}
It "Empty Member Set Null Value1" {
$results = add-member -InputObject a -MemberType MemberSet -Name Name -Value $null -passthru
$results.Length | Should Be 1
$results.Name.a | Should BeNullOrEmpty
}
It "Member Set With 1 Member" {
$members = new-object System.Collections.ObjectModel.Collection[System.Management.Automation.PSMemberInfo]
$n=new-object Management.Automation.PSNoteProperty a,1
$members.Add($n)
$r=add-member -InputObject a -MemberType MemberSet -Name Name -Value $members -passthru
$r.Name.a | Should Be '1'
}
It "MemberSet With Wrong Type For Value1" {
try
{
add-member -InputObject a -MemberType MemberSet -Name Name -Value ImNotACollection
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "ConvertToFinalInvalidCastException,Microsoft.PowerShell.Commands.AddMemberCommand"
}
}
It "ScriptMethod Reference Wrong Type" {
try
{
add-member -InputObject a -MemberType ScriptMethod -Name Name -Value something
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "ConvertToFinalInvalidCastException,Microsoft.PowerShell.Commands.AddMemberCommand"
}
}
It "Add ScriptMethod Success" {
$results = add-member -InputObject 'abc' -MemberType ScriptMethod -Name Name -Value {$this.length} -passthru
$results | Should Be abc
$results.Name() | Should Be 3
}
It "ScriptProperty Reference Wrong Type" {
try
{
add-member -InputObject a -MemberType ScriptProperty -Name Name -Value something
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "ConvertToFinalInvalidCastException,Microsoft.PowerShell.Commands.AddMemberCommand"
}
}
It "Add ScriptProperty Success" {
set-alias ScriptPropertyTestAlias dir
$al=(get-alias ScriptPropertyTestAlias)
$al.Description="MyDescription"
$al | add-member -MemberType ScriptProperty -Name NewDescription -Value {$this.Description} -SecondValue {$this.Description=$args[0]}
$al.NewDescription | Should Be 'MyDescription'
$al.NewDescription = "some description"
$al.NewDescription | Should Be 'some description'
}
It "Add TypeName MemberSet Success" {
$a = 'string' | add-member -MemberType NoteProperty -Name TestNote -Value Any -TypeName MyType -passthru
$a.PSTypeNames[0] | Should Be MyType
}
It "Add TypeName Existing Name Success" {
$a = 'string' | add-member -TypeName System.Object -passthru
$a.PSTypeNames[0] | Should Be System.Object
}
It "Add Single Note To Array" {
$a=1,2,3
$a = Add-Member -InputObject $a -MemberType NoteProperty -Name Name -Value Value -PassThru
$a.Name | Should Be Value
}
It "Add Multiple Note Members" {
$obj=new-object psobject
$hash=@{Name='Name';TestInt=1;TestNull=$null}
add-member -InputObject $obj $hash
$obj.Name | Should Be 'Name'
$obj.TestInt | Should Be 1
$obj.TestNull | Should BeNullOrEmpty
}
It "Add Multiple Note With TypeName" {
$obj=new-object psobject
$hash=@{Name='Name';TestInt=1;TestNull=$null}
$obj = add-member -InputObject $obj $hash -TypeName MyType -Passthru
$obj.PSTypeNames[0] | Should Be MyType
}
It "Add Multiple Members With Force" {
$obj=new-object psobject
$hash=@{TestNote='hello'}
$obj | Add-Member -MemberType NoteProperty -Name TestNote -Value 1
$obj | add-member $hash -force
$obj.TestNote | Should Be 'hello'
}
It "Simplified Add-Member should support using 'Property' as the NoteProperty member name" {
$results = add-member -InputObject a property Any -passthru
$results.property | Should Be 'Any'
$results = add-member -InputObject a Method Any -passthru
$results.Method | Should Be 'Any'
$results = add-member -InputObject a 23 Any -passthru
$results.23 | Should Be 'Any'
$results = add-member -InputObject a 8 np Any -passthru
$results.np | Should Be 'Any'
$results = add-member -InputObject a 16 sp {1+1} -passthru
$results.sp | Should Be 2
}
}
Describe "Add-Member" {
It "should be able to see a newly added member of an object" {
$o = New-Object psobject
Add-Member -InputObject $o -MemberType NoteProperty -Name proppy -Value "superVal"
$o.proppy | Should Not BeNullOrEmpty
$o.proppy | Should Be "superVal"
}
It "Should be able to add a member to an object that already has a member in it" {
$o = New-Object psobject
Add-Member -InputObject $o -MemberType NoteProperty -Name proppy -Value "superVal"
Add-Member -InputObject $o -MemberType NoteProperty -Name AnotherMember -Value "AnotherValue"
$o.AnotherMember | Should Not BeNullOrEmpty
$o.AnotherMember | Should Be "AnotherValue"
}
}
@@ -0,0 +1,5 @@
Describe "Add-Type" {
It "Should not throw given a simple class definition" {
{ Add-Type -TypeDefinition "public static class foo { }" } | Should Not Throw
}
}
@@ -0,0 +1,268 @@
Describe "Clear-Variable DRT Unit Tests" -Tags DRT{
It "Clear-Variable normal variable Name should works"{
Set-Variable foo bar
Clear-Variable -Name foo
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be $null
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
}
It "Clear-Variable ReadOnly variable Name should throw exception and force Clear-Variable should works"{
Set-Variable foo bar -Option ReadOnly
try {
Clear-Variable -Name foo -EA Stop
Throw "Execution OK"
}
catch {
$_.CategoryInfo| Should Match "SessionStateUnauthorizedAccessException"
$_.FullyQualifiedErrorId | Should Be "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand"
}
Clear-Variable -Name foo -Force
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be $null
$var1.Options|Should Be "ReadOnly"
$var1.Description|Should Be ""
}
It "Clear-Variable normal variable Name with local scope should works"{
Set-Variable foo bar
&{
Set-Variable foo baz
$foo | should be baz
Clear-Variable -Name foo -Scope "local"
$var1=Get-Variable -Name foo -Scope "local"
$var1.Name|Should Be "foo"
$var1.Value|Should Be $null
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
}
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
}
It "Clear-Variable Private variable Name should works and Get-Variable with local scope should throw exception"{
Set-Variable foo bar -Option Private
&{
try {
Get-Variable -Name foo -Scope local -EA Stop
Throw "Execution OK"
}
catch {
$_.CategoryInfo| Should Match "ItemNotFoundException"
$_.FullyQualifiedErrorId | Should Be "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand"
}
}
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "Private"
$var1.Description|Should Be ""
}
It "Clear-Variable normal variable Name with local scope should works in different scope"{
Set-Variable foo bar
&{
Set-Variable foo baz
Clear-Variable -Name foo -Scope "local"
$var1=Get-Variable -Name foo -Scope "local"
$var1.Name|Should Be "foo"
$var1.Value|Should Be $null
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
}
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
$var1=Get-Variable -Name foo -Scope "local"
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
}
}
Describe "Clear-Variable" {
BeforeEach {
$var1 = 3
}
It "Should be able to clear a variable using the Name switch" {
Clear-Variable -Name var1
$var1 | Should BeNullOrEmpty
{ Get-Variable var1 } | Should Not Throw
}
It "Should be able to clear a variable without using the Name switch" {
Clear-Variable var1
$var1 | Should BeNullOrEmpty
{ Get-Variable var1 } | Should Not Throw
}
It "Should work using the clv alias" {
clv -Name var1
$var1 | Should BeNullOrEmpty
{ Get-Variable var1 } | Should Not Throw
}
It "Should be able to include a set of variables to clear" {
$var1 = 2
$var2 = 3
$var3 = 4
$variable1 = 23
$variable2 = 4
$variable3 = 2
$w = 3
Clear-Variable -Name w, vari* -Include w, vari*
$variable1 | Should BeNullOrEmpty
$variable2 | Should BeNullOrEmpty
$variable3 | Should BeNullOrEmpty
$w | Should BeNullOrEmpty
$var1 | Should Not BeNullOrEmpty
$var2 | Should Not BeNullOrEmpty
$var3 | Should Not BeNullOrEmpty
}
It "Should be able to exclude a set of variables to clear" {
$var1 = 2
$var2 = 3
$var3 = 4
$variable1 = 23
$variable2 = 4
$variable3 = 2
$w = 3
Clear-Variable -Name w, vari* -Exclude var*
$variable1 | Should Not BeNullOrEmpty
$variable2 | Should Not BeNullOrEmpty
$variable3 | Should Not BeNullOrEmpty
$var1 | Should Not BeNullOrEmpty
$var2 | Should Not BeNullOrEmpty
$var3 | Should Not BeNullOrEmpty
$w | Should BeNullOrEmpty
}
It "Should be able to pass the cleared object through the pipeline using the passthru switch" {
{ Clear-Variable -Name var1 -PassThru | Format-Wide -Property Value } | Should Not Throw
}
It "Should not clear environment variables" {
$env:TEMPVARIABLE = "test data"
{Clear-Variable -Name env:TEMPVARIABLE -ErrorAction Stop} | Should Throw
}
It "Should clear variable even if it is read-only using the Force parameter" {
try
{
New-Variable -Name var2 -Option ReadOnly -Value 100
Clear-Variable -Name var1
Clear-Variable -Name var2 -Force
$var1 | Should BeNullOrEmpty
$var2 | Should BeNullOrEmpty
}
finally
{
Remove-Variable -Name var2 -Force
}
}
It "Should throw error when trying to clear variable that is read-only without using the Force parameter" {
New-Variable -Name var2 -Option ReadOnly -Value 100
try {
Clear-Variable -Name var2 -ea stop
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | should be "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand"
}
$var2 | Should Not BeNullOrEmpty
Remove-Variable -Name var2 -Force
}
Context "Scope Tests" {
# This will violate the DRY principle. Tread softly.
It "Should be able to clear a global scope variable using the global switch" {
New-Variable globalVar -Value 1 -Scope global -Force
Clear-Variable -Name globalVar -Scope global
$globalVar | Should BeNullOrEmpty
}
It "Should not be able to clear a global scope variable using the local switch" {
New-Variable globalVar -Value 1 -Scope global -Force
{Clear-Variable -Name globalVar -Scope local -ErrorAction Stop} | Should Throw
}
It "Should not be able to clear a global variable using the script scope switch" {
New-Variable globalVar -Value 1 -Scope global -Force
{Clear-Variable -Name localVar -Scope script -ErrorAction Stop} | Should Throw
}
It "Should be able to clear an item locally using the local switch" {
New-Variable localVar -Value 2 -Scope local -Force
Clear-Variable -Name localVar -Scope local
$localVar | Should BeNullOrEmpty
{Clear-Variable -Name localVar -Scope script -ErrorAction Stop} | Should Throw
}
It "Should not be able to clear an item locally using the global switch" {
New-Variable localVar -Value 2 -Scope local -Force
{Clear-Variable -Name localVar -Scope global -ErrorAction Stop} | Should Throw
}
It "Should not be able to clear a local variable using the script scope switch" {
New-Variable localVar -Value 2 -Scope local -Force
{Clear-Variable -Name localVar -Scope script -ErrorAction Stop} | Should Throw
}
It "Should be able to clear a script variable created using the script switch" {
{
New-Variable -Name derp2 -Value 3 -Scope script -Force
Clear-Variable -Name derp2 -Scope script
}| Should Not Throw
}
It "Should be able to clear a global script variable that was created using the script scope switch" {
{
New-Variable -Name derpx -Value 4 -Scope script -Force
Clear-Variable -Name derpx -Scope script
} | Should Not Throw
}
}
}
@@ -0,0 +1,457 @@
Describe "Compare-Object" {
BeforeAll {
$nl = [Environment]::NewLine
$content1 = "line 1" + $nl + "line 2"
$content2 = "line 1" + $nl + "line 2.1"
$content3 = "line 1" + $nl + "line 2" + $nl + "line 3"
$content4 = "line 1" + $nl + "line 2.1" + $nl + "Line 3"
$file1 = Join-Path -Path $TestDrive -ChildPath "test1.txt"
$file2 = Join-Path -Path $TestDrive -ChildPath "test2.txt"
$file3 = Join-Path -Path $TestDrive -ChildPath "test3.txt"
$file4 = Join-Path -Path $TestDrive -ChildPath "test4.txt"
New-Item $file1 -ItemType file -Value $content1 -Force
New-Item $file2 -ItemType file -Value $content2 -Force
New-Item $file3 -ItemType file -Value $content3 -Force
New-Item $file4 -ItemType file -Value $content4 -Force
}
It "Should be able to compare the same object using the referenceObject and differenceObject switches" {
{ Compare-Object -ReferenceObject $(Get-Content $file1) -DifferenceObject $(Get-Content $file2) } | Should Not Throw
}
It "Should not throw when referenceobject switch is not used" {
{ Compare-Object $(Get-Content $file1) -DifferenceObject $(Get-Content $file2) } | Should Not Throw
}
It "Should not throw when differenceobject switch is not used" {
{ Compare-Object -ReferenceObject $(Get-Content $file1) $(Get-Content $file2) } | Should Not Throw
}
It "Should indicate data that exists only in the reference dataset" {
$actualOutput = Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $(Get-Content $file4)
$actualOutput[1].SideIndicator | Should Be "<="
}
It "Should indicate data that exists only in the difference dataset" {
$actualOutput = Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $(Get-Content $file4)
$actualOutput[1].SideIndicator | Should Be "<="
}
It "Should indicate data that exists in both datasets when the includeEqual switch is used" {
$actualOutput = Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $(Get-Content $file4) -IncludeEqual
$actualOutput.Length | Should Be 4
$actualOutput[0].SideIndicator | Should Be "=="
$actualOutput[1].SideIndicator | Should Be "=="
}
It "Should be able to use the casesensitive switch" {
{ Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $(Get-Content $file4) -CaseSensitive } | Should Not Throw
}
It "Should correctly indicate that different cases are different when the casesensitive switch is used" {
$caOutput = Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $(Get-Content $file4) -CaseSensitive
$ncaOutput = Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $(Get-Content $file4)
$caOutput.Length | Should Be 4
$ncaOutput[1].SideIndicator | Should Not Be $caOutput[1].SideIndicator
$ncaOutput[2].SideIndicator | Should Not Be $caOutput[2].SideIndicator
$ncaOutput[3].SideIndicator | Should Not Be $caOutput[3].SideIndicator
}
It "Should throw when reference set is null" {
{ Compare-Object -ReferenceObject $anonexistentvariable -DifferenceObject $(Get-Content $file4) } | Should Throw
}
It "Should throw when difference set is null" {
{ Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $anonexistentvariable } | Should Throw
}
It "Should give a 0 array when using excludedifferent switch without also using the includeequal switch" {
$actualOutput = Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $(Get-Content $file4) -ExcludeDifferent
$actualOutput.Length | Should Be 0
}
It "Should only display equal lines when excludeDifferent switch is used alongside the includeequal switch" {
$actualOutput = Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $(Get-Content $file4) -IncludeEqual -ExcludeDifferent
$actualOutput.Length | Should Be 2
}
It "Should be able to pass objects to pipeline using the passthru switch" {
{ Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $(Get-Content $file4) -Passthru | Format-Wide } | Should Not Throw
}
It "Should be able to specify the property of two objects to compare" {
$actualOutput = Compare-Object -ReferenceObject $file3 -DifferenceObject $TestDrive -Property Length
$actualOutput[0].Length | Should BeNullOrEmpty
$actualOutput[1].Length | Should BeGreaterThan 0
$actualOutput[0].Length | Should Not Be $actualOutput[1].Length
}
It "Should be able to specify the syncwindow without error" {
{ Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $(Get-Content $file4) -syncWindow 5 } | Should Not Throw
{ Compare-Object -ReferenceObject $(Get-Content $file3) -DifferenceObject $(Get-Content $file4) -syncWindow 8 } | Should Not Throw
}
It "Should have the expected output when changing the syncwindow" {
$var1 = 1..15
$var2 = 15..1
$actualOutput = Compare-Object -ReferenceObject $var1 -DifferenceObject $var2 -syncWindow 6
$actualOutput[0].InputObject | Should Be 15
$actualOutput[1].InputObject | Should Be 1
$actualOutput[2].InputObject | Should Be 1
$actualOutput[3].InputObject | Should Be 15
$actualOutput[0].SideIndicator | Should be "=>"
$actualOutput[1].SideIndicator | Should be "<="
$actualOutput[2].SideIndicator | Should be "=>"
$actualOutput[3].SideIndicator | Should be "<="
}
}
Describe "Compare-Object DRT basic functionality" -Tags DRT{
if(-not ([System.Management.Automation.PSTypeName]'Employee').Type)
{
Add-Type -TypeDefinition @"
public class Employee
{
public Employee(){}
public Employee(string firstName, string lastName, int yearsInMS)
{
FirstName = firstName;
LastName = lastName;
YearsInMS = yearsInMS;
}
public string FirstName;
public string LastName;
public int YearsInMS;
}
public class EmployeeComparable : Employee, System.IComparable
{
public EmployeeComparable(
string firstName, string lastName, int yearsInMS)
: base(firstName, lastName, yearsInMS)
{}
public int CompareTo(object obj)
{
EmployeeComparable ec = obj as EmployeeComparable;
if (null == ec)
return -1;
if (FirstName != ec.FirstName)
return -1;
if (LastName != ec.LastName)
return -1;
if (YearsInMS != ec.YearsInMS)
return -1;
return 0;
}
}
public class EmployeeDefinesSideIndicator : EmployeeComparable
{
public EmployeeDefinesSideIndicator(
string firstName, string lastName, int yearsInMS)
: base(firstName, lastName, yearsInMS)
{}
public string SideIndicator
{
get { throw new System.ArgumentException("get_SideIndicator"); }
set { throw new System.ArgumentException("get_SideIndicator"); }
}
}
"@
}
else
{
Add-Type -TypeDefinition @"
public class EmployeeComparable : Employee, System.IComparable
{
public EmployeeComparable(
string firstName, string lastName, int yearsInMS)
: base(firstName, lastName, yearsInMS)
{}
public int CompareTo(object obj)
{
EmployeeComparable ec = obj as EmployeeComparable;
if (null == ec)
return -1;
if (FirstName != ec.FirstName)
return -1;
if (LastName != ec.LastName)
return -1;
if (YearsInMS != ec.YearsInMS)
return -1;
return 0;
}
}
public class EmployeeDefinesSideIndicator : EmployeeComparable
{
public EmployeeDefinesSideIndicator(
string firstName, string lastName, int yearsInMS)
: base(firstName, lastName, yearsInMS)
{}
public string SideIndicator
{
get { throw new System.ArgumentException("get_SideIndicator"); }
set { throw new System.ArgumentException("get_SideIndicator"); }
}
}
"@
}
It "Compare-Object with 1 referenceObject and 1 differenceObject should work"{
$empsReference = @([EmployeeComparable]::New("john","smith",5))
$empsDifference = @([EmployeeComparable]::New("mary","jane",5))
$boolvalues=@($true,$false)
foreach($recordEqual in $boolvalues)
{
foreach($excludeDifferent in $boolvalues)
{
foreach($passthru in $boolvalues)
{
$result = Compare-Object -ReferenceObject $empsReference -IncludeEqual:$recordEqual -ExcludeDifferent:$excludeDifferent -Passthru:$passthru -DifferenceObject $empsDifference
if(!$excludeDifferent)
{
$result.Count | Should Be 2
if($passthru)
{
$result[0] | Should Be $empsDifference
$result[1] | Should Be $empsReference
}
else
{
$result[0].InputObject | Should Be $empsDifference
$result[1].InputObject | Should Be $empsReference
$result[0].SideIndicator | Should Be "=>"
$result[1].SideIndicator | Should Be "<="
}
}
else
{
$result.Count | Should Be 0
}
}
}
}
}
It "Compare-Object with 2 referenceObjects and 1 differenceObject should work"{
$empsReference = @([EmployeeComparable]::New("john","smith",5),[EmployeeComparable]::New("mary","jane",3))
$empsDifference = @([EmployeeComparable]::New("john","smith",5))
$boolvalues=@($true,$false)
foreach($recordEqual in $boolvalues)
{
foreach($excludeDifferent in $boolvalues)
{
foreach($passthru in $boolvalues)
{
$result = Compare-Object -ReferenceObject $empsReference -IncludeEqual:$recordEqual -ExcludeDifferent:$excludeDifferent -Passthru:$passthru -DifferenceObject $empsDifference
if($recordEqual)
{
if(!$excludeDifferent)
{
$result.Count | Should Be 2
if($passthru)
{
$result[0] | Should Be $empsReference[0]
$result[1] | Should Be $empsReference[1]
}
else
{
$result[0].InputObject | Should Be $empsReference[0]
$result[1].InputObject | Should Be $empsReference[1]
$result[0].SideIndicator | Should Be "=="
$result[1].SideIndicator | Should Be "<="
}
}
else
{
if($passthru)
{
$result | Should Be $empsReference[0]
}
else
{
$result.InputObject | Should Be $empsReference[0]
$result.SideIndicator | Should Be "=="
}
}
}
else
{
if(!$excludeDifferent)
{
if($passthru)
{
$result | Should Be $empsReference[1]
}
else
{
$result.InputObject | Should Be $empsReference[1]
$result.SideIndicator | Should Be "<="
}
}
else
{
$result.Count | Should Be 0
}
}
}
}
}
}
It "Compare-Object with 0 SyncWindow should work"{
$empsReference = @([EmployeeComparable]::New("john","smith",5))
$empsDifference = @([EmployeeComparable]::New("john","smith",5),[EmployeeComparable]::New("mary","jane",3))
$boolvalues=@($true,$false)
foreach($recordEqual in $boolvalues)
{
foreach($excludeDifferent in $boolvalues)
{
foreach($passthru in $boolvalues)
{
$result = Compare-Object -ReferenceObject $empsReference -IncludeEqual:$recordEqual -ExcludeDifferent:$excludeDifferent -Passthru:$passthru -DifferenceObject $empsDifference -SyncWindow:0
if($recordEqual)
{
if(!$excludeDifferent)
{
$result.Count | Should Be 2
if($passthru)
{
$result[0] | Should Be $empsReference
$result[1] | Should Be $empsDifference[1]
}
else
{
$result[0].InputObject | Should Be $empsReference
$result[1].InputObject | Should Be $empsDifference[1]
$result[0].SideIndicator | Should Be "=="
$result[1].SideIndicator | Should Be "=>"
}
}
else
{
if($passthru)
{
$result | Should Be $empsReference
}
else
{
$result.InputObject | Should Be $empsReference
$result.SideIndicator | Should Be "=="
}
}
}
else
{
if(!$excludeDifferent)
{
if($passthru)
{
$result | Should Be $empsDifference[1]
}
else
{
$result.InputObject | Should Be $empsDifference[1]
$result.SideIndicator | Should Be "=>"
}
}
else
{
$result.Count | Should Be 0
}
}
}
}
}
}
It "Compare-Object with SyncWindow should work"{
$empsReference = @([EmployeeComparable]::New("mary","jane",3),[EmployeeComparable]::New("john","smith",5),[EmployeeComparable]::New("jack", "black", 15),[EmployeeComparable]::New("jim", "bob", 1))
$empsDifference = @([EmployeeComparable]::New("jack", "black", 15),[EmployeeComparable]::New("jim", "bob", 1),[EmployeeComparable]::New("mary","jane",3),[EmployeeComparable]::New("john","smith",5))
$boolvalues=@($true,$false)
foreach($recordEqual in $boolvalues)
{
foreach($excludeDifferent in $boolvalues)
{
foreach($passthru in $boolvalues)
{
$result = Compare-Object -ReferenceObject $empsReference -IncludeEqual:$recordEqual -ExcludeDifferent:$excludeDifferent -Passthru:$passthru -DifferenceObject $empsDifference -SyncWindow:2
if($recordEqual)
{
$result.Count | Should Be 4
if($passthru)
{
$result[0] | Should Be $empsReference[0]
$result[1] | Should Be $empsReference[2]
$result[2] | Should Be $empsReference[1]
$result[3] | Should Be $empsReference[3]
}
else
{
$result[0].InputObject | Should Be $empsReference[0]
$result[0].SideIndicator | Should Be "=="
$result[1].InputObject | Should Be $empsReference[2]
$result[1].SideIndicator | Should Be "=="
$result[2].InputObject | Should Be $empsReference[1]
$result[2].SideIndicator | Should Be "=="
$result[3].InputObject | Should Be $empsReference[3]
$result[3].SideIndicator | Should Be "=="
}
}
else
{
$result.Count | Should Be 0
}
}
}
}
}
It "Compare-Object with Script Block Property Parameter should work"{
$a = [version]"1.2.3.4"
$b = [version]"5.6.7.8"
$result = Compare-Object $a $b -IncludeEqual -Property {$_.Major},{$_.Minor}
$result[0]|Select -ExpandProperty "*Major" | Should Be 5
$result[0]|Select -ExpandProperty "*Minor" | Should Be 6
$result[0].SideIndicator | Should Be "=>"
$result[1]|Select -ExpandProperty "*Major" | Should Be 1
$result[1]|Select -ExpandProperty "*Minor" | Should Be 2
$result[1].SideIndicator | Should Be "<="
}
It "Compare-Object with no ReferenceObject nor DifferenceObject: output nothing, no error and should work"{
$result = Compare-Object @() @()
$result | Should BeNullOrEmpty
}
It "Compare-Object with no DifferenceObject should work"{
$result = Compare-Object @() @("diffObject")
$result.InputObject | Should Be "diffObject"
$result.SideIndicator | Should Be "=>"
}
It "Compare-Object with no ReferenceObject should work"{
$result = Compare-Object @("refObject") @()
$result.InputObject | Should Be "refObject"
$result.SideIndicator | Should Be "<="
}
}
@@ -0,0 +1,65 @@
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
Describe "ConvertFrom-Csv" {
$testObject = "a", "1"
$testcsv = Join-Path -Path (Join-Path -Path $here -ChildPath assets) -ChildPath TestCsv2.csv
$testName = "Zaphod BeebleBrox"
$testColumns = @"
a,b,c
1,2,3
"@
It "Should be able to be called" {
{ ConvertFrom-Csv -InputObject $testObject } | Should Not Throw
}
It "Should be able to pipe" {
{ $testObject | ConvertFrom-Csv } | Should Not Throw
}
It "Should have expected results when using piped inputs" {
$csvContent = Get-Content $testcsv
$actualresult = $csvContent | ConvertFrom-Csv
$actualresult.GetType().BaseType.Name | Should Be "Array"
$actualresult[0].GetType().Name | Should Be "PSCustomObject"
#Should have a name property in the result
$actualresult[0].Name | Should Be $testName
}
It "Should be able to set a delimiter" {
{ $testcsv | ConvertFrom-Csv -Delimiter ";" } | Should Not Throw
}
It "Should actually delimit the output" {
$csvContent = Get-Content $testcsv
$actualresult = $csvContent | ConvertFrom-Csv -Delimiter ";"
$actualresult.GetType().BaseType.Name | Should Be "Array"
$actualresult[0].GetType().Name | Should Be "PSCustomObject"
# ConvertFrom-Csv takes the first line of the input as a header by default
$actualresult.Length | Should Be $($csvContent.Length - 1)
}
It "Should be able to have multiple columns" {
$actualData = $testColumns | ConvertFrom-Csv
$actualLength = $($( $actualData | gm) | Where-Object {$_.MemberType -eq "NoteProperty" }).Length
$actualLength | Should Be 3
}
}
Describe "ConvertFrom-Csv DRT Unit Tests" -Tags DRT{
It "Test ConvertFrom-Csv with pipelined InputObject and Header" {
$inputObject = [pscustomobject]@{ First = 1; Second = 2 }
$res = $inputObject | ConvertTo-Csv
$result = $res | ConvertFrom-Csv -Header "Header1","Header2"
$result[0].Header1 | Should Be "First"
$result[0].Header2 | Should Be "Second"
$result[1].Header1 | Should Be "1"
$result[1].Header2 | Should Be "2"
}
}
@@ -0,0 +1,71 @@
Describe "ConvertFrom-StringData DRT Unit Tests" -Tags DRT {
It "Should able to throw error when convert invalid line" {
$str =@"
#comments here
abc
#comments here
def=content of def
"@
try
{
ConvertFrom-StringData $str
Throw "we expect 'InvalidOperation' exception"
}
catch
{
$_.FullyQualifiedErrorId | Should be "InvalidOperation,Microsoft.PowerShell.Commands.ConvertFromStringDataCommand"
}
}
}
Describe "ConvertFrom-StringData" {
$sampleData = @'
foo = 0
bar = 1
bazz = 2
'@
It "Should not throw when called with just the stringdata switch" {
{ ConvertFrom-StringData -StringData 'a=b' } | Should Not Throw
}
It "Should return a hashtable" {
$(ConvertFrom-StringData -StringData 'a=b').GetType().Name | Should Be "Hashtable"
}
It "Should throw if not in x=y format" {
{ ConvertFrom-StringData -StringData 'ab' } | Should Throw
{ ConvertFrom-StringData -StringData 'a,b' } | Should Throw
{ ConvertFrom-StringData -StringData 'a b' } | Should Throw
{ ConvertFrom-StringData -StringData 'a\tb' } | Should Throw
{ ConvertFrom-StringData -StringData 'a:b' } | Should Throw
}
It "Should return the data on the left side in the key" {
$actualValue = ConvertFrom-StringData -StringData 'a=b'
$actualValue.Keys | Should Be "a"
}
It "Should return the data on the right side in the value" {
$actualValue = ConvertFrom-StringData -StringData 'a=b'
$actualValue.Values | Should Be "b"
}
It "Should return a keycollection for the keys" {
$(ConvertFrom-StringData -StringData 'a=b').Keys.gettype().Name | Should Be "KeyCollection"
}
It "Should return a valuecollection for the values" {
$(ConvertFrom-StringData -StringData 'a=b').Values.gettype().Name | Should Be "ValueCollection"
}
It "Should work for multiple lines" {
{ ConvertFrom-StringData -StringData $sampleData } | Should Not Throw
$(ConvertFrom-StringData -StringData $sampleData).Keys | Should Be "foo", "bar", "bazz"
$(ConvertFrom-StringData -StringData $sampleData).Values | Should Be "0","1","2"
}
}
@@ -0,0 +1,72 @@
Describe "ConvertTo-Csv DRT Unit Tests" -Tags DRT{
$inputObject = [pscustomobject]@{ First = 1; Second = 2 }
It "Test convertto-csv with psobject pipelined" {
$returnObject = $inputObject | ConvertTo-Csv
$returnObject.Count | Should Be 3
$returnObject[0] | Should Be "#TYPE System.Management.Automation.PSCustomObject"
$returnObject[1] | Should Be "`"First`",`"Second`""
$returnObject[2] | Should Be "`"1`",`"2`""
}
It "Test convertto-csv with NoTypeInformation and psobject pipelined" {
$returnObject = $inputObject | ConvertTo-Csv -NoTypeInformation
$returnObject.Count | Should Be 2
$returnObject[0] | Should Be "`"First`",`"Second`""
$returnObject[1] | Should Be "`"1`",`"2`""
}
It "Test convertto-csv with a useculture flag" {
#The default value is ','
$returnObject = $inputObject | ConvertTo-Csv -UseCulture
$returnObject.Count | Should Be 3
$returnObject[0] | Should Be "#TYPE System.Management.Automation.PSCustomObject"
$returnObject[1] | Should Be "`"First`",`"Second`""
$returnObject[2] | Should Be "`"1`",`"2`""
}
It "Test convertto-csv with Delimiter" {
#The default value is ','
$returnObject = $inputObject | ConvertTo-Csv -Delimiter ";"
$returnObject.Count | Should Be 3
$returnObject[0] | Should Be "#TYPE System.Management.Automation.PSCustomObject"
$returnObject[1] | Should Be "`"First`";`"Second`""
$returnObject[2] | Should Be "`"1`";`"2`""
}
}
Describe "ConvertTo-Csv" {
$Name = "Hello"; $Data = "World";
$testObject = New-Object psobject -Property @{ FirstColumn = $Name; SecondColumn = $Data }
It "Should Be able to be called without error" {
{ $testObject | ConvertTo-Csv } | Should Not Throw
}
It "Should output an array of objects" {
$result = $testObject | ConvertTo-Csv
$result.GetType().BaseType.Name | Should Be "Array"
}
It "Should return the type of data in the first element of the output array" {
$result = $testObject | ConvertTo-Csv
$result[0] | Should Be "#TYPE System.Management.Automation.PSCustomObject"
}
It "Should return the column info in the second element of the output array" {
$result = $testObject | ConvertTo-Csv
$result[1] | Should Match "`"FirstColumn`""
$result[1] | Should Match "`"SecondColumn`""
}
It "Should return the data as a comma-separated list in the third element of the output array" {
$result = $testObject | ConvertTo-Csv
$result[2] | Should Match "`"Hello`""
$result[2] | Should Match "`"World`""
}
}
@@ -0,0 +1,11 @@
Describe "ConvertTo-SecureString" {
Context "Checking return types of ConvertTo-SecureString" {
It "Should return System.Security.SecureString after converting plaintext variable"{
$PesterTestConvert = (ConvertTo-SecureString "plaintextpester" -AsPlainText -force)
($PesterTestConvert).GetType() | Should Be securestring
}
}
}
@@ -0,0 +1,53 @@
Describe "ConvertTo-Xml DRT Unit Tests" -Tags DRT{
$customPSObject = [pscustomobject]@{ "prop1" = "val1"; "prop2" = "val2" }
$newLine = [System.Environment]::NewLine
It "Test convertto-xml with a depth parameter" {
$returnObject = $customPSObject | ConvertTo-Xml -Depth 1
$returnObject -is [System.Xml.XmlDocument] | Should Be $true
#$xml = [System.Xml.XmlDocument]$returnObject
$expectedValue = '<?xml version="1.0" encoding="utf-8"?><Objects><Object Type="System.Management.Automation.PSCustomObject">' + '<Property Name="prop1" Type="System.String">val1</Property><Property Name="prop2" Type="System.String">val2</Property></Object></Objects>'
$returnObject.OuterXml | Should Be $expectedValue
}
It "Test convertto-xml with notypeinfo parameter" {
$returnObject = $customPSObject | ConvertTo-Xml -NoTypeInformation
$returnObject -is [System.Xml.XmlDocument] | Should Be $true
$expectedValue = '<?xml version="1.0" encoding="utf-8"?><Objects><Object>' + '<Property Name="prop1">val1</Property><Property Name="prop2">val2</Property></Object></Objects>'
$returnObject.OuterXml | Should Be $expectedValue
}
It "Test convertto-xml as String" {
$returnObject = $customPSObject | ConvertTo-Xml -As String
$expectedValue = @"
<?xml version="1.0" encoding="utf-8"?>$newLine<Objects>$newLine <Object Type="System.Management.Automation.PSCustomObject">$newLine <Property Name="prop1" Type="System.String">val1</Property>$newLine <Property Name="prop2" Type="System.String">val2</Property>$newLine </Object>$newLine</Objects>
"@
$returnObject -is [System.String] | Should Be $true
$returnObject | Should Be $expectedValue
#$returnObject.Trim($newLine) | Should Be $expectedValue.Trim($newLine)
}
It "Test convertto-xml as Stream" {
$returnObject = $customPSObject | ConvertTo-Xml -As Stream
$returnObject -is [System.Array] | Should Be $true
$stream1 = '<?xml version="1.0" encoding="utf-8"?>'
$stream2 = '<Objects>'
$stream3 = @"
<Object Type="System.Management.Automation.PSCustomObject">$newLine <Property Name="prop1" Type="System.String">val1</Property>$newLine <Property Name="prop2" Type="System.String">val2</Property>$newLine</Object>
"@
$stream4 = '</Objects>'
$returnObject.Count | Should Be 4
$returnObject[0] | Should Be $stream1
$returnObject[1] | Should Be $stream2
$returnObject[2] | Should Be $stream3
$returnObject[3] | Should Be $stream4
}
It "Test convertto-xml as Document" {
$returnObject = $customPSObject | ConvertTo-Xml -As Document -NoTypeInformation
$returnObject -is [System.Xml.XmlDocument] | Should Be $true
$expectedValue = '<?xml version="1.0" encoding="utf-8"?><Objects><Object><Property Name="prop1">val1</Property><Property Name="prop2">val2</Property></Object></Objects>'
$returnObject.OuterXml | Should Be $expectedValue
}
}
@@ -0,0 +1,19 @@
$removeAliasList = @("ac","compare","cpp","diff","sleep","sort","start","cat","cp","ls","man","mount","mv","ps","rm","rmdir")
$keepAliasList = @{cd="Set-Location"},@{dir="Get-ChildItem"},@{echo="Write-output"},@{fc="format-custom"},@{kill="stop-process"},@{clear="clear-host"}
Describe "Windows aliases do not conflict with Linux commands" {
foreach ($alias in $removeAliasList) {
It "Should not have certain aliases on Linux" -Skip:$IsWindows {
Test-Path Alias:$alias | Should Be $false
}
}
foreach ($alias in $keepAliasList) {
It "Should have aliases that are Bash built-ins on Linux" {
(Get-Alias $alias.Keys).Definition | Should Be $alias.Values
}
}
It "Should have more as a function" {
Test-Path Function:more | Should Be $true
}
}
@@ -0,0 +1,43 @@
Describe "Environment-Variables" {
It "Should have environment variables" {
Get-Item ENV: | Should Not BeNullOrEmpty
}
It "Should have a nonempty PATH" {
$ENV:PATH | Should Not BeNullOrEmpty
}
It "Should contain /bin in the PATH" {
if ($IsWindows)
{
$ENV:PATH | Should Match "C:"
}
else
{
$ENV:PATH | Should Match "/bin"
}
}
It "Should have the correct HOME" {
if ($IsWindows)
{
$expected = "\Users"
Split-Path $ENV:HOMEPATH -Parent | Should Be $expected
}
else
{
$expected = /bin/bash -c "cd ~ && pwd"
$ENV:HOME | Should Be $expected
}
}
It "Should be able to set the environment variables" {
$expected = "this is a test environment variable"
{ $ENV:TESTENVIRONMENTVARIABLE = $expected } | Should Not Throw
$ENV:TESTENVIRONMENTVARIABLE | Should Not BeNullOrEmpty
$ENV:TESTENVIRONMENTVARIABLE | Should Be $expected
}
}
@@ -0,0 +1,159 @@
Describe "Export-Alias DRT Unit Tests" -Tags DRT{
$testAliasDirectory = Join-Path -Path $TestDrive -ChildPath ExportAliasTestDirectory
$testAliases = "TestAliases"
$fulltestpath = Join-Path -Path $testAliasDirectory -ChildPath $testAliases
BeforeEach {
New-Item -Path $testAliasDirectory -ItemType Directory -Force
remove-item alias:abcd* -force
remove-item alias:ijkl* -force
set-alias abcd01 efgh01
set-alias abcd02 efgh02
set-alias abcd03 efgh03
set-alias abcd04 efgh04
set-alias ijkl01 mnop01
set-alias ijkl02 mnop02
set-alias ijkl03 mnop03
set-alias ijkl04 mnop04
}
AfterEach {
Remove-Item -Path $testAliasDirectory -Recurse -Force
}
It "Export-Alias for exist file should work"{
New-Item -Path $fulltestpath -ItemType File -Force
{Export-Alias $fulltestpath}| Should Not Throw
}
It "Export-Alias Resolve To Multiple will throw PSInvalidOperationException" {
try {
Export-Alias *
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "ReadWriteMultipleFilesNotSupported,Microsoft.PowerShell.Commands.ExportAliasCommand"
}
}
It "Export-Alias with Invalid Scope will throw PSArgumentException" {
try {
Export-Alias $fulltestpath -scope foobar
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "Argument,Microsoft.PowerShell.Commands.ExportAliasCommand"
}
}
It "Export-Alias for Default"{
Export-Alias $fulltestpath abcd01 -passthru
$fulltestpath| Should ContainExactly '"abcd01","efgh01","","None"'
}
It "Export-Alias As CSV"{
Export-Alias $fulltestpath abcd01 -As CSV -passthru
$fulltestpath| Should ContainExactly '"abcd01","efgh01","","None"'
}
It "Export-Alias As CSV With Description"{
Export-Alias $fulltestpath abcd01 -As CSV -description "My Aliases" -passthru
$fulltestpath| Should ContainExactly '"abcd01","efgh01","","None"'
$fulltestpath| Should ContainExactly "My Aliases"
}
It "Export-Alias As CSV With Multiline Description"{
Export-Alias $fulltestpath abcd01 -As CSV -description "My Aliases\nYour Aliases\nEveryones Aliases" -passthru
$fulltestpath| Should ContainExactly '"abcd01","efgh01","","None"'
$fulltestpath| Should ContainExactly "My Aliases"
$fulltestpath| Should ContainExactly "Your Aliases"
$fulltestpath| Should ContainExactly "Everyones Aliases"
}
It "Export-Alias As Script"{
Export-Alias $fulltestpath abcd01 -As Script -passthru
$fulltestpath| Should ContainExactly 'set-alias -Name:"abcd01" -Value:"efgh01" -Description:"" -Option:"None"'
}
It "Export-Alias As Script With Multiline Description"{
Export-Alias $fulltestpath abcd01 -As Script -description "My Aliases\nYour Aliases\nEveryones Aliases" -passthru
$fulltestpath| Should ContainExactly 'set-alias -Name:"abcd01" -Value:"efgh01" -Description:"" -Option:"None"'
$fulltestpath| Should ContainExactly "My Aliases"
$fulltestpath| Should ContainExactly "Your Aliases"
$fulltestpath| Should ContainExactly "Everyones Aliases"
}
It "Export-Alias for Force Test"{
Export-Alias $fulltestpath abcd01
Export-Alias $fulltestpath abcd02 -force
$fulltestpath| Should Not ContainExactly '"abcd01","efgh01","","None"'
$fulltestpath| Should ContainExactly '"abcd02","efgh02","","None"'
}
It "Export-Alias for Force ReadOnly Test" {
Export-Alias $fulltestpath abcd01
if ( $IsWindows )
{
attrib +r $fulltestpath
}
else
{
chmod 444 $fulltestpath
}
try{
Export-Alias $fulltestpath abcd02
}
catch{
$_.FullyQualifiedErrorId | Should be "FileOpenFailure,Microsoft.PowerShell.Commands.ExportAliasCommand"
}
Export-Alias $fulltestpath abcd03 -force
$fulltestpath| Should Not ContainExactly '"abcd01","efgh01","","None"'
$fulltestpath| Should Not ContainExactly '"abcd02","efgh02","","None"'
$fulltestpath| Should ContainExactly '"abcd03","efgh03","","None"'
if ( $IsWindows )
{
attrib -r $fulltestpath
}
else
{
chmod 777 $fulltestpath
}
}
}
Describe "Export-Alias" {
$testAliasDirectory = Join-Path -Path $TestDrive -ChildPath ExportAliasTestDirectory
$testAliases = "TestAliases"
$fulltestpath = Join-Path -Path $testAliasDirectory -ChildPath $testAliases
BeforeEach {
New-Item -Path $testAliasDirectory -ItemType Directory -Force
}
It "Should be able to create a file in the specified location"{
Export-Alias $fulltestpath
Test-Path $fulltestpath | Should be $true
}
It "Should create a file with the list of aliases that match the expected list" {
Export-Alias $fulltestpath
Test-Path $fulltestpath | Should Be $true
$actual = Get-Content $fulltestpath | Sort-Object
$expected = Get-Command -CommandType Alias
for ( $i=0; $i -lt $expected.Length; $i++)
{
# We loop through the expected list and not the other because the output writes some comments to the file.
$expected[$i] | Should Match $actual[$i].Name
}
}
Remove-Item -Path $testAliasDirectory -Recurse -Force
}
@@ -0,0 +1,114 @@
Describe "Export-Csv" {
$testObject = @("test","object","array")
$testCsv = "output.csv"
AfterEach {
Remove-Item $testCsv -Force -ErrorAction SilentlyContinue
}
It "Should be able to be called without error" {
{ $testObject | Export-Csv $testCsv } | Should Not Throw
}
It "Should throw if an output file isn't specified" {
{ $testObject | Export-Csv -ErrorAction SilentlyContinue } | Should Throw
}
It "Should be a string when exporting via pipe" {
$testObject | Export-Csv $testCsv
$piped = Get-Content $testCsv
$piped[0] | Should Match ".String"
}
It "Should be an object when exporting via the inputObject switch" {
Export-Csv -InputObject $testObject -Path $testCsv
$switch = Get-Content $testCsv
$switch[0] | Should Match ".Object"
}
It "Should output a csv file containing a string of all the lengths of each element when piped input is used" {
$testObject | Export-Csv -Path $testCsv
$first = "`"" + $testObject[0].Length.ToString() + "`""
$second = "`"" + $testObject[1].Length.ToString() + "`""
$third = "`"" + $testObject[2].Length.ToString() + "`""
$expected = @("#TYPE System.String", "`"Length`"", $first , $second, $third)
for ( $i = 0; $i -lt $testCsv.Length; $i++)
{
$(Get-Content $testCsv)[$i] | Should Be $expected[$i]
}
}
It "Should be able to use the epcsv alias without error" {
{ $testObject | Export-Csv -Path $testCsv } | Should Not Throw
}
It "Should have the same information when using the alias vs the cmdlet" {
$testObject | Export-Csv -Path $testCsv
$aliasObject = "alias.csv"
$testObject | epcsv -Path $aliasObject
for ( $i = 0; $i -lt $testCsv.Length; $i++)
{
$(Get-Content $testCsv)[$i] | Should Be $(Get-Content $aliasObject)[$i]
}
# Clean up after yourself
Remove-Item $aliasObject -Force
}
}
Describe "Export-Csv DRT Unit Tests" -Tags DRT{
$filePath = Join-Path $TestDrive -ChildPath "test.csv"
$newLine = [environment]::NewLine
It "Test basic function works well" {
$input = [pscustomobject]@{ "P1" = "V11"; "P2" = "V12"; "P3" = "V13" }
$input | Export-Csv -Path $filePath -NoTypeInformation
$results = Import-Csv $filePath
$results.P1 | Should Be "V11"
$results.P2 | Should Be "V12"
$results.P3 | Should Be "V13"
}
It "Test if it works with special character" {
$v3 = "abc" + $newLine + "foo"
$input = [pscustomobject]@{ "P1" = " "; "P2" = "abc,foo"; "P3" = $v3}
$input | Export-Csv -Path $filePath -NoTypeInformation
$results = Import-Csv $filePath
$results.P1 | Should Be " "
$results.P2 | Should Be "abc,foo"
$results.P3 | Should Be $v3
}
It "Test force switch works well" {
$input = [pscustomobject]@{ "P1" = "first" }
$input | Export-Csv -Path $filePath
$input = [pscustomobject]@{ "P2" = "second" }
$input | Export-Csv -Path $filePath -Force
$results = Import-Csv $filePath
$results.P2 | Should be "second"
$property = $results | Get-Member | ? { $_.MemberType -eq "NoteProperty" } | % { $_.Name }
$property | should not be P1
}
It "Test export-csv with a useculture flag" {
$outputFilesDir = Join-Path $TestDrive -ChildPath "Monad"
$fileToGenerate = Join-Path $outputFilesDir -ChildPath "CSVTests.csv"
$delimiter = (Get-Culture).TextInfo.ListSeparator
New-Item -Path $outputFilesDir -ItemType Directory -Force
Get-Item -Path $outputFilesDir| Export-Csv -Path $fileToGenerate -UseCulture -NoTypeInformation
$contents = Get-Content -Path $fileToGenerate
$contents.Count | Should Be 2
$contents[0].Contains($delimiter) | Should Be $true
$contents[1].Contains($delimiter) | Should Be $true
}
}
@@ -0,0 +1,41 @@
Describe "Export-FormatData DRT Unit Tests" -Tags DRT{
It "Test basic functionality" {
$fd = Get-FormatData
$tempFile = Join-Path $TestDrive -ChildPath "exportFormatTest.txt"
$results = Export-FormatData -InputObject $fd[0] -Path $tempFile
$content = Get-Content $tempFile
$formatViewDefinition = $fd[0].FormatViewDefinition
$typeName = $fd[0].TypeName
$content.Contains($typeName) | Should Be $true
for ($i = 0; $i -lt $formatViewDefinition.Count;$i++)
{
$content.Contains($formatViewDefinition[$i].Name) | Should Be $true
}
}
}
Describe "Export-FormatData" {
Context "Check Export-FormatData can be called validly." {
It "Should be able to be called without error" {
{ Get-FormatData | Export-FormatData -Path "outputfile" } | Should Not Throw
Remove-Item "outputfile" -Force -ErrorAction SilentlyContinue
}
}
Context "Check that the output is in the correct format" {
It "Should not return an empty xml file" {
Get-FormatData | Export-FormatData -Path "outputfile"
$piped = Get-Content "outputfile"
$piped | Should Not Be ""
Remove-Item "outputfile" -Force -ErrorAction SilentlyContinue
}
It "Should have a valid xml tag at the start of the file" {
Get-FormatData | Export-FormatData -Path "outputfile"
$piped = Get-Content "outputfile"
$piped[0] | Should Be "<"
Remove-Item "outputfile" -Force -ErrorAction SilentlyContinue
}
}
}
@@ -0,0 +1,300 @@
Describe "Format-Custom" {
Context "Check Format-Custom aliases" {
It "Should have the same output between the alias and the unaliased function" {
$nonaliased = Get-FormatData | Format-Custom
$aliased = Get-FormatData | fc
$($nonaliased | Out-String).CompareTo($($aliased | Out-String)) | Should Be 0
}
}
Context "Check specific flags on Format-Custom" {
It "Should be able to specify the depth in output" {
$getprocesspester = Get-FormatData | Format-Custom -depth 1
($getprocesspester).Count | Should BeGreaterThan 0
}
It "Should be able to use the Property flag to select properties" {
$CommandName = Get-Command | Format-Custom -Property "Name"
$CommandName | Should Not Match "Source"
}
}
}
Describe "Format-Custom DRT basic functionality" -Tags DRT{
Add-Type -TypeDefinition @"
public abstract class NamedItem
{
public string name;
}
public abstract class MyContainerBase : NamedItem
{
public System.Collections.Generic.List<NamedItem> children = new System.Collections.Generic.List<NamedItem> ();
}
public sealed class MyLeaf1 : NamedItem
{
public int val1 = 0;
}
public sealed class MyLeaf2 : NamedItem
{
public int val2 = 0;
}
public sealed class MyContainer1 : MyContainerBase
{
public string data1;
}
public sealed class MyContainer2 : MyContainerBase
{
public string data2;
}
"@
It "Format-Custom with subobject should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$expectResult1 = "this is the name"
$expectResult2 = "this is the name of the sub object"
$testObject = @{}
$testObject.name = $expectResult1
$testObject.subObjectValue = @{}
$testObject.subObjectValue.name = $expectResult2
$testObject.subObjectValue.array = (0..63)
$testObject.subObjectValue.stringarray = @("one","two")
$result = $testObject | Format-Custom | Out-String
$result | Should Match $expectResult1
$result | Should Match $expectResult2
$result | Should Match "one"
$result | Should Match "two"
}
It "Format-Custom with Tree Object should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$expectedResult=@"
class MyContainer1
{
data1 = data 1
children =
[
class MyLeaf1
{
val1 = 10
name = leaf 1
}
class MyLeaf2
{
val2 = 20
name = leaf 2
}
]
name = container 1
}
class MyContainer2
{
data2 = data 2
children =
[
class MyLeaf1
{
val1 = 10
name = leaf 1
}
class MyLeaf2
{
val2 = 20
name = leaf 2
}
]
name = container 2
}
class MyContainer2
{
data2 = data 2 deep
children =
[
class MyContainer1
{
data1 = cx data
children =
[
class MyLeaf1
{
val1 = 10
name = leaf 1
}
class MyLeaf2
{
val2 = 20
name = leaf 2
}
]
name = cx
}
]
name = container 2 deep
}
class MyContainer1
{
data1 = cx data
children =
[
class MyLeaf1
{
val1 = 10
name = leaf 1
}
class MyLeaf2
{
val2 = 20
name = leaf 2
}
]
name = cx
}
"@
$leaf1 = New-Object MyLeaf1
$leaf1.name = "leaf 1"
$leaf1.val1 = 10
$leaf2 = New-Object MyLeaf2
$leaf2.name = "leaf 2"
$leaf2.val2 = 20
$c1 = New-Object MyContainer1
$c1.name = "container 1"
$c1.data1 = "data 1"
$c1.children.Add($leaf1)
$c1.children.Add($leaf2)
$c2 = New-Object MyContainer2
$c2.name = "container 2"
$c2.data2 = "data 2"
$c2.children.Add($leaf1)
$c2.children.Add($leaf2)
$cDeep = New-Object MyContainer2
$cDeep.name = "container 2 deep"
$cDeep.data2 = "data 2 deep"
$cx= New-Object MyContainer1
$cx.name = "cx"
$cx.data1 = "cx data"
$cx.children.Add($leaf1)
$cx.children.Add($leaf2)
$cDeep.children.Add($cx)
$objectList = @($c1,$c2,$cDeep,$cx)
$result = $objectList | Format-Custom | Out-String
$result = $result -replace "[{} `n\r]",""
$expectedResult = $expectedResult -replace "[{} `n\r]",""
$result | Should Be $expectedResult
}
It "Format-Custom with Empty Data Tree Object should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$expectedResult=@"
class MyContainer1
{
data1 =
children =
name =
}
"@
$c= New-Object MyContainer1
$c.name = $null
$c.data1 = $null
$c.children = $null
$objectList = @($c)
$result = $objectList | Format-Custom | Out-String
$result = $result -replace "[{} `n\r]",""
$expectedResult = $expectedResult -replace "[{} `n\r]",""
$result | Should Be $expectedResult
}
It "Format-Custom with Back Pointers Tree Object should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$expectedResult=@"
class MyContainer1
{
data1 =
children =
[
class MyContainer1
{
data1 =
children =
[
class MyContainer1
{
data1 =
children =
[
MyContainer1
]
name = ROOT
}
]
name = ROOT
}
]
name = ROOT
}
"@
$root= New-Object MyContainer1
$root.name = "ROOT"
$root.children.Add($root)
$objectList = @($root)
$result = $objectList | Format-Custom | Out-String
$result = $result -replace "[{} `n\r]",""
$expectedResult = $expectedResult -replace "[{} `n\r]",""
$result | Should Be $expectedResult
}
It "Format-Custom with Leaf Only Data should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$expectedResult=@"
class MyLeaf1
{
val1 = 10
name = leaf 1
}
class MyLeaf2
{
val2 = 20
name = leaf 2
}
"@
$leaf1 = New-Object MyLeaf1
$leaf1.name = "leaf 1"
$leaf1.val1 = 10
$leaf2 = New-Object MyLeaf2
$leaf2.name = "leaf 2"
$leaf2.val2 = 20
$objectList = @($leaf1,$leaf2)
$result = $objectList | Format-Custom | Out-String
$result = $result -replace "[{} `n\r]",""
$expectedResult = $expectedResult -replace "[{} `n\r]",""
$result | Should Be $expectedResult
}
}
@@ -0,0 +1,153 @@
Describe "Format-List" {
$nl = [Environment]::NewLine
BeforeEach {
$in = New-Object PSObject
Add-Member -InputObject $in -MemberType NoteProperty -Name testName -Value testValue
}
It "Should call format list without error" {
{ $in | Format-List } | Should Not BeNullOrEmpty
}
It "Should be able to call the alias" {
{ $in | fl } | Should Not BeNullOrEmpty
}
It "Should have the same output whether choosing alias or not" {
$expected = $in | Format-List | Out-String
$actual = $in | fl | Out-String
$actual | Should Be $expected
}
It "Should produce the expected output" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$expected = "${nl}${nl}testName : testValue${nl}${nl}${nl}${nl}"
$in = New-Object PSObject
Add-Member -InputObject $in -MemberType NoteProperty -Name testName -Value testValue
$in | Format-List | Should Not BeNullOrEmpty
$in | Format-List | Out-String | Should Not BeNullOrEmpty
$in | Format-List | Out-String | Should Be $expected
}
It "Should be able to call a property of the piped input" {
# Tested on two input commands to verify functionality.
{ Get-Command | Select-Object -First 5 | Format-List -Property Name } | Should Not BeNullOrEmpty
{ Get-Date | Format-List -Property DisplayName } | Should Not BeNullOrEmpty
}
It "Should be able to display a list of props when separated by a comma" {
(Get-Command | Select-Object -First 5 | Format-List -Property Name,Source | Out-String) -Split "${nl}" |
Where-Object { $_.trim() -ne "" } |
ForEach-Object { $_ | Should Match "(Name)|(Source)" }
}
It "Should show the requested prop in every element" {
# Testing each element of format-list, using a for-each loop since the Format-List is so opaque
(Get-Command | Select-Object -First 5 | Format-List -Property Source | Out-String) -Split "${nl}" |
Where-Object { $_.trim() -ne "" } |
ForEach-Object { $_ | Should Match "Source :" }
}
It "Should not show anything other than the requested props" {
$output = Get-Command | Select-Object -First 5 | Format-List -Property Name | Out-String
$output | Should Not Match "CommandType :"
$output | Should Not Match "Source :"
$output | Should Not Match "Module :"
}
It "Should be able to take input without piping objects to it" {
$output = { Format-List -InputObject $in }
$output | Should Not BeNullOrEmpty
}
}
Describe "Format-List DRT basic functionality" -Tags DRT{
It "Format-List with array should work"-Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$al = (0..255)
$info = @{}
$info.array = $al
$result = $info | Format-List | Out-String
$result | Should Match "Name : array\s+Value : {0, 1, 2, 3...}"
}
It "Format-List with No Objects for End-To-End should work"{
$p = @{}
$result = $p | Format-List -Force -Property "foo","bar" | Out-String
$result.Trim() | Should BeNullOrEmpty
}
It "Format-List with Null Objects for End-To-End should work"{
$p = $null
$result = $p | Format-List -Force -Property "foo","bar" | Out-String
$result.Trim() | Should BeNullOrEmpty
}
It "Format-List with single line string for End-To-End should work"{
$p = "single line string"
$result = $p | Format-List -Force -Property "foo","bar" | Out-String
$result.Trim() | Should BeNullOrEmpty
}
It "Format-List with multiple line string for End-To-End should work"{
$p = "Line1\nLine2"
$result = $p | Format-List -Force -Property "foo","bar" | Out-String
$result.Trim() | Should BeNullOrEmpty
}
It "Format-List with string sequence for End-To-End should work"{
$p = "Line1","Line2"
$result = $p | Format-List -Force -Property "foo","bar" | Out-String
$result.Trim() | Should BeNullOrEmpty
}
It "Format-List with complex object for End-To-End should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
Add-Type -TypeDefinition "public enum MyDayOfWeek{Sun,Mon,Tue,Wed,Thr,Fri,Sat}"
$eto = [MyDayOfWeek]::New()
$info = @{}
$info.intArray = 1,2,3,4
$info.arrayList = "string1","string2"
$info.enumerable = [MyDayOfWeek]$eto
$info.enumerableTestObject = $eto
$result = $info|Format-List|Out-String
$result | Should Match "Name : enumerableTestObject"
$result | Should Match "Value : Sun"
$result | Should Match "Name : arrayList"
$result | Should Match "Value : {string1, string2}"
$result | Should Match "Name : enumerable"
$result | Should Match "Value : Sun"
$result | Should Match "Name : intArray"
$result | Should Match "Value : {1, 2, 3, 4}"
}
It "Format-List with multiple same class object should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx"){
Add-Type -TypeDefinition "public class TestClass{public TestClass(string name,int length){Name = name;Length = length;}public string Name;public int Length;}"
$testobjects = [TestClass]::New('name1',1),[TestClass]::New('name2',2),[TestClass]::New('name3',3)
$result = $testobjects|Format-List|Out-String
$result | Should Match "Name : name1"
$result | Should Match "Length : 1"
$result | Should Match "Name : name2"
$result | Should Match "Length : 2"
$result | Should Match "Name : name3"
$result | Should Match "Length : 3"
}
It "Format-List with multiple different class object should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx"){
Add-Type -TypeDefinition "public class TestClass{public TestClass(string name,int length){Name = name;Length = length;}public string Name;public int Length;}"
Add-Type -TypeDefinition "public class TestClass2{public TestClass2(string name,string value,int length){Name = name;Value = value; Length = length;}public string Name;public string Value;public int Length;}"
$testobjects = [TestClass]::New('name1',1),[TestClass2]::New('name2',"value2",2),[TestClass]::New('name3',3)
$result = $testobjects|Format-List|Out-String
$result | Should Match "Name : name1"
$result | Should Match "Length : 1"
$result | Should Match "Name : name2"
$result | Should Match "Value : value2"
$result | Should Match "Length : 2"
$result | Should Match "Name : name3"
$result | Should Match "Length : 3"
}
}
@@ -0,0 +1,213 @@
Describe "Format-Table" {
It "Should call format table on piped input without error" {
{ Get-Date | Format-Table } | Should Not Throw
{ Get-Date | ft } | Should Not Throw
}
It "Should return a format object data type" {
$val = (Get-Date | Format-Table | gm )
$val2 = (Get-Date | Format-Table | gm )
$val.TypeName | Should Match "Microsoft.Powershell.Commands.Internal.Format"
$val2.TypeName | Should Match "Microsoft.Powershell.Commands.Internal.Format"
}
It "Should be able to be called with optional parameters" {
$v1 = (Get-Date | Format-Table *)
$v2 = (Get-Date | Format-Table -Property Hour)
$v3 = (Get-Date | Format-Table -GroupBy Hour)
$v12 = (Get-Date | ft *)
$v22 = (Get-Date | ft -Property Hour)
$v32 = (Get-Date | ft -GroupBy Hour)
}
}
Describe "Format-Table DRT Unit Tests" -Tags DRT{
It "Format-Table with not existing table with force should throw PipelineStoppedException"{
$obj = New-Object -typename PSObject
try
{
$obj | Format-Table -view bar -force -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo | Should Match "PipelineStoppedException"
$_.FullyQualifiedErrorId | Should be "FormatViewNotFound,Microsoft.PowerShell.Commands.FormatTableCommand"
}
}
It "Format-Table with array should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$al = (0..255)
$info = @{}
$info.array = $al
$result = $info|Format-Table|Out-String
$result | Should Match "array\s+{0, 1, 2, 3...}"
}
It "Format-Table with Negative Count should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$FormatEnumerationLimit = -1
$result = Format-Table -inputobject @{'test'= 1, 2}
$resultStr = $result|Out-String
$resultStr | Should Match "test\s+{1, 2}"
}
# Pending on issue#888
It "Format-Table with Zero Count should work" -Pending {
$FormatEnumerationLimit = 0
$result = Format-Table -inputobject @{'test'= 1, 2}
$resultStr = $result|Out-String
$resultStr | Should Match "test\s+{...}"
}
It "Format-Table with Less Count should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$FormatEnumerationLimit = 1
$result = Format-Table -inputobject @{'test'= 1, 2}
$resultStr = $result|Out-String
$resultStr | Should Match "test\s+{1...}"
}
It "Format-Table with More Count should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$FormatEnumerationLimit = 10
$result = Format-Table -inputobject @{'test'= 1, 2}
$resultStr = $result|Out-String
$resultStr | Should Match "test\s+{1, 2}"
}
It "Format-Table with Equal Count should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$FormatEnumerationLimit = 2
$result = Format-Table -inputobject @{'test'= 1, 2}
$resultStr = $result|Out-String
$resultStr | Should Match "test\s+{1, 2}"
}
# Pending on issue#888
It "Format-Table with Bogus Count should throw Exception" -Pending {
$FormatEnumerationLimit = "abc"
$result = Format-Table -inputobject @{'test'= 1, 2}
$resultStr = $result|Out-String
$resultStr | Should Match "test\s+{1, 2}"
}
# Pending on issue#888
It "Format-Table with Var Deleted should throw Exception" -Pending {
$FormatEnumerationLimit = 2
Remove-Variable FormatEnumerationLimit
$result = Format-Table -inputobject @{'test'= 1, 2}
$resultStr = $result|Out-String
$resultStr | Should Match "test\s+{1, 2}"
}
It "Format-Table with new line should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$info = @{}
$info.name = "1\n2"
$result = $info|Format-Table|Out-String
$result | Should Match "name\s+1.+2"
}
It "Format-Table with ExposeBug920454 should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$IP1 = [System.Net.IPAddress]::Parse("1.1.1.1")
$IP2 = [System.Net.IPAddress]::Parse("4fde:0000:0000:0002:0022:f376:255.59.171.63")
$IPs = New-Object System.Collections.ArrayList
$IPs.Add($IP1)
$IPs.Add($IP2)
$info = @{}
$info.test = $IPs
$result = $info|Format-Table|Out-String
$result | Should Match "test\s+{1.1.1.1, 4fde::2:22:f376:ff3b:ab3f}"
}
It "Format-Table with Autosize should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$IP1 = [PSCustomObject]@{'name'='Bob';'size'=1234;'booleanValue'=$true;}
$IP2 = [PSCustomObject]@{'name'='Jim';'size'=5678;'booleanValue'=$false;}
$IPs = New-Object System.Collections.ArrayList
$IPs.Add($IP1)
$IPs.Add($IP2)
$result = $IPs|Format-Table -Autosize|Out-String
$result | Should Match "name size booleanValue"
$result | Should Match "---- ---- ------------"
$result | Should Match "Bob\s+1234\s+True"
$result | Should Match "Jim\s+5678\s+False"
}
It "Format-Table with No Objects for End-To-End should work"{
$p = @{}
$result = $p|Format-Table -Property "foo","bar"|Out-String
$result | Should BeNullOrEmpty
}
It "Format-Table with Null Objects for End-To-End should work"{
$p = $null
$result = $p|Format-Table -Property "foo","bar"|Out-String
$result | Should BeNullOrEmpty
}
#pending on issue#900
It "Format-Table with single line string for End-To-End should work" -pending{
$p = "single line string"
$result = $p|Format-Table -Property "foo","bar"|Out-String
$result | Should BeNullOrEmpty
}
#pending on issue#900
It "Format-Table with multiple line string for End-To-End should work" -pending{
$p = "Line1\nLine2"
$result = $p|Format-Table -Property "foo","bar"|Out-String
$result | Should BeNullOrEmpty
}
#pending on issue#900
It "Format-Table with string sequence for End-To-End should work" -pending{
$p = "Line1","Line2"
$result = $p|Format-Table -Property "foo","bar"|Out-String
$result | Should BeNullOrEmpty
}
#pending on issue#900
It "Format-Table with string sequence for End-To-End should work" -pending{
$p = "Line1","Line2"
$result = $p|Format-Table -Property "foo","bar"|Out-String
$result | Should BeNullOrEmpty
}
It "Format-Table with complex object for End-To-End should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
Add-Type -TypeDefinition "public enum MyDayOfWeek{Sun,Mon,Tue,Wed,Thr,Fri,Sat}"
$eto = New-Object MyDayOfWeek
$info = @{}
$info.intArray = 1,2,3,4
$info.arrayList = "string1","string2"
$info.enumerable = [MyDayOfWeek]$eto
$info.enumerableTestObject = $eto
$result = $info|Format-Table|Out-String
$result | Should Match "intArray\s+{1, 2, 3, 4}"
$result | Should Match "arrayList\s+{string1, string2}"
$result | Should Match "enumerable\s+Sun"
$result | Should Match "enumerableTestObject\s+Sun"
}
It "Format-Table with Expand Enumerable should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$obj1 = "x 0","y 0"
$obj2 = "x 1","y 1"
$objs = New-Object System.Collections.ArrayList
$objs.Add($obj1)
$objs.Add($obj2)
$mo = [PSCustomObject]@{name = "this is name";sub = $objs}
$result1 = $mo|Format-Table -Expand CoreOnly|Out-String
$result1 | Should Match "name\s+sub"
$result1 | Should Match "this is name"
$result2 = $mo|Format-Table -Expand EnumOnly|Out-String
$result2 | Should Match "name\s+sub"
$result2 | Should Match "this is name\s+{x 0 y 0, x 1 y 1}"
$result3 = $mo|Format-Table -Expand Both|Out-String
$result3 | Should Match "name\s+sub"
$result3 | Should Match "this is name\s+{x 0 y 0, x 1 y 1}"
}
}
@@ -0,0 +1,113 @@
Describe "Format-Wide" {
It "Should have the same output between the alias and the unaliased function" {
$nonaliased = Get-ChildItem | Format-Wide
$aliased = Get-ChildItem | fw
$($nonaliased | Out-String).CompareTo($($aliased | Out-String)) | Should Be 0
}
It "Should be able to specify the columns in output using the column switch" {
{ Get-ChildItem | Format-Wide -Column 3 } | Should Not Throw
}
It "Should be able to use the autosize switch" {
{ Get-ChildItem | Format-Wide -Autosize } | Should Not Throw
}
It "Should be able to take inputobject instead of pipe" {
{ Format-Wide -InputObject $(Get-ChildItem) } | Should Not Throw
}
It "Should be able to use the property switch" {
{ Format-Wide -InputObject $(Get-ChildItem) -Property Mode } | Should Not Throw
}
It "Should throw an error when property switch and view switch are used together" {
try
{
Format-Wide -InputObject $(Get-ChildItem) -Property CreationTime -View aoeu
}
catch
{
$_.FullyQualifiedErrorId | Should be "FormatCannotSpecifyViewAndProperty,Microsoft.PowerShell.Commands.FormatWideCommand"
}
}
It "Should throw and suggest proper input when view is used with invalid input without the property switch" {
{ Format-Wide -InputObject $(Get-Process) -View aoeu } | Should Throw
}
}
Describe "Format-Wide DRT basic functionality" -Tags DRT{
It "Format-Wide with array should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$al = (0..255)
$info = @{}
$info.array = $al
$result = $info | Format-Wide | Out-String
$result | Should Match "array"
}
It "Format-Wide with No Objects for End-To-End should work"{
$p = @{}
$result = $p | Format-Wide | Out-String
$result | Should BeNullOrEmpty
}
It "Format-Wide with Null Objects for End-To-End should work"{
$p = $null
$result = $p | Format-Wide | Out-String
$result | Should BeNullOrEmpty
}
It "Format-Wide with single line string for End-To-End should work"{
$p = "single line string"
$result = $p | Format-Wide | Out-String
$result | Should Match $p
}
It "Format-Wide with multiple line string for End-To-End should work"{
$p = "Line1\nLine2"
$result = $p | Format-Wide | Out-String
$result | Should Match "Line1"
$result | Should Match "Line2"
}
It "Format-Wide with string sequence for End-To-End should work"{
$p = "Line1","Line2"
$result = $p |Format-Wide | Out-String
$result | Should Match "Line1"
$result | Should Match "Line2"
}
It "Format-Wide with complex object for End-To-End should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
Add-Type -TypeDefinition "public enum MyDayOfWeek{Sun,Mon,Tue,Wed,Thr,Fri,Sat}"
$eto = New-Object MyDayOfWeek
$info = @{}
$info.intArray = 1,2,3,4
$info.arrayList = "string1","string2"
$info.enumerable = [MyDayOfWeek]$eto
$info.enumerableTestObject = $eto
$result = $info|Format-Wide|Out-String
$result | Should Match "intArray"
$result | Should Match "arrayList"
$result | Should Match "enumerable"
$result | Should Match "enumerableTestObject"
}
It "Format-Wide with multiple same class object with grouping should work" -Pending:($env:TRAVIS_OS_NAME -eq "osx"){
Add-Type -TypeDefinition "public class TestGroupingClass{public TestGroupingClass(string name,int length){Name = name;Length = length;}public string Name;public int Length;public string GroupingKey;}"
$testobject1 = [TestGroupingClass]::New('name1',1)
$testobject1.GroupingKey = "foo"
$testobject2 = [TestGroupingClass]::New('name2',2)
$testobject1.GroupingKey = "bar"
$testobject3 = [TestGroupingClass]::New('name3',3)
$testobject1.GroupingKey = "bar"
$testobjects = @($testobject1,$testobject2,$testobject3)
$result = $testobjects|Format-Wide -GroupBy GroupingKey|Out-String
$result | Should Match "GroupingKey: bar"
$result | Should Match "name1"
$result | Should Match " GroupingKey:"
$result | Should Match "name2\s+name3"
}
}
@@ -0,0 +1,214 @@
Describe "Get-Alias DRT Unit Tests" -Tags DRT{
It "Get-Alias Bogus Scope Name should throw PSArgumentException"{
try {
Get-Alias -Name "ABCD" -Scope "bogus"
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "Argument,Microsoft.PowerShell.Commands.GetAliasCommand"
}
}
It "Get-Alias OutOfRange Scope"{
try {
Get-Alias -Name "ABCD" -Scope "99999"
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "ArgumentOutOfRange,Microsoft.PowerShell.Commands.GetAliasCommand"
}
}
It "Get-Alias Named Single Valid"{
Set-Alias -Name ABCD -Value "foo"
$result=Get-Alias -Name ABCD
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
}
It "Get-Alias Positional Single Valid"{
Set-Alias -Name ABCD -Value "foo"
$result=Get-Alias ABCD
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
}
It "Get-Alias Named Multiple Valid"{
Set-Alias -Name ABCD -Value "foo"
Set-Alias -Name AEFG -Value "bar"
$result=Get-Alias -Name ABCD,AEFG
$result[0].Name| Should Be "ABCD"
$result[0].Definition| Should Be "foo"
$result[0].Description| Should Be ""
$result[0].Options| Should Be "None"
$result[1].Name| Should Be "AEFG"
$result[1].Definition| Should Be "bar"
$result[1].Description| Should Be ""
$result[1].Options| Should Be "None"
}
It "Get-Alias Named Wildcard Valid"{
Set-Alias -Name ABCD -Value "foo"
Set-Alias -Name ABCG -Value "bar"
$result=Get-Alias -Name ABC*
$result[0].Name| Should Be "ABCD"
$result[0].Definition| Should Be "foo"
$result[0].Description| Should Be ""
$result[0].Options| Should Be "None"
$result[1].Name| Should Be "ABCG"
$result[1].Definition| Should Be "bar"
$result[1].Description| Should Be ""
$result[1].Options| Should Be "None"
}
It "Get-Alias Positional Wildcard Valid"{
Set-Alias -Name ABCD -Value "foo"
Set-Alias -Name ABCG -Value "bar"
$result=Get-Alias ABC*
$result[0].Name| Should Be "ABCD"
$result[0].Definition| Should Be "foo"
$result[0].Description| Should Be ""
$result[0].Options| Should Be "None"
$result[1].Name| Should Be "ABCG"
$result[1].Definition| Should Be "bar"
$result[1].Description| Should Be ""
$result[1].Options| Should Be "None"
}
It "Get-Alias Named Wildcard And Exclude Valid"{
Set-Alias -Name ABCD -Value "foo"
Set-Alias -Name ABCG -Value "bar"
$result=Get-Alias -Name ABC* -Exclude "*BCG"
$result[0].Name| Should Be "ABCD"
$result[0].Definition| Should Be "foo"
$result[0].Description| Should Be ""
$result[0].Options| Should Be "None"
}
It "Get-Alias Scope Valid"{
Set-Alias -Name ABCD -Value "foo"
$result=Get-Alias -Name ABCD
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
Set-Alias -Name ABCD -Value "localfoo" -scope local
$result=Get-Alias -Name ABCD -scope local
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "localfoo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
Set-Alias -Name ABCD -Value "globalfoo" -scope global
Set-Alias -Name ABCD -Value "scriptfoo" -scope "script"
Set-Alias -Name ABCD -Value "foo0" -scope "0"
Set-Alias -Name ABCD -Value "foo1" -scope "1"
$result=Get-Alias -Name ABCD
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo0"
$result.Description| Should Be ""
$result.Options| Should Be "None"
$result=Get-Alias -Name ABCD -scope local
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo0"
$result.Description| Should Be ""
$result.Options| Should Be "None"
$result=Get-Alias -Name ABCD -scope global
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "globalfoo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
$result=Get-Alias -Name ABCD -scope "script"
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "scriptfoo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
$result=Get-Alias -Name ABCD -scope "0"
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo0"
$result.Description| Should Be ""
$result.Options| Should Be "None"
$result=Get-Alias -Name ABCD -scope "1"
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo1"
$result.Description| Should Be ""
$result.Options| Should Be "None"
}
It "Get-Alias Expose Bug 1065828, BugId:905235"{
try {
Get-Alias -Name "ABCD" -Scope "100"
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "ArgumentOutOfRange,Microsoft.PowerShell.Commands.GetAliasCommand"
}
}
It "Get-Alias Zero Scope Valid"{
Set-Alias -Name ABCD -Value "foo"
$result=Get-Alias -Name ABCD
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
$result=Get-Alias -Name ABCD -scope "0"
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
}
It "Test get-alias with Definition parameter" {
$returnObject = Get-Alias -Definition Get-Command
For($i = 0; $i -lt $returnObject.Length;$i++)
{
$returnObject[$i] | Should Not BeNullOrEmpty
$returnObject[$i].CommandType | Should Be 'Alias'
$returnObject[$i].Definition | Should Be 'Get-Command'
}
}
}
Describe "Get-Alias" {
It "Should have a return type of System.Array when gal returns more than one object" {
$val1=(Get-Alias a*)
$val2=(Get-Alias c*)
$i=0
$val1 | ForEach-Object{ $i++};
if($i -lt 2) {
$val1.GetType().BaseType.FullName | Should Be "System.Management.Automation.CommandInfo"
}
else
{
$val1.GetType().BaseType.FullName | Should Be "System.Array"
}
$val2 | ForEach-Object{ $i++};
if($i -lt 2) {
$val2.GetType().BaseType.FullName | Should Be "System.Management.Automation.CommandInfo"
}
else
{
$val2.GetType().BaseType.FullName | Should Be "System.Array"
}
}
It "should return an array of 3 objects" {
$val = Get-Alias a*
$alias = gal a*
$val.CommandType | Should Not BeNullOrEmpty
$val.Name | Should Not BeNullOrEmpty
$val.ModuleName | Should BeNullOrEmpty
$alias.CommandType | Should Not BeNullOrEmpty
$alias.Name | Should Not BeNullOrEmpty
$alias.ModuleName | Should BeNullOrEmpty
}
}
@@ -0,0 +1,24 @@
Describe "Get-Culture DRT Unit Tests" -Tags DRT{
It "Should works proper with get-culture" {
$results = get-Culture
$results -is "System.Globalization.CultureInfo" | Should be $true
$results[0].Name | Should Be $PSCulture
}
}
Describe "Get-Culture" {
It "Should return a type of CultureInfo for Get-Culture cmdlet" {
(Get-Culture).GetType() | Should Be CultureInfo
}
It "Should have $ culture variable be equivalent to (Get-Culture).Name" {
(Get-Culture).Name | Should Be $PsCulture
}
}
@@ -0,0 +1,118 @@
Describe "Get-Date DRT Unit Tests" -Tags DRT {
It "Get-Date with all parameters returns proper results" {
$date = [datetime]::Now + ([timespan]::new(0,0,30))
$result = Get-Date -Date $date -Year 1973 -Month 2 -Day 22 -Hour 15 -Minute 40 -Second 10 -Millisecond 200
$result.GetType() | Should be ([Datetime])
$result.Year | Should be 1973
$result.Month| Should be 2
$result.Day | Should be 22
$result.Hour | Should be 15
$result.Minute | Should be 40
$result.Second | Should be 10
$result.Millisecond | Should be 200
}
It "using -displayhint produces the correct output" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$d = Get-date -Date:"Jan 1, 2020" -DisplayHint Date | Out-String
$d.Trim() | Should be "Wednesday, January 1, 2020"
}
It "using -format produces the correct output" {
Get-date -Date:"Jan 1, 2020" -Format:"MMM-dd-yy" | Should be "Jan-01-20"
}
It "using -uformat produces the correct output" {
Get-date -Date:"Jan 1, 2020" -UFormat:"%s" | Should be "1577836800"
}
It "using -uformat 'ymdH' produces the correct output" {
Get-date -Date 0030-01-01T00:00:00 -uformat %y/%m/%d-%H | Should be "30/01/01-00"
}
It "using -uformat 'aAbBcCdDehHIjmMpr' produces the correct output" {
Get-date -Date 1/1/0030 -uformat %a%A%b%B%c%C%d%D%e%h%H%I%j%m%M%p%r | Should be "TueTuesdayJanJanuaryTue Jan 1 00:00:00 003000101/01/30 1Jan001210100AM12:00:00 AM"
}
It "using -uformat 'StTuUVwWxXyYZ' produces the correct output" {
Get-date -Date 1/1/0030 -uformat %S%T%u%U%V%w%W%x%X%y%Y%% | Should be "0000:00:002012001/01/3000:00:00300030%"
}
It "Get-date works with pipeline input" {
$x = new-object System.Management.Automation.PSObject
$x | add-member NoteProperty Date ([DateTime]::Now)
$y = @($x,$x)
($y | Get-date).Length | Should be 2
}
It "the LastWriteTime alias works with pipeline input" {
$folder = "GetDateTest"
$pathString = Join-Path -Path $TestDrive -ChildPath $folder
New-Item -Path $TestDrive -Name $folder -ItemType directory -Force
for($i = 0; $i -lt 10; $i++)
{
$temp = [guid]::NewGuid()
$pathString2 = Join-Path -Path $pathString -ChildPath $temp
New-Item -Path $pathString -Name $temp -ItemType file -Force
for($j = 0; $j -lt 100; $j++)
{
Add-Content -Path $pathString2 -Value $j
}
}
$result1 = get-childitem -path $pathString | get-date
$result2 = get-childitem -path $pathString | get-date
$result1.Length | Should be 10
$result1.Length -eq $result2.Length | Should be $true
for($i = 0; $i -lt $result1.Length; $i++)
{
$result1[$i] -eq $result2[$i] | Should be $true
}
Get-ChildItem -Path $pathString | Remove-Item
Remove-Item -Path $pathString -Force -Recurse
}
}
Describe "Get-Date" {
It "Should return a DateTime object upon being called" {
(Get-Date).GetType().Name.Equals('DateTime') | Should Be $true
}
It "Should have colons when ToString method is used" {
(Get-Date).ToString().Contains(":") | Should be $true
(Get-Date -DisplayHint Time).ToString().Contains(":") | Should be $true
(Get-Date -DisplayHint Date).ToString().Contains(":") | Should be $true
}
It "Should be able to use the format flag" {
# You would think that one could use simple loops here, but apparently powershell in Windows returns different values in loops
(Get-Date -Format d).Contains("/") | Should be $true
(Get-Date -Format D).Contains(",") | Should be $true
(Get-Date -Format f).Contains(",") -and (Get-Date -Format f).Contains(":") | Should be $true
(Get-Date -Format F).Contains(",") -and (Get-Date -Format F).Contains(":") | Should be $true
(Get-Date -Format g).Contains("/") -and (Get-Date -Format g).Contains(":") | Should be $true
(Get-Date -Format G).Contains("/") -and (Get-Date -Format G).Contains(":") | Should be $true
(Get-Date -Format m).Contains(",") -or `
(Get-Date -Format m).Contains(":") -or `
(Get-Date -Format m).Contains("/") | Should be $false
}
It "Should check that Get-Date can return the correct datetime from the system time" {
$timeDifference = $(Get-Date).Subtract([System.DateTime]::Now)
$timeDifference.Days | Should Be 0
$timeDifference.Hours | Should Be 0
$timeDifference.Minutes | Should Be 0
$timeDifference.Milliseconds | Should BeLessThan 1
$timeDifference.Ticks | Should BeLessThan 10000
}
}
@@ -0,0 +1,33 @@
Describe "Get-Event" {
BeforeEach {
( New-Event -SourceIdentifier PesterTestEvent -sender Windows.timer -messagedata "PesterTestMessage" )
}
AfterEach {
( Remove-Event -SourceIdentifier PesterTestEvent -ErrorAction SilentlyContinue )
}
Context "Check return type of Get-Event" {
It "Should return PSEventArgs as return type of Get-Event" {
{ ( Get-Event -SourceIdentifier PesterTestEvent ).GetType() | Should Be System.Management.Automation.PSEventArgs }
}
}
Context "Validate Get-Event can retrieve event" {
It "Should return at least 1 event" {
{ (Get-Event).Count | Should BeGreaterThan 0 }
}
It "Should return PesterTestMessage as the MessageData" {
{ (Get-Event -SourceIdentifier PesterTimer).MessageData | Should Be "PesterTestMessage" }
}
It "Should return Sender as Windows.timer" {
{ (Get-Event -SourceIdentifier PesterTimer).Sender | Should be Windows.timer }
}
}
}
@@ -0,0 +1,30 @@
Describe "Get-EventSubscriber" {
AfterEach {
Unregister-Event -SourceIdentifier PesterTestRegister -ErrorAction SilentlyContinue
}
Context "Check return type of Get-EventSubscriber" {
It "Should return System.Management.Automation.PSEventSubscriber as return type of New-Event" {
$pesterobject = (New-Object System.Collections.ObjectModel.ObservableCollection[object])
Register-ObjectEvent -InputObject $pesterobject -EventName CollectionChanged -SourceIdentifier PesterTestRegister
(Get-EventSubscriber).GetType() | Should Be System.Management.Automation.PSEventSubscriber
}
}
Context "Check Get-EventSubscriber can validly register events"{
It "Should return source identifier of PesterTimer " {
$pesterobject = (New-Object System.Collections.ObjectModel.ObservableCollection[object])
Register-ObjectEvent -InputObject $pesterobject -EventName CollectionChanged -SourceIdentifier PesterTestRegister
(Get-EventSubscriber -SourceIdentifier PesterTestRegister).SourceIdentifier | Should Be "PesterTestRegister"
}
It "Should return an integer greater than 0 for the SubscriptionId" {
$pesterobject = (New-Object System.Collections.ObjectModel.ObservableCollection[object])
Register-ObjectEvent -InputObject $pesterobject -EventName CollectionChanged -SourceIdentifier PesterTestRegister
(Get-EventSubscriber -SourceIdentifier PesterTestRegister).SubscriptionId | Should BeGreaterThan 0
}
}
}
@@ -0,0 +1,49 @@
Describe "Get-FileHash" {
New-Variable testDocument -Value (Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath assets) -ChildPath testablescript.ps1) -Scope Global -Force
# The MACTripleDES and RIPEMD160 algorithms are unsupported on Linux
$algorithms = @{"SHA1" ="01B865D143E07ECC875AB0EFC0A4429387FD0CF7";
"SHA256" = "4A6DA9F1C0827143BB19FC4B0F2A8057BC1DF55F6D1F62FA3B917BA458E8F570";
"SHA384" = "656215B6A07011E625206F43E57873F49AD7B36DFCABB70F6CDCE2303D7A603E55D052774D26F339A6D80A264340CB8C";
"SHA512" = "C688C33027D89ACAC920545471C8053D8F64A54E21D0415F1E03766DDCDA215420E74FAFD1DC399864C6B6B5723A3358BD337339906797A39090B02229BF31FE";
"MD5" = "7B09811D1631C9FD46B39D1D35522F0A";
}
Context "Cmdlet result tests" {
It "Should default to correct hash algorithm" {
$result = Get-FileHash $testDocument
$result.Algorithm | Should Be "SHA256"
}
It "Should be able to set the default hash algorithm" {
$PSDefaultParameterValues.add("Get-FileHash:Algorithm","MD5")
$result = Get-FileHash $testDocument
$result.Algorithm | Should Be "MD5"
$PSDefaultParameterValues.Remove("Get-FileHash:Algorithm")
}
It "Should list the path of the file under test" {
$result = Get-FileHash $testDocument
$result.Path | Should Be $testDocument
}
}
Context "Algorithm tests" {
It "Should be able to get the correct hash from each algorithm" {
foreach ( $algorithm in $algorithms.Keys)
{
$algorithmResult = Get-FileHash $testDocument -Algorithm $algorithm
$algorithmResult.Hash | Should Be $algorithms[$algorithm]
}
#MACTripleDES and RIPEMD160 are unsupported in the existing Pester tests from Windows team
{ Get-FileHash $testDocument -Algorithm MACTripleDES } | Should Throw "Algorithm 'MACTripleDES' is not supported in this system."
{ Get-FileHash $testDocument -Algorithm RIPEMD160 } | Should Throw "Algorithm 'RIPEMD160' is not supported in this system."
}
}
}
@@ -0,0 +1,13 @@
Describe "Get-FormatData" {
Context "Check return type of Get-FormatData" {
It "Should return an object[] as the return type" {
(Get-FormatData).GetType() | Should be System.Object[]
}
It "Should return a System.Object[] with a count greater than 0" {
(Get-formatData).Count | Should BeGreaterThan 0
}
}
}
@@ -0,0 +1,21 @@
Describe "Get-Host DRT Unit Tests" -Tags DRT{
It "Should works proper with get-host" {
$results = Get-Host
$results | Should Be $Host
$results.GetType().Name | Should Be InternalHost
}
}
Describe "Get-Host" {
It "Should return a type of InternalHost for Get-Host cmdlet" {
(Get-Host).GetType().Name | Should Be InternalHost
}
It "Should have $ host variable be equivalent to Get-Host object" {
Get-Host | Should Be $host
}
}
@@ -0,0 +1,294 @@
Describe "Get-Member" {
It "Should be able to be called on string objects, ints, arrays, etc" {
$a = 1 #test numbers
$b = 1.3
$c = $false #test bools
$d = @(1,3) # test arrays
$e = "anoeduntodeu" #test strings
$f = 'asntoheusth' #test strings
Get-Member -InputObject $a | Should Not BeNullOrEmpty
Get-Member -InputObject $b | Should Not BeNullOrEmpty
Get-Member -InputObject $c | Should Not BeNullOrEmpty
Get-Member -InputObject $d | Should Not BeNullOrEmpty
Get-Member -InputObject $e | Should Not BeNullOrEmpty
Get-Member -InputObject $f | Should Not BeNullOrEmpty
}
It "Should be able to extract a field from string objects, ints, arrays, etc" {
$a = 1 #test numbers
$b = 1.3
$c = $false #test bools
$d = @(1,3) # test arrays
$e = "anoeduntodeu" #test strings
$f = 'asntoheusth' #test strings
$a.GetType().Name | Should Be 'Int32'
$b.GetType().Name | Should Be 'Double'
$c.GetType().Name | Should Be 'Boolean'
$d.GetType().Name | Should Be 'Object[]'
$e.GetType().Name | Should Be 'String'
$f.GetType().Name | Should Be 'String'
}
It "Should be able to be called on a newly created PSObject" {
$o = New-Object psobject
# this creates a dependency on the Add-Member cmdlet.
Add-Member -InputObject $o -MemberType NoteProperty -Name proppy -Value "superVal"
Get-Member -InputObject $o | Should Not BeNullOrEmpty
}
}
Describe "Get-Member DRT Unit Tests" -Tags DRT {
Context "Verify Get-Member with Class" {
if(-not ([System.Management.Automation.PSTypeName]'Employee').Type)
{
Add-Type -TypeDefinition @"
public class Employee
{
private string firstName;
private string lastName;
private int yearsInMS;
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
public int YearsInMS
{
get
{
return yearsInMS;
}
set
{
yearsInMS = value;
}
}
public Employee(string firstName, string lastName, int yearsInMS)
{
this.firstName = firstName;
this.lastName = lastName;
this.yearsInMS = yearsInMS;
}
}
"@
}
$fileToDeleteName = Join-Path $TestDrive -ChildPath "getMemberTest.ps1xml"
$XMLFile= @"
<Types>
<Type>
<Name>Employee</Name>
<Members>
<PropertySet>
<Name>PropertySetName</Name>
<ReferencedProperties>
<Name>FirstName</Name>
<Name>LastName</Name>
</ReferencedProperties>
</PropertySet>
<PropertySet>
<Name>FullSet</Name>
<ReferencedProperties>
<Name>FirstName</Name>
<Name>LastName</Name>
<Name>YearsInMS</Name>
</ReferencedProperties>
</PropertySet>
</Members>
</Type>
<Type>
<Name>EmployeePartTime</Name>
<Members>
<PropertySet>
<Name>PropertySetName</Name>
<ReferencedProperties>
<Name>FirstName</Name>
<Name>HoursPerWeek</Name>
</ReferencedProperties>
</PropertySet>
<PropertySet>
<Name>FullSet</Name>
<ReferencedProperties>
<Name>FirstName</Name>
<Name>LastName</Name>
<Name>HoursPerWeek</Name>
</ReferencedProperties>
</PropertySet>
</Members>
</Type>
</Types>
"@
$XMLFile > $fileToDeleteName
Update-TypeData -AppendPath $fileToDeleteName
It "Fail to get member without any input" {
try
{
Get-Member -MemberType All -ErrorAction Stop
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be 'NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand'
}
}
It 'Get the expected Properties of "Employee" object' {
$emps = [Employee]::New("john", "smith", 5), [Employee]::New("joesph", "smith", 15), [Employee]::New("john", "smyth", 2)
$results = $emps | Get-Member -MemberType Property
$results.Length | Should Be 3
$results[0].Name | Should Be "FirstName"
$results[1].Name | Should Be "LastName"
$results[2].Name | Should Be "YearsInMS"
}
It 'Get the Public Methods of "Employee" object' {
$emps = [Employee]::New("john", "smith", 5), [Employee]::New("joesph", "smith", 15), [Employee]::New("john", "smyth", 2)
$methodList = "GetHashCode", "Equals", "ToString", "GetType"
$results = $emps | Get-Member -MemberType Method
$results.Length | Should Be $methodList.Length
$methodFound = @()
for ($i = 0;$i -lt $methodList.Length;$i++)
{
for ($j = 0;$j -lt $results.Length;$j++)
{
if ($results[$j].Name.Equals($methodList[$i]))
{
$methodFound += $true
}
}
}
for ($i = 0;$i -lt $methodList.Length;$i++)
{
$methodFound[$i] | Should Be $true
}
}
It 'Get property sets defined in private members' {
$emps = [Employee]::New("john", "smith", 5), [Employee]::New("joesph", "smith", 15), [Employee]::New("john", "smyth", 2)
$results = $emps | Get-Member -MemberType PropertySet
$results.Length | Should Be 2
$results[0].Name | Should Be "FullSet"
$results[1].Name | Should Be "PropertySetName"
}
}
Context "Verify Get-Member with Static Parameter" {
It 'Get the static properties and methods of the object' {
$obj = New-Object -TypeName System.Int32
$results = $obj | Get-Member -Static
$members = "MaxValue", "MinValue", "Parse", "TryParse"
foreach ($member in $members)
{
foreach ($result in $results)
{
if($result.Name.Equals($member))
{
return $true
}
}
return $false
}
}
It "Get the static properties and methods of int instance" {
$results = 1 | Get-Member -Static
$members = "MaxValue", "MinValue", "Parse", "TryParse"
foreach ($member in $members)
{
foreach ($result in $results)
{
if($result.Name.Equals($member))
{
return $true
}
}
return $false
}
}
It "Get the static properties and methods of int instance Wrapped" {
$results = [pscustomobject]1 | Get-Member -Static
$members = "MaxValue", "MinValue", "Parse", "TryParse"
foreach ($member in $members)
{
foreach ($result in $results)
{
if($result.Name.Equals($member))
{
return $true
}
}
return $false
}
}
}
Context "Verify Get-Member with other parameters" {
It 'works with View Parameter' {
$results = [xml]'<a>some text</a>' | Get-Member -view adapted
$results.Length | Should Be 38
}
It 'Get hidden members'{
$results = 'abc' | Get-Member -force
$hiddenMembers = "psbase", "psextended", "psadapted", "pstypenames", "psobject"
foreach ($member in $hiddenMembers)
{
foreach ($result in $results)
{
if($result.Name.Equals($member))
{
return $true
}
}
return $false
}
}
It 'Get Set Property Accessors On PsBase'{
$results = ('abc').psbase | Get-Member -force get_*
$expectedMembers = "get_Chars", "get_Length"
foreach ($member in $expectedMembers)
{
foreach ($result in $results)
{
if($result.Name.Equals($member))
{
return $true
}
}
return $false
}
}
}
}
@@ -0,0 +1,30 @@
Describe "Get-PSBreakpoint" {
$scriptName = "Get-PSBreakpoint.Tests.ps1"
$fullScriptPath = Join-Path -Path $PSScriptRoot -ChildPath $scriptName
AfterEach {
Get-PSBreakpoint -Script $fullScriptPath | Remove-PSBreakpoint
}
It "should be able to get PSBreakpoint with using Id switch" {
Set-PSBreakpoint -Script $fullScriptPath -Line 1
{ Get-PSBreakpoint -Script $fullScriptPath } | Should Not Throw
$Id = (Get-PSBreakpoint -Script $fullScriptPath).Id
$Id | Should be 0
}
It "sshould be able to get PSBreakpoint with using Variable switch" {
Set-PSBreakpoint -Script $fullScriptPath -Variable "$scriptName"
{ Get-PSBreakpoint -Variable "$scriptName" -Script $fullScriptPath } | Should Not Throw
$Id = (Get-PSBreakpoint -Variable "$scriptName" -Script $fullScriptPath).Variable
$Id | Should be $scriptName
}
}
@@ -0,0 +1,87 @@
Describe "Get-PSCallStack DRT Unit Tests" -Tags DRT {
BeforeAll {
$scriptFileName = "GetTryCatchCallStack.ps1"
$scriptFilePath = Join-Path $TestDrive -ChildPath $scriptFileName
}
It "Verifies that the script block of a catch clause does not show up on the call stack" {
$fileStream = @"
function foo()
{
try
{
throw 1
}
catch
{
bar
}
}
function bar()
{
try
{
throw 1
}
catch
{
try
{
throw 1
}
catch
{
Get-PSCallStack
}
}
}
foo
"@
$fileStream > $scriptFilePath
$results = & "$scriptFilePath"
$results.Count | Should BeGreaterThan 3
$results[0].Command | Should be "bar"
$results[0].ScriptName | Should be $scriptFilePath
$results[0].ScriptLineNumber | Should be 27
$results[0].InvocationInfo.ScriptLineNumber | Should be 9
$results[1].Command | Should be "foo"
$results[1].ScriptName | Should be $scriptFilePath
$results[1].ScriptLineNumber | Should be 9
$results[1].InvocationInfo.ScriptLineNumber | Should be 32
#InvocationInfo.ScriptLineNumber: Gets the line number of the script that contains the command
$results[2].Command | Should be $scriptFileName
$results[2].ScriptName | Should be $scriptFilePath
$results[2].ScriptLineNumber | Should be 32
$results[2].InvocationInfo.ScriptLineNumber | Should be 44
}
It "Verify that the script block of a trap statement shows up on the call stack" {
$fileStream = @"
trap
{
Get-PSCallStack
continue
}
throw 1
"@
$fileStream > $scriptFilePath
$results = & "$scriptFilePath"
$results.Count | Should BeGreaterThan 2
$results[0].Command | Should be $scriptFileName
$results[0].ScriptName | Should be $scriptFilePath
$results[0].ScriptLineNumber | Should be 3
$results[0].InvocationInfo.ScriptLineNumber | Should be 75
$results[1].Command | Should be $scriptFileName
$results[1].ScriptName | Should be $scriptFilePath
$results[1].ScriptLineNumber | Should be 7
$results[1].InvocationInfo.ScriptLineNumber | Should be 75
}
}
@@ -0,0 +1,173 @@
Describe "Get-Random DRT Unit Tests" -Tags DRT{
$testData = @(
@{ Name = 'no params'; Maximum = $null; Minimum = $null; GreaterThan = -1; LessThan = ([int32]::MaxValue); Type = 'System.Int32' }
@{ Name = 'only positive maximum number'; Maximum = 100; Minimum = $null; GreaterThan = -1; LessThan = 100; Type = 'System.Int32' }
@{ Name = 'maximum set to 0, Minimum to a negative number'; Maximum = 0; Minimum = -100; GreaterThan = -101; LessThan = 0; Type = 'System.Int32' }
@{ Name = 'positive maximum, negative Minimum'; Maximum = 100; Minimum = -100; GreaterThan = -101; LessThan = 100; Type = 'System.Int32' }
@{ Name = 'both negative'; Maximum = -100; Minimum = -200; GreaterThan = -201; LessThan = -100; Type = 'System.Int32' }
@{ Name = 'both negative with parentheses'; Maximum = (-100); Minimum = (-200); GreaterThan = -201; LessThan = -100; Type = 'System.Int32' }
@{ Name = 'maximum enclosed in quote'; Maximum = '8'; Minimum = 5; GreaterThan = 4; LessThan = 8; Type = 'System.Int32' }
@{ Name = 'minimum enclosed in quote'; Maximum = 8; Minimum = '5'; GreaterThan = 4; LessThan = 8; Type = 'System.Int32' }
@{ Name = 'maximum with plus sign'; Maximum = +100; Minimum = 0; GreaterThan = -1; LessThan = 100; Type = 'System.Int32' }
@{ Name = 'maximum with plus sign and quote'; Maximum = '+100'; Minimum = 0; GreaterThan = -1; LessThan = 100; Type = 'System.Int32' }
@{ Name = 'both with quote'; Maximum = '+100'; Minimum = '-100'; GreaterThan = -101; LessThan = 100; Type = 'System.Int32' }
@{ Name = 'maximum set to kb'; Maximum = '1kb'; Minimum = 0; GreaterThan = -1; LessThan = 1024; Type = 'System.Int32' }
@{ Name = 'maximum is Int64.MaxValue'; Maximum = ([int64]::MaxValue); Minimum = $null; GreaterThan = ([int64]-1); LessThan = ([int64]::MaxValue); Type = 'System.Int64' }
@{ Name = 'maximum is a 64-bit integer'; Maximum = ([int64]100); Minimum = $null; GreaterThan = ([int64]-1); LessThan = ([int64]100); Type = 'System.Int64' }
@{ Name = 'maximum set to a large integer greater than int32.MaxValue'; Maximum = 100000000000; Minimum = $null; GreaterThan = ([int64]-1); LessThan = ([int64]100000000000); Type = 'System.Int64' }
@{ Name = 'maximum set to 0, Minumum set to a negative 64-bit integer'; Maximum = ([int64]0); Minimum = ([int64]-100); GreaterThan = ([int64]-101); LessThan = ([int64]0); Type = 'System.Int64' }
@{ Name = 'maximum set to positive 64-bit number, min set to negative 64-bit number'; Maximum = ([int64]100); Minimum = ([int64]-100); GreaterThan = ([int64]-101); LessThan = ([int64]100); Type = 'System.Int64' }
@{ Name = 'both are negative 64-bit number'; Maximum = ([int64]-100); Minimum = ([int64]-200); GreaterThan = ([int64]-201); LessThan = ([int64]-100); Type = 'System.Int64' }
@{ Name = 'both are negative 64-bit number with parentheses'; Maximum = ([int64](-100)); Minimum = ([int64](-200)); GreaterThan = ([int64]-201); LessThan = ([int64]-100); Type = 'System.Int64' }
@{ Name = 'max is 32-bit, min is 64-bit integer'; Maximum = '8'; Minimum = ([int64]5); GreaterThan = ([int64]4); LessThan = ([int64]8); Type = 'System.Int64' }
@{ Name = 'max is 64-bit, min is 32-bit integer'; Maximum = ([int64]8); Minimum = '5'; GreaterThan = ([int64]4); LessThan = ([int64]8); Type = 'System.Int64' }
@{ Name = 'max set to a 32-bit integer, min set to [int64]0'; Maximum = +100; Minimum = ([int64]0); GreaterThan = ([int64]-1); LessThan = ([int64]100); Type = 'System.Int64' }
@{ Name = 'max set to a 32-bit integer with quote'; Maximum = '+100'; Minimum = ([int64]0); GreaterThan = ([int64]-1); LessThan = ([int64]100); Type = 'System.Int64' }
@{ Name = 'max is [int64]0, min is a 32-bit integer'; Maximum = ([int64]0); Minimum = '-100'; GreaterThan = ([int64]-101); LessThan = ([int64]0); Type = 'System.Int64' }
@{ Name = 'min set to 1MB, max set to a 64-bit integer greater than min'; Maximum = ([int64]1048585); Minimum = '1mb'; GreaterThan = ([int64]1048575); LessThan = ([int64]1048585); Type = 'System.Int64' }
@{ Name = 'max set to 1tb, min set to 10 mb'; Maximum = '1tb'; Minimum = '10mb'; GreaterThan = ([int64]10485759); LessThan = ([int64]1099511627776); Type = 'System.Int64' }
@{ Name = 'max is int64.MaxValue, min is Int64.MinValue'; Maximum = ([int64]::MaxValue); Minimum = ([int64]::MinValue); GreaterThan = ([int64]::MinValue); LessThan = ([int64]::MaxValue); Type = 'System.Int64' }
@{ Name = 'both are int64.MaxValue plus a 32-bit integer'; Maximum = ([int64](([int]::MaxValue)+15)); Minimum = ([int64](([int]::MaxValue)+10)); GreaterThan = ([int64](([int]::MaxValue)+9)); LessThan = ([int64](([int]::MaxValue)+15)); Type = 'System.Int64' }
@{ Name = 'both are greater than int32.MaxValue without specified type, and max with quote'; Maximum = '100099000001'; Minimum = 100000000001; GreaterThan = ([int64]10000000000); LessThan = ([int64]100099000001); Type = 'System.Int64' }
@{ Name = 'both are greater than int32.MaxValue without specified type, and min with quote'; Maximum = 100000002230; Minimum = '100000002222'; GreaterThan = ([int64]100000002221); LessThan = ([int64]100000002230); Type = 'System.Int64' }
@{ Name = 'max is greater than int32.MaxValue without specified type'; Maximum = 90000000000; Minimum = 4; GreaterThan = ([int64]3); LessThan = ([int64]90000000000); Type = 'System.Int64' }
@{ Name = 'max is a double-precision number'; Maximum = 100.0; Minimum = $null; GreaterThan = -1.0; LessThan = 100.0; Type = 'System.Double' }
@{ Name = 'both are double-precision numbers, min is negative.'; Maximum = 0.0; Minimum = -100.0; GreaterThan = -101.0; LessThan = 0.0; Type = 'System.Double' }
@{ Name = 'both are double-precision number, max is positive, min is negative.'; Maximum = 100.0; Minimum = -100.0; GreaterThan = -101.0; LessThan = 100.0; Type = 'System.Double' }
@{ Name = 'max is a double-precision number, min is int32'; Maximum = 8.0; Minimum = 5; GreaterThan = 4.0; LessThan = 8.0; Type = 'System.Double' }
@{ Name = 'min is a double-precision number, max is int32'; Maximum = 8; Minimum = 5.0; GreaterThan = 4.0; LessThan = 8.0; Type = 'System.Double' }
@{ Name = 'max set to a special double number'; Maximum = 20.; Minimum = 0.0; GreaterThan = -1.0; LessThan = 20.0; Type = 'System.Double' }
@{ Name = 'max is double with quote'; Maximum = '20.'; Minimum = 0.0; GreaterThan = -1.0; LessThan = 20.0; Type = 'System.Double' }
@{ Name = 'max is double with plus sign'; Maximum = +100.0; Minimum = 0; GreaterThan = -1.0; LessThan = 100.0; Type = 'System.Double' }
@{ Name = 'max is doulbe with plus sign and enclosed in quote'; Maximum = '+100.0'; Minimum = 0; GreaterThan = -1.0; LessThan = 100.0; Type = 'System.Double' }
@{ Name = 'both set to the special numbers as 1.0e+xx '; Maximum = $null; Minimum = 1.0e+100; GreaterThan = 1.0e+99; LessThan = ([double]::MaxValue); Type = 'System.Double' }
@{ Name = 'max is Double.MaxValue, min is Double.MinValue'; Maximum = ([double]::MaxValue); Minimum = ([double]::MinValue); GreaterThan = ([double]::MinValue); LessThan = ([double]::MaxValue); Type = 'System.Double' }
)
$testDataForError = @(
@{ Name = 'Min is greater than max and all are positive 32-bit integer'; Maximum = 10; Minimum = 20}
@{ Name = 'Min and Max are same and all are positive 32-bit integer'; Maximum = 20; Minimum = 20}
@{ Name = 'Min is greater than max and all are negative 32-bit integer'; Maximum = -20; Minimum = -10}
@{ Name = 'Min and Max are same and all are negative 32-bit integer'; Maximum = -20; Minimum = -20}
@{ Name = 'Min is greater than max and all are positive double-precision number'; Maximum = 10.0; Minimum = 20.0}
@{ Name = 'Min and Max are same and all are positive double-precision number'; Maximum = 20.0; Minimum = 20.0}
@{ Name = 'Min is greater than max and all are negative double-precision number'; Maximum = -20.0; Minimum = -10.0}
@{ Name = 'Min and Max are same and all are negative double-precision number'; Maximum = -20.0; Minimum = -20.0}
@{ Name = 'Max is a negative number, min is the default number '; Maximum = -10; Minimum = $null}
)
# minimum is always set to the actual low end of the range, details refer to closed issue #887.
It "get a correct random number for '<Name>'" -TestCases $testData {
param($maximum, $minimum, $greaterThan, $lessThan, $type)
$result = Get-Random -Maximum $maximum -Minimum $minimum
$result | Should BeGreaterThan $greaterThan
$result | Should BeLessThan $lessThan
$result.GetType().FullName | Should Be $type
}
It "Should be able to throw error when '<Name>'" -TestCases $testDataForError {
param($maximum, $minimum)
try
{
Get-Random -Minimum $minimum -Maximum $maximum
throw "OK"
}
catch
{
$_.FullyQualifiedErrorId | Should Be "MinGreaterThanOrEqualMax,Microsoft.PowerShell.Commands.GetRandomCommand"
}
}
It "Tests for setting the seed" {
$result1 = (get-random -SetSeed 123), (get-random)
$result2 = (get-random -SetSeed 123), (get-random)
$result1 | Should Be $result2
}
}
Describe "Get-Random" {
It "Should return a random number greater than -1 " {
Get-Random | Should BeGreaterThan -1
}
It "Should return a random number less than 100 " {
Get-Random -Maximum 100 | Should BeLessThan 100
Get-Random -Maximum 100 | Should BeGreaterThan -1
}
It "Should return a random number less than 100 and greater than -100 " {
$randomNumber = Get-Random -Minimum -100 -Maximum 100
$randomNumber | Should BeLessThan 100
$randomNumber | Should BeGreaterThan -101
}
It "Should return a random number less than 20.93 and greater than 10.7 " {
$randomNumber = Get-Random -Minimum 10.7 -Maximum 20.93
$randomNumber | Should BeLessThan 20.93
$randomNumber | Should BeGreaterThan 10.7
}
It "Should return same number for both Get-Random when switch SetSeed is used " {
$firstRandomNumber = Get-Random -Maximum 100 -SetSeed 23
$secondRandomNumber = Get-Random -Maximum 100 -SetSeed 23
$firstRandomNumber | Should be $secondRandomNumber
}
It "Should return a number from 1,2,3,5,8,13 " {
$randomNumber = Get-Random -InputObject 1, 2, 3, 5, 8, 13
$randomNumber | Should Be (1 -or 2 -or 3 -or 5 -or 8 -or 13)
}
It "Should return an array " {
$randomNumber = Get-Random -InputObject 1, 2, 3, 5, 8, 13 -Count 3
$randomNumber.GetType().BaseType | Should Be array
}
It "Should return three random numbers for array of 1,2,3,5,8,13 " {
$randomNumber = Get-Random -InputObject 1, 2, 3, 5, 8, 13 -Count 3
$randomNumber[0] | Should Be (1 -or 2 -or 3 -or 5 -or 8 -or 13)
$randomNumber[1] | Should Be (1 -or 2 -or 3 -or 5 -or 8 -or 13)
$randomNumber[2] | Should Be (1 -or 2 -or 3 -or 5 -or 8 -or 13)
$randomNumber[3] | Should BeNullOrEmpty
}
It "Should return all the numbers for array of 1,2,3,5,8,13 in no particular order" {
$randomNumber = Get-Random -InputObject 1, 2, 3, 5, 8, 13 -Count ([int]::MaxValue)
$randomNumber[0] | Should Be (1 -or 2 -or 3 -or 5 -or 8 -or 13)
$randomNumber[1] | Should Be (1 -or 2 -or 3 -or 5 -or 8 -or 13)
$randomNumber[2] | Should Be (1 -or 2 -or 3 -or 5 -or 8 -or 13)
$randomNumber[3] | Should Be (1 -or 2 -or 3 -or 5 -or 8 -or 13)
$randomNumber[4] | Should Be (1 -or 2 -or 3 -or 5 -or 8 -or 13)
$randomNumber[5] | Should Be (1 -or 2 -or 3 -or 5 -or 8 -or 13)
$randomNumber[6] | Should BeNullOrEmpty
}
It "Should return for a string collection " {
$randomNumber = Get-Random -InputObject "red", "yellow", "blue"
$randomNumber | Should Be ("red" -or "yellow" -or "blue")
}
It "Should return a number for hexdecimal " {
$randomNumber = Get-Random 0x07FFFFFFFFF
$randomNumber | Should BeLessThan 549755813887
$randomNumber | Should BeGreaterThan 0
}
It "Should return false, check two random numbers are not equal when not using the SetSeed switch " {
$firstRandomNumber = Get-Random
$secondRandomNumber = Get-Random
$firstRandomNumber | Should Not Be $secondRandomNumber
}
It "Should return the same number for hexidemical number and regular number when the switch SetSeed it used " {
$firstRandomNumber = Get-Random 0x07FFFFFFFF -SetSeed 20
$secondRandomNumber = Get-Random 34359738367 -SetSeed 20
$firstRandomNumber | Should Be @secondRandomNumber
}
It "Should throw an error because the hexidecial number is to large " {
{ Get-Random 0x07FFFFFFFFFFFFFFFF } | Should Throw "Value was either too large or too small for a UInt32"
}
}
@@ -0,0 +1,10 @@
Describe "Get-RunspaceDebug" {
Context "Check return types of RunspaceDebug" {
It "Should return Microsoft.Powershell.Commands.PSRunspaceDebug as the return type" {
$rs = Get-RunspaceDebug
$rs[0].GetType().Name | Should Be PSRunspaceDebug
}
}
}
@@ -0,0 +1,6 @@
Describe "Get-TraceSource" -tags "P1" {
It "Should output data sorted by name" {
$expected = (Get-TraceSource | Sort-Object Name)
Get-TraceSource | Should be $expected
}
}
@@ -0,0 +1,9 @@
Describe "Get-UICulture" {
It "Should return a type of CultureInfo as the name of the type" {
(Get-UICulture).GetType().Name | Should Match CultureInfo
}
It "Should have $ PsUICulture variable be equivalent to Get-UICulture object" {
(Get-UICulture).Name | Should Be $PsUICulture
}
}
@@ -0,0 +1,89 @@
Describe "Get-Unique DRT Unit Tests" -Tags DRT{
It "Command get-unique works with AsString switch" {
$inputArray = "aa","aa","Aa","ba","BA","BA"
$results = $inputArray | Get-Unique -AsString
$results.Length | Should Be 4
$results[0] | Should Be "aa"
$results[1] | Should Be "Aa"
$results[2] | Should Be "ba"
$results[3] | Should Be "BA"
$results[0].GetType().FullName | Should be System.String
$results[1].GetType().FullName | Should be System.String
$results[2].GetType().FullName | Should be System.String
$results[3].GetType().FullName | Should be System.String
}
}
Describe "Get-Unique" {
$sortedList1 = 1,2,2,3,3,4,5
It "Should be able to use the Get-Unique cmdlet without error with inputObject switch" {
{ Get-Unique -InputObject $sortedList1 } | Should Not Throw
}
It "Should be able to uset the gu alias without error" {
{ gu -InputObject $sortedList1 } | Should Not Throw
}
It "Should output an array" {
$(Get-Unique -InputObject $sortedList1).GetType().BaseType | Should Be Array
}
It "Should output an array of unchanged items when the InputObject switch is used" {
$actual = Get-Unique -InputObject $sortedList1
$actual[0] | Should Be $sortedList1[0]
$actual[1] | Should Be $sortedList1[1]
$actual[2] | Should Be $sortedList1[2]
$actual[3] | Should Be $sortedList1[3]
$actual[4] | Should Be $sortedList1[4]
$actual[5] | Should Be $sortedList1[5]
$actual[6] | Should Be $sortedList1[6]
$actual.Length | Should Be 7
}
It "Should accept piped input" {
{ $actualOutput = $sortedList1 | Get-Unique } | Should Not Throw
}
It "Should have the expected output when piped input is used" {
$actualOutput = $sortedList1 | Get-Unique
$expectedOutput = 1,2,3,4,5
$actualOutput.Length | Should Be $expectedOutput.Length
$actualOutput[0] | Should Be $expectedOutput[0]
$actualOutput[1] | Should Be $expectedOutput[1]
$actualOutput[2] | Should Be $expectedOutput[2]
$actualOutput[3] | Should Be $expectedOutput[3]
$actualOutput[4] | Should Be $expectedOutput[4]
}
It "Should be able to input a collection in the inputObject switch" {
$collection = "a", "b", "b", "d"
$actual = Get-Unique -InputObject $collection
$actual.Length | Should Be $collection.Length
$actual[0] | Should Be $collection[0]
$actual[1] | Should Be $collection[1]
$actual[2] | Should Be $collection[2]
$actual[3] | Should Be $collection[3]
}
It "Should get the unique items when piped collection input is used" {
$collection = "a", "b", "b", "d"
$expectedOutput = "a", "b", "d"
$actual = $collection | Get-Unique
$actual.Length | Should Be $expectedOutput.Length
$actual[0] | Should Be $expectedOutput[0]
$actual[1] | Should Be $expectedOutput[1]
$actual[2] | Should Be $expectedOutput[2]
}
}
@@ -0,0 +1,194 @@
Describe "Get-Variable DRT Unit Tests" -Tags DRT{
It "Get-Variable of not existing variable Name should throw ItemNotFoundException"{
try {
Get-Variable -EA Stop -Name nonexistingVariableName
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand"
}
}
It "Get-Variable of existing variable Name with include and bogus exclude should work"{
Set-Variable newVar testing
$var1=get-variable -Name newVar -Include newVar -Exclude bogus
$var1.Name|Should Be "newVar"
$var1.Value|Should Be "testing"
}
It "Get-Variable of existing variable Name with Description and Option should work"{
Set-Variable newVar testing -Option ReadOnly -Description "testing description"
$var1=get-variable -Name newVar
$var1.Name|Should Be "newVar"
$var1.Value|Should Be "testing"
$var1.Options|Should Be "ReadOnly"
$var1.Description|Should Be "testing description"
}
It "Get-Variable of existing variable Globbing Name should work"{
Set-Variable abcaVar testing
Set-Variable bcdaVar "another test"
Set-Variable aVarfoo wow
$var1=get-variable -Name *aVar* -Scope local
$var1.Count | Should be 3
$var1[0].Name|Should Be "abcaVar"
$var1[0].Value|Should Be "testing"
$var1[1].Name|Should Be "aVarfoo"
$var1[1].Value|Should Be "wow"
$var1[2].Name|Should Be "bcdaVar"
$var1[2].Value|Should Be "another test"
}
It "Get-Variable of existing private variable Name should throw ItemNotFoundException"{
try {
Set-Variable newVar testing -Option Private
&{Get-Variable -Name newVar -EA Stop}
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand"
}
}
}
Describe "Get-Variable" {
It "Should be able to call with no parameters without error" {
{ Get-Variable } | Should Not Throw
}
It "Should return environment variables when called with no parameters" {
(Get-Variable).Name -contains "$" | Should Be $true
(Get-Variable).Name -contains "?" | Should Be $true
(Get-Variable).Name -contains "HOST" | Should Be $true
(Get-Variable).Name -contains "PWD" | Should Be $true
(Get-Variable).Name -contains "PID" | Should Be $true
(Get-Variable).Name -contains "^" | Should Be $true
}
It "Should return the value of an object" {
New-Variable -Name tempVar -Value 1
(Get-Variable tempVar).Value | Should Be (1)
}
It "Should be able to call using the gv alias" {
(get-alias gv).Definition | Should be "Get-Variable"
}
It "Should be able to call using the Name switch" {
New-Variable -Name var1 -Value 4
{ Get-Variable -Name var1 } | Should Not Throw
(Get-Variable -Name var1).Value | Should Be 4
Remove-Variable var1
}
It "Should be able to use wildcard characters in the Name field" {
New-Variable -Name var1 -Value 4
New-Variable -Name var2 -Value "test"
(Get-Variable -Name var*).Value[0] | Should be 4
(Get-Variable -Name var*).Value[1] | Should be "test"
Remove-Variable var1
Remove-Variable var2
}
It "Should return only the value if the value switch is used" {
New-Variable -Name var1 -Value 4
Get-Variable -Name var1 -ValueOnly | Should be 4
Remove-Variable var1
}
It "Should pipe string to the name field without the Name field being specified"{
New-Variable -Name var1 -Value 3
("var1" | Get-Variable ).Value | Should Be 3
Remove-Variable var1
}
It "Should be able to include a set of variables to get" {
New-Variable -Name var1 -Value 4
New-Variable -Name var2 -Value 2
$actual = Get-Variable -Include var1, var2
$actual[0].Name | Should Be var1
$actual[1].Name | Should Be var2
$actual[0].Value | Should Be 4
$actual[1].Value | Should Be 2
Remove-Variable var1
Remove-Variable var2
}
It "Should be able to exclude a set of variables to get" {
New-Variable -Name var1 -Value 4
New-Variable -Name var2 -Value 2
New-Variable -Name var3 -Value "test"
$actual = Get-Variable -Exclude var1, var2
$actual.Name -contains "var3" | Should Be $true
}
Context "Scope Tests" {
# This will violate the DRY principle. Tread softly.
It "Should be able to get a global scope variable using the global switch" {
New-Variable globalVar -Value 1 -Scope global -Force
(Get-Variable -Name globalVar -Scope global).Value | Should Be 1
}
It "Should not be able to clear a global scope variable using the local switch" {
New-Variable globalVar -Value 1 -Scope global -Force
Get-Variable -Name globalVar -Scope local -ErrorAction SilentlyContinue | Should Throw
}
It "Should be able to get a global variable when there's one in the script scope" {
New-Variable globalVar -Value 1 -Scope global -Force
{ New-Variable globalVar -Value 2 -Scope script -Force}
(Get-Variable -Name globalVar).Value | Should Be 1
}
It "Should be able to get an item locally using the local switch" {
{
New-Variable localVar -Value 1 -Scope local -Force
Get-Variable -Name localVar -Scope local
} | Should Not Throw
}
It "Should be able to get a variable created in the global scope when there's one in local scope" {
New-Variable localVar -Value 1 -Scope local -Force
New-Variable localVar -Value 2 -Scope global -Force
(Get-Variable -Name localVar -Scope global).Value | Should Be 2
}
It "Should be able to get a script variable created using the script switch" {
{
New-Variable scriptVar -Value 1 -Scope script -Force
Get-Variable -Name scriptVar -Scope script
} | Should Not Throw
}
It "Should be able to clear a global script variable that was created using the script scope switch" {
{
New-Variable scriptVar -Value 1 -Scope script -Force
Get-Variable -Name scriptVar -Scope script
} | Should Not Throw
}
}
}
@@ -0,0 +1,100 @@
Describe "Group-Object DRT Unit Tests" -Tags DRT{
It "Test for CaseSensitive switch" {
$testObject = 'aA', 'aA', 'AA', 'AA'
$results = $testObject | Group-Object -CaseSensitive
$results.Count | Should Be 2
$results.Name.Count | Should Be 2
$results.Group.Count | Should Be 4
$results.Name | Should Be aA,AA
$results.Group | Should Be aA,aA,AA,AA
$results.Group.GetType().BaseType | Should Be Array
}
}
Describe "Group-Object" {
$testObject = Get-ChildItem
It "Should be called using an object as piped without error with no switches" {
{$testObject | Group-Object } | Should Not Throw
}
It "Should be called using the InputObject without error with no other switches" {
{ Group-Object -InputObject $testObject } | Should Not Throw
}
It "Should return three columns- count, name, and group" {
$actual = Group-Object -InputObject $testObject
$actual.Count | Should BeGreaterThan 0
$actual.Name.Count | Should BeGreaterThan 0
$actual.Group.Count | Should BeGreaterThan 0
}
It "Should use the group alias" {
{ group -InputObject $testObject } | Should Not Throw
}
It "Should create a collection when the inputObject parameter is used" {
$actualParam = Group-Object -InputObject $testObject
$actualParam.Group.GetType().Name | Should Be "Collection``1"
}
It "Should output an array when piped input is used" {
$actual = $testObject | Group-Object
$actual.Group.GetType().BaseType | Should Be Array
}
It "Should have the same output between the group alias and the group-object cmdlet" {
$actualAlias = group -InputObject $testObject
$actualCmdlet = Group-Object -InputObject $testObject
$actualAlias.Name[0] | Should Be $actualCmdlet.Name[0]
$actualAlias.Group[0] | Should Be $actualCmdlet.Group[0]
}
It "Should be able to use the property switch without error" {
{ $testObject | Group-Object -Property Attributes } | Should Not Throw
$actual = $testObject | Group-Object -Property Attributes
$actual.Group.Count | Should BeGreaterThan 0
}
It "Should be able to use the property switch on multiple properties without error" {
{ $testObject | Group-Object -Property Attributes, Length }
$actual = $testObject | Group-Object -Property Attributes, Length
$actual.Group.Count | Should BeGreaterThan 0
}
It "Should be able to omit members of a group using the NoElement switch without error" {
{ $testObject | Group-Object -NoElement } | Should Not Throw
($testObject | Group-Object -NoElement).Group | Should BeNullOrEmpty
}
It "Should be able to output a hashtable datatype" {
$actual = $testObject | Group-Object -AsHashTable
$actual.GetType().Name | Should be "Hashtable"
}
It "Should be able to access when output as hash table" {
$actual = $testObject | Group-Object -AsHashTable
$actual.Keys | Should Not BeNullOrEmpty
}
It "Should throw when attempting to use AsString without AsHashTable" {
{ $testObject | Group-Object -AsString } | Should Throw
}
It "Should not throw error when using AsString when the AsHashTable was added" {
{ $testObject | Group-Object -AsHashTable -AsString } | Should Not Throw
}
}
@@ -0,0 +1,101 @@
Describe "Import-Alias DRT Unit Tests" -Tags DRT{
$testAliasDirectory = Join-Path -Path $TestDrive -ChildPath ImportAliasTestDirectory
$testAliases = "TestAliases"
$fulltestpath = Join-Path -Path $testAliasDirectory -ChildPath $testAliases
BeforeEach {
New-Item -Path $testAliasDirectory -ItemType Directory -Force
remove-item alias:abcd* -force
remove-item alias:ijkl* -force
set-alias abcd01 efgh01
set-alias abcd02 efgh02
set-alias abcd03 efgh03
set-alias abcd04 efgh04
set-alias ijkl01 mnop01
set-alias ijkl02 mnop02
set-alias ijkl03 mnop03
set-alias ijkl04 mnop04
}
AfterEach {
Remove-Item -Path $testAliasDirectory -Recurse -Force
}
It "Import-Alias Resolve To Multiple will throw PSInvalidOperationException" {
$ErrorActionPreference = "Stop"
try {
Import-Alias *
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "NotSupported,Microsoft.PowerShell.Commands.ImportAliasCommand"
}
}
It "Import-Alias From Exported Alias File Aliases Already Exist should throw SessionStateException" {
$ErrorActionPreference = "Stop"
{Export-Alias $fulltestpath abcd*}| Should Not Throw
try {
Import-Alias $fulltestpath
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "AliasAlreadyExists,Microsoft.PowerShell.Commands.ImportAliasCommand"
}
}
It "Import-Alias Into Invalid Scope should throw PSArgumentException"{
{Export-Alias $fulltestpath abcd*}| Should Not Throw
try {
Import-Alias $fulltestpath -scope bogus
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "Argument,Microsoft.PowerShell.Commands.ImportAliasCommand"
}
}
It "Import-Alias From Exported Alias File Aliases Already Exist using force should not throw"{
{Export-Alias $fulltestpath abcd*}| Should Not Throw
{Import-Alias $fulltestpath -Force}| Should Not Throw
}
}
Describe "Import-Alias" {
$newLine=[Environment]::NewLine
$testAliasDirectory = Join-Path -Path $TestDrive -ChildPath ImportAliasTestDirectory
$testAliases = "pesteralias.txt"
$pesteraliasfile = Join-Path -Path $testAliasDirectory -ChildPath $testAliases
BeforeEach {
New-Item -Path $testAliasDirectory -ItemType Directory -Force
$pesteraliascontent ='# Alias File'+$newLine
$pesteraliascontent+='# Exported by : alex'+$newLine
$pesteraliascontent+='# Date/Time : Thursday, 12 November 2015 21:55:08'+$newLine
$pesteraliascontent+='# Computer : archvm'+$newLine+'"pesterecho","echo","","None"'
$pesteraliascontent > $pesteraliasfile
}
AfterEach {
Remove-Item -Path $testAliasDirectory -Recurse -Force
}
It "Should be able to import an alias file successfully" {
{ Import-Alias $pesteraliasfile } | Should Not throw
}
It "Should be able to import file via the Import-Alias alias of ipal" {
{ ipal $pesteraliasfile } | Should Not throw
}
It "Should be able to import an alias file and perform imported aliased echo cmd" {
(Import-Alias $pesteraliasfile)
(pesterecho pestertesting) | Should Be "pestertesting"
}
It "Should be able to use ipal alias to import an alias file and perform cmd" {
(ipal $pesteraliasfile)
(pesterecho pestertesting) | Should be "pestertesting"
}
}
@@ -0,0 +1,73 @@
Describe "Import-Csv" {
$testCsv = Join-Path -Path (Join-Path $PSScriptRoot -ChildPath assets) -ChildPath TestCsv.csv
It "Should be able to call without error" {
{ Import-Csv $testCsv } | Should Not Throw
}
It "Should be able to assign to a variable" {
$actual = Import-Csv $testCsv
$actual | Should Not BeNullOrEmpty
$actual.GetType().BaseType | Should Be array
}
It "Should have the data from the csv file" {
$actualContent = $(Get-Content $testCsv)[0]
$testContent = $($(Import-Csv $testCsv) | Get-Member) | ? { $_.MemberType -eq "NoteProperty" } | % { $_.Name } | Select-Object -First 1
$actualContent.IndexOf($testContent) | Should BeGreaterThan -1
}
It "Should be able to prepend a custom header" {
$header = "test1","test2","test3"
$originalContent = $($(Import-Csv $testCsv) | Get-Member) | ? { $_.MemberType -eq "NoteProperty" } | % { $_.Name } | Select-Object -First 1
$testContent = $($(Import-Csv $testCsv -Header $header) | Get-Member) | ? { $_.MemberType -eq "NoteProperty" } | % { $_.Name } | Select-Object -First 3
# the original csv file doesn't contain the headers
$originalContent.IndexOf($header[0]) | Should Be -1
# but it does with the -Header switch!
$testContent[0] | Should Be $header[0]
$testContent[1] | Should Be $header[1]
$testContent[2] | Should Be $header[2]
}
It "Should be able to use the alias without error" {
{ Import-Csv $testCsv } | Should Not Throw
}
It "Should have the same output between the alias and the full cmdlet name" {
$alias = $($(ipcsv $testCsv) | Get-Member) | ? { $_.MemberType -eq "NoteProperty" } | % { $_.Name } | Select-Object -First 1
$cmdlet = $($(Import-Csv $testCsv) | Get-Member) | ? { $_.MemberType -eq "NoteProperty" } | % { $_.Name } | Select-Object -First 1
$alias[0] | Should Be $cmdlet[0]
$alias[1] | Should Be $cmdlet[1]
$alias[2] | Should Be $cmdlet[2]
}
}
Describe "Import-Csv DRT Unit Tests" -Tags DRT {
BeforeAll {
$fileToGenerate = Join-Path $TestDrive -ChildPath "importCSVTest.csv"
$psObject = [pscustomobject]@{ "First" = "1"; "Second" = "2" }
}
It "Test import-csv with a delimiter parameter" {
$delimiter = ';'
$psObject | Export-Csv -Path $fileToGenerate -Delimiter $delimiter
$returnObject = Import-Csv -Path $fileToGenerate -Delimiter $delimiter
$returnObject.First | Should Be 1
$returnObject.Second | Should Be 2
}
It "Test import-csv with UseCulture parameter" {
$psObject | Export-Csv -Path $fileToGenerate -UseCulture
$returnObject = Import-Csv -Path $fileToGenerate -UseCulture
$returnObject.First | Should Be 1
$returnObject.Second | Should Be 2
}
}
@@ -0,0 +1,35 @@
$assetsDir = Join-Path -Path $PSScriptRoot -ChildPath assets
Describe "Import-LocalizedData" {
BeforeAll {
$script = "localized.ps1"
$sunday = "Sunday"
$sundayInGerman = $sunday + " (in German)"
}
It "Should be able to import string using default culture" {
# Set-Culture is broken, but let's verify that default culture is en-US
$culture = Get-Culture
$culture.Name | Should Be "en-US"
$d = Import-LocalizedData -FileName $script -BaseDirectory $assetsDir
$d.d0 | Should be $sunday
}
It "Should be able to import string using en-US culture" {
$d = Import-LocalizedData -FileName $script -BaseDirectory $assetsDir -UICulture en-US
$d.d0 | Should be $sunday
}
It "Should be able to import string using de-DE culture" {
$d = Import-LocalizedData -FileName $script -BaseDirectory $assetsDir -UICulture de-DE
$d.d0 | Should be $sundayInGerman
}
It "Should be able to import string and store in binding variable" {
Import-LocalizedData -FileName $script -BaseDirectory $assetsDir -UICulture de-DE -BindingVariable d
$d.d0 | Should be $sundayInGerman
}
}
@@ -0,0 +1,35 @@
Describe "Invoke-Expression" {
Context "Should execute the invoked command validly" {
It "Should return the echoed text" {
(Invoke-Expression -command "echo pestertest1") | Should be "pestertest1"
}
It "Should return the echoed text for the alias" {
(iex -command "echo pestertest2") | Should Be "pestertest2"
}
It "Should return the echoed text from a script" {
$testfile = Join-Path -Path (Join-Path $PSScriptRoot -ChildPath assets) -ChildPath echoscript.ps1
$testcommand = "echo pestertestscript"
$testcommand | Add-Content -Path $testfile
(Invoke-Expression $testfile) | Should Be "pestertestscript"
Remove-Item $testfile
}
It "Should return the echoed text from a script from the alias" {
$testfile = Join-Path -Path (Join-Path $PSScriptRoot -ChildPath assets) -ChildPath echoscript.ps1
$testcommand = "echo pestertestscript"
$testcommand | Add-Content -Path $testfile
(iex $testfile) | Should Be "pestertestscript"
Remove-Item $testfile
}
}
}
Describe "Invoke-Expression DRT Unit Tests" -Tags DRT{
It "Invoke-Expression should work"{
$result=invoke-expression -Command 2+2
$result|Should Be 4
}
}
@@ -0,0 +1,26 @@
Describe "Measure-Command" {
Context "Validate return types for Measure-Command" {
It "Should return TimeSpan as the return type" {
(Measure-Command { Get-Date }).GetType() | Should Be timespan
}
}
Context "Validate that it is executing commands correctly" {
It "Should return TimeSpan after executing a script" {
(Measure-Command { echo hi }).GetType() | Should Be timespan
}
It "Should return TimeSpan after executing a cmdlet" {
$pesterscript = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath assets) -ChildPath echoscript.ps1
$testfile = $pesterscript
$testcommand = "echo pestertestscript"
$testcommand | Add-Content -Path $testfile
(Measure-Command { $pesterscript }).GetType() | Should Be timespan
Remove-Item $testfile
}
}
}
@@ -0,0 +1,292 @@
Describe "Measure-Object" {
$testObject = 1,3,4
It "Should be able to be called without error" {
{ Measure-Object | Out-Null } | Should Not Throw
}
It "Should be able to call on piped input" {
{ $testObject | Measure-Object } | Should Not Throw
}
It "Should be able to count the number of objects input to it" {
$($testObject | Measure-Object).Count | Should Be $testObject.Length
}
It "Should be able to count using the Property switch" {
$expected = $(Get-ChildItem $TestDrive).Length
$actual = $(Get-ChildItem $TestDrive | Measure-Object -Property Length).Count
$actual | Should Be $expected
}
Context "Numeric tests" {
It "Should be able to sum" {
$actual = $testObject | Measure-Object -Sum
$expected = 0
foreach ( $obj in $testObject )
{
$expected += $obj
}
$actual.Sum | Should Be $expected
}
It "Should be able to average" {
$actual = $testObject | Measure-Object -Average
$expected = 0
foreach ( $obj in $testObject )
{
$expected += $obj
}
$expected /= $testObject.length
$actual.Average | Should Be $expected
}
It "Should be able to return a minimum" {
$actual = $testObject | Measure-Object -Minimum
$expected = $testObject[0]
for ($i=0; $i -lt $testObject.length; $i++)
{
if ( $testObject[$i] -lt $expected )
{
$expected = $testObject[$i]
}
}
$actual.Minimum | Should Be $expected
}
It "Should be able to return a minimum when multiple objects are the minimum" {
$testMinimum = 1,1,2,4
$actual = $testMinimum | Measure-Object -Minimum
$expected = $testMinimum[0]
for ($i=1; $i -lt $testMinimum.length; $i++)
{
if ( $testMinimum[$i] -lt $expected )
{
$expected = $testMinimum[$i]
}
}
$actual.Minimum | Should Be $expected
}
It "Should be able to return a maximum" {
$actual = $testObject | Measure-Object -Maximum
$expected = $testObject[0]
for ($i=1; $i -lt $testObject.length; $i++)
{
if ( $testObject[$i] -gt $expected )
{
$expected = $testObject[$i]
}
}
$actual.Maximum | Should Be $expected
}
It "Should be able to return a maximum when multiple objects are the maximum" {
$testMaximum = 1,3,5,5
$actual = $testMaximum | Measure-Object -Maximum
$expected = $testMaximum[0]
for ($i=1; $i -lt $testMaximum.length; $i++)
{
if ( $testMaximum[$i] -gt $expected )
{
$expected = $testMaximum[$i]
}
}
$actual.Maximum | Should Be $expected
}
}
Context "String tests" {
$nl = [Environment]::NewLine
$testString = "HAD I the heavens' embroidered cloths,$nl Enwrought with golden and silver light,$nl The blue and the dim and the dark cloths$nl Of night and light and the half light,$nl I would spread the cloths under your feet:$nl But I, being poor, have only my dreams;$nl I have spread my dreams under your feet;$nl Tread softly because you tread on my dreams."
It "Should be able to count the number of words in a string" {
$expectedLength = $testString.Replace($nl,"").Split().length
$actualLength = $testString | Measure-Object -Word
$actualLength.Words | Should Be $expectedLength
}
It "Should be able to count the number of characters in a string" {
$expectedLength = $testString.length
$actualLength = $testString | Measure-Object -Character
$actualLength.Characters | Should Be $expectedLength
}
It "Should be able to count the number of lines in a string" {
$expectedLength = $testString.Split($nl, [System.StringSplitOptions]::RemoveEmptyEntries).length
$actualLength = $testString | Measure-Object -Line
$actualLength.Lines | Should Be $expectedLength
}
}
}
Describe "Measure-Object DRT basic functionality" -Tags DRT{
BeforeAll {
if(-not ([System.Management.Automation.PSTypeName]'TestMeasureGeneric').Type)
{
Add-Type -TypeDefinition @"
[System.Flags]
public enum TestMeasureGeneric : uint
{
TestSum = 1,
TestAverage = 2,
TestMax = 4,
TestMin = 8
}
"@
}
if(-not ([System.Management.Automation.PSTypeName]'TestMeasureText').Type)
{
Add-Type -TypeDefinition @"
[System.Flags]
public enum TestMeasureText : uint
{
TestIgnoreWS = 1,
TestCharacter = 2,
TestWord = 4,
TestLine = 8
}
"@
}
$employees = [pscustomobject]@{"FirstName"="joseph"; "LastName"="smith"; "YearsInMS"=15},
[pscustomobject]@{"FirstName"="paul"; "LastName"="smith"; "YearsInMS"=15},
[pscustomobject]@{"FirstName"="mary jo"; "LastName"="soe"; "YearsInMS"=5},
[pscustomobject]@{"FirstName"="edmund`todd `n"; "LastName"="bush"; "YearsInMS"=9}
}
It "Measure-Object with Generic enum value options combination should work"{
$flags = [TestMeasureGeneric]0
$property = "FirstName"
$testSum = ($flags -band [TestMeasureGeneric]::TestSum) -gt 0
$testAverage = ($flags -band [TestMeasureGeneric]::TestAverage) -gt 0
$testMax = ($flags -band [TestMeasureGeneric]::TestMax) -gt 0
$testMin = ($flags -band [TestMeasureGeneric]::TestMin) -gt 0
$result = $employees | Measure-Object -Sum:$testSum -Average:$testAverage -Max:$testMax -Min:$testMin -Prop $property
$result.Count | Should Be 4
$result.Sum | Should BeNullOrEmpty
$result.Average | Should BeNullOrEmpty
$result.Max | Should BeNullOrEmpty
$result.Min | Should BeNullOrEmpty
for ($i = 1; $i -lt 8 * 2; $i++)
{
$flags = [TestMeasureGeneric]$i
$property = "YearsInMS"
$testSum = ($flags -band [TestMeasureGeneric]::TestSum) -gt 0
$testAverage = ($flags -band [TestMeasureGeneric]::TestAverage) -gt 0
$testMax = ($flags -band [TestMeasureGeneric]::TestMax) -gt 0
$testMin = ($flags -band [TestMeasureGeneric]::TestMin) -gt 0
$result = $employees | Measure-Object -Sum:$testSum -Average:$testAverage -Max:$testMax -Min:$testMin -Prop $property
$result.Count | Should Be 4
if($testSum)
{
$result.Sum | Should Be 44
}
else
{
$result.Sum | Should BeNullOrEmpty
}
if($testAverage)
{
$result.Average | Should Be 11
}
else
{
$result.Average | Should BeNullOrEmpty
}
if($testMax)
{
$result.Maximum | Should Be 15
}
else
{
$result.Maximum | Should BeNullOrEmpty
}
if($testMin)
{
$result.Minimum | Should Be 5
}
else
{
$result.Minimum | Should BeNullOrEmpty
}
}
}
It "Measure-Object with Text combination should work"{
for ($i = 1; $i -lt 8 * 2; $i++)
{
$flags = [TestMeasureText]$i
$property = "FirstName"
$testIgnoreWS = ($flags -band [TestMeasureText]::TestIgnoreWS) -gt 0
$testCharacter = ($flags -band [TestMeasureText]::TestCharacter) -gt 0
$testWord = ($flags -band [TestMeasureText]::TestWord) -gt 0
$testLine = ($flags -band [TestMeasureText]::TestLine) -gt 0
$result = $employees | Measure-Object -IgnoreWhiteSpace:$testIgnoreWS -Character:$testCharacter -Word:$testWord -Line:$testLine -Prop $property
if($testCharacter)
{
if($testIgnoreWS)
{
$result.Characters | Should Be 25
}
else
{
$result.Characters | Should Be 29
}
}
else
{
$result.Characters | Should BeNullOrEmpty
}
if($testWord)
{
$result.Words | Should Be 6
}
else
{
$result.Words | Should BeNullOrEmpty
}
if($testLine)
{
$result.Lines | Should Be 4
}
else
{
$result.Lines | Should BeNullOrEmpty
}
}
}
It "Measure-Object with multiple lines should work"{
$result = "123`n4"|measure-object -line
$result.Lines | Should Be 2
}
}
@@ -0,0 +1,75 @@
Describe "New-Alias DRT Unit Tests" -Tags DRT{
It "New-Alias Constant should throw SessionStateUnauthorizedAccessException"{
try {
New-Alias -Name "ABCD" -Value "foo" -Option "Constant" -Force:$true
New-Alias -Name "ABCD" -Value "foo" -Force:$true -ErrorAction Stop
Throw "Execution OK"
}
catch {
$_.CategoryInfo| Should Match "SessionStateUnauthorizedAccessException"
$_.FullyQualifiedErrorId | Should be "AliasNotWritable,Microsoft.PowerShell.Commands.NewAliasCommand"
}
}
It "New-Alias NamePositional And Value Valid" {
New-Alias ABCD -Value "MyCommand" -Scope "0"
$result=Get-Alias -Name ABCD -Scope "0"
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "MyCommand"
$result.Description| Should Be ""
$result.Options| Should Be "None"
}
It "New-Alias NamePositional And ValuePositional Valid" {
New-Alias ABCD "MyCommand" -Scope "0"
$result=Get-Alias -Name ABCD -Scope "0"
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "MyCommand"
$result.Description| Should Be ""
$result.Options| Should Be "None"
}
It "New-Alias Description Valid" {
New-Alias -Name ABCD -Value "MyCommand" -Description "test description" -Scope "0"
$result=Get-Alias -Name ABCD -Scope "0"
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "MyCommand"
$result.Description| Should Be "test description"
$result.Options| Should Be "None"
}
}
Describe "New-Alias" {
It "Should be able to be called using the name and value parameters without error" {
{ New-Alias -Name testAlias -Value 100 } | Should Not Throw
}
It "Should have the same output between the alias and the original cmdlet" {
New-Alias -Name testAlias -Value Get-Command
$aliasId = $(testAlias).Id
$cmdletId = $(Get-Command).Id
foreach ($IdNumber in $aliasId)
{
$aliasId[$IdNumber] | Should Be $cmdletId[$IdNumber]
}
}
It "Should be able to call the New-Alias cmdlet using the nal alias without error" {
{ nal -Name testAlias -Value 100 } | Should Not Throw
}
It "Should have the same output between the nal alias and the New-Alias cmdlet" {
nal -Name testAlias -Value Get-Command
New-Alias -Name testalias2 -Value Get-Command
$aliasData = $(testAlias).Id
$cmdletData = $(testAlias2).Id
foreach ($IdNumber in $aliasData)
{
$aliasData[$IdNumber] | Should Be $cmdletData[$IdNumber]
}
}
}
@@ -0,0 +1,23 @@
Describe "New-Event" {
Context "Check return type of New-Event" {
It "Should return PSEventArgs as return type of New-Event" {
(New-Event -SourceIdentifier a).GetType() | Should Be System.Management.Automation.PSEventArgs
}
}
Context "Check New-Event can register an event"{
It "Should return PesterTestMessage as the MessageData" {
(New-Event -sourceidentifier PesterTimer -sender Windows.timer -messagedata "PesterTestMessage")
(Get-Event -SourceIdentifier PesterTimer).MessageData | Should Be "PesterTestMessage"
Remove-Event -sourceidentifier PesterTimer
}
It "Should return Sender as Windows.timer" {
(New-Event -sourceidentifier PesterTimer -sender Windows.timer -messagedata "PesterTestMessage")
(Get-Event -SourceIdentifier PesterTimer).Sender | Should be Windows.timer
Remove-Event -sourceIdentifier PesterTimer
}
}
}
@@ -0,0 +1,167 @@
Describe "New-Object" {
It "should create an object with 4 fields" {
$o = New-Object psobject
$val = $o.GetType()
$val.IsPublic | Should Not BeNullOrEmpty
$val.Name | Should Not BeNullOrEmpty
$val.IsSerializable | Should Not BeNullOrEmpty
$val.BaseType | Should Not BeNullOrEmpty
$val.IsPublic | Should Be $true
$val.IsSerializable | Should Be $false
$val.Name | Should Be 'PSCustomObject'
$val.BaseType | Should Be 'System.Object'
}
It "should create an object with using Property switch" {
$hash = @{
FirstVal = 'test1'
SecondVal = 'test2'
}
$o = New-Object psobject -Property $hash
$o.FirstVal | Should Be 'test1'
$o.SecondVal | Should Be 'test2'
}
It "should create a .Net object with using ArgumentList switch" {
$o = New-Object -TypeName System.Version -ArgumentList "1.2.3.4"
$o.GetType() | Should Be ([System.Version])
$o | Should Be "1.2.3.4"
}
}
Describe "New-Object DRT basic functionality" -Tags DRT{
It "New-Object with int array should work"{
$result = New-Object -TypeName int[] -Arg 10
$result.Count | Should Be 10
}
It "New-Object with char should work"{
$result = New-Object -TypeName char
$result.Count | Should Be 1
$defaultChar = [char]0
([char]$result) | Should Be $defaultChar
}
It "New-Object with default Coordinates should work"{
$result = New-Object -TypeName System.Management.Automation.Host.Coordinates
$result.Count | Should Be 1
$result.X | Should Be 0
$result.Y | Should Be 0
}
It "New-Object with specified Coordinates should work"{
$result = New-Object -TypeName System.Management.Automation.Host.Coordinates -ArgumentList 1,2
$result.Count | Should Be 1
$result.X | Should Be 1
$result.Y | Should Be 2
}
It "New-Object with Employ should work"{
if(-not ([System.Management.Automation.PSTypeName]'Employee').Type)
{
Add-Type -TypeDefinition "public class Employee{public Employee(string firstName,string lastName,int yearsInMS){FirstName = firstName;LastName=lastName;YearsInMS = yearsInMS;}public string FirstName;public string LastName;public int YearsInMS;}"
}
$result = New-Object -TypeName Employee -ArgumentList "Mary", "Soe", 11
$result.Count | Should Be 1
$result.FirstName | Should Be "Mary"
$result.LastName | Should Be "Soe"
$result.YearsInMS | Should Be 11
}
It "New-Object with invalid type should throw Exception"{
try
{
New-Object -TypeName LiarType -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo| Should Match "PSArgumentException"
$_.FullyQualifiedErrorId | Should be "TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand"
}
}
It "New-Object with invalid argument should throw Exception"{
try
{
New-Object -TypeName System.Management.Automation.PSVariable -ArgumentList "A", 1, None, "asd" -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo| Should Match "MethodException"
$_.FullyQualifiedErrorId | Should be "ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand"
}
}
It "New-Object with abstract class should throw Exception"{
Add-Type -TypeDefinition "public abstract class AbstractEmployee{public AbstractEmployee(){}}"
try
{
New-Object -TypeName AbstractEmployee -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo| Should Match "MethodInvocationException"
$_.FullyQualifiedErrorId | Should be "ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand"
}
}
It "New-Object with bad argument for class construtor should throw Exception"{
if(-not ([System.Management.Automation.PSTypeName]'Employee').Type)
{
Add-Type -TypeDefinition "public class Employee{public Employee(string firstName,string lastName,int yearsInMS){FirstName = firstName;LastName=lastName;YearsInMS = yearsInMS;}public string FirstName;public string LastName;public int YearsInMS;}"
}
try
{
New-Object -TypeName Employee -ArgumentList 11 -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo| Should Match "MethodException"
$_.FullyQualifiedErrorId | Should be "ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand"
}
}
#This case will throw "Execution OK" now, just mark as pending now
It "New-Object with not init class construtor should throw Exception" -Pending{
if(-not ([System.Management.Automation.PSTypeName]'Employee').Type)
{
Add-Type -TypeDefinition "public class Employee{public Employee(string firstName,string lastName,int yearsInMS){FirstName = firstName;LastName=lastName;YearsInMS = yearsInMS;}public string FirstName;public string LastName;public int YearsInMS;}"
}
try
{
New-Object -TypeName Employee -EA Stop
Throw "Execution OK"
}
catch
{
$_.FullyQualifiedErrorId | Should be "CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand"
}
}
It "New-Object with Private Nested class should throw Exception"{
Add-Type -TypeDefinition "public class WeirdEmployee{public WeirdEmployee(){}private class PrivateNestedWeirdEmployee{public PrivateNestedWeirdEmployee(){}}}"
try
{
New-Object -TypeName WeirdEmployee+PrivateNestedWeirdEmployee -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo| Should Match "PSArgumentException"
$_.FullyQualifiedErrorId | Should be "TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand"
}
}
It "New-Object with TypeName and Property parameter should work"{
$result = New-Object -TypeName PSObject -property @{foo=123}
$result.foo | Should Be 123
}
}
@@ -0,0 +1,57 @@
Describe "New-TimeSpan DRT Unit Tests" -Tags DRT{
It "Should works proper with new-timespan"{
$results = New-TimeSpan -Days 10 -Hours 10 -Minutes 10 -Seconds 10
$results.GetType() | Should Be timespan
$results.Days | Should Be 10
$results.Hours | Should Be 10
$results.Minutes | Should Be 10
$results.Seconds | Should Be 10
}
}
Describe "New-TimeSpan" {
It "Should be able to create a new timespan object" {
New-Variable -Name testObject -Value $(New-TimeSpan)
$testObject.GetType() | Should Be timespan
}
Context "Core Functionality Tests" {
New-Variable -Name testObject -Value $(New-TimeSpan -Days 2 -Hours 23 -Minutes 4 -Seconds 3) -Force
$expectedOutput = @{ "Days" = "2";
"Hours" = "23";
"Minutes" = "4";
"Seconds" = "3";
"Milliseconds" = "0";
"Ticks" = "2558430000000";
"TotalDays" = "2.96114583333333";
"TotalHours" = "71.0675";
"TotalMinutes" = "4264.05";
"TotalSeconds" = "255843";
"TotalMilliseconds" = "255843000"
}
$TEN_MILLION = 10000000
It "Should have expected values for time properties set during creation" {
$testObject.Days | Should Be $expectedOutput["Days"]
$testObject.Hours | Should Be $expectedOutput["Hours"]
$testObject.Minutes | Should Be $expectedOutput["Minutes"]
$testObject.Seconds | Should Be $expectedOutput["Seconds"]
$testObject.Ticks | Should Be $expectedOutput["Ticks"]
}
}
It "Should have matching output when using the Start switch vs piping from another cmdlet" {
# this file is guaranteed to exist
$inputObject = (Get-ChildItem $PSScriptRoot/New-TimeSpan.Tests.ps1)
$inputParameter = New-TimeSpan -Start $inputObject.lastwritetime
$pipedInput = $inputObject | New-TimeSpan
$difference = [math]::Abs($inputParameter.Milliseconds - $pipedInput.Milliseconds)
# The difference between commands should be minimal
$difference | Should BeLessThan 100
}
}
@@ -0,0 +1,247 @@
Describe "New-Variable DRT Unit Tests" -Tags DRT{
It "New-Variable variable with description should works"{
New-Variable foo bar -description "my description"
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "None"
$var1.Description|Should Be "my description"
}
It "New-Variable variable with option should works"{
New-Variable foo bar -option Constant
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "Constant"
$var1.Description|Should Be ""
}
It "New-Variable variable twice should throw Exception"{
New-Variable foo bogus
try {
New-Variable foo bar -EA Stop
Throw "Execution OK"
}
catch {
$_.CategoryInfo| Should Match "SessionStateException"
$_.FullyQualifiedErrorId | Should Be "VariableAlreadyExists,Microsoft.PowerShell.Commands.NewVariableCommand"
}
New-Variable foo bar -Force -PassThru
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
}
It "New-Variable ReadOnly variable twice should throw Exception"{
New-Variable foo bogus -option ReadOnly
try {
New-Variable foo bar -EA Stop
Throw "Execution OK"
}
catch {
$_.CategoryInfo| Should Match "SessionStateException"
$_.FullyQualifiedErrorId | Should Be "VariableAlreadyExists,Microsoft.PowerShell.Commands.NewVariableCommand"
}
New-Variable foo bar -Force -PassThru
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
}
}
Describe "New-Variable" {
It "Should create a new variable with no parameters" {
{ New-Variable var1 } | Should Not Throw
}
It "Should be able to set variable name using the Name parameter" {
{ New-Variable -Name var1 } | Should Not Throw
}
It "Should be able to assign a value to a variable using the value switch" {
New-Variable var1 -Value 4
$var1 | Should Be 4
}
It "Should be able to assign a value to a new variable without using the value switch" {
New-Variable var1 "test"
$var1 | Should Be "test"
}
It "Should assign a description to a new variable using the description switch" {
New-Variable var1 100 -Description "Test Description"
(Get-Variable var1).Description | Should Be "Test Description"
}
It "Should be able to be called with the nv alias" {
nv var1
$var1 | Should BeNullOrEmpty
nv var2 2
$var2 | Should Be 2
}
It "Should not be able to set the name of a new variable to that of an old variable within same scope when the Force switch is missing" {
New-Variable var1
(New-Variable var1 -ErrorAction SilentlyContinue) | Should Throw
}
It "Should change the value of an already existing variable using the Force switch" {
New-Variable var1 -Value 1
$var1 | Should Be 1
New-Variable var1 -Value 2 -Force
$var1 | Should Be 2
$var1 | Should Not Be 1
}
It "Should be able to set the value of a variable by piped input" {
$in = "value"
$in | New-Variable -Name var1
$var1 | Should Be $in
}
It "Should be able to pipe object properties to output using the PassThru switch" {
$in = Set-Variable -Name testVar -Value "test" -Description "test description" -PassThru
$in.Description | Should Be "test description"
}
It "Should be able to set the value using the value switch" {
New-Variable -Name var1 -Value 2
$var1 | Should Be 2
}
Context "Option tests" {
It "Should be able to use the options switch without error" {
{ New-Variable -Name var1 -Value 2 -Option Unspecified } | Should Not Throw
}
It "Should default to none as the value for options" {
(new-variable -name var2 -value 4 -passthru).Options | should be "None"
}
It "Should be able to set ReadOnly option" {
{ New-Variable -Name var1 -Value 2 -Option ReadOnly } | Should Not Throw
}
It "Should not be able to change variable created using the ReadOnly option when the Force switch is not used" {
New-Variable -Name var1 -Value 1 -Option ReadOnly
Set-Variable -Name var1 -Value 2 -ErrorAction SilentlyContinue
$var1 | Should Not Be 2
}
It "Should be able to set a new variable to constant" {
{ New-Variable -Name var1 -Option Constant } | Should Not Throw
}
It "Should not be able to change an existing variable to constant" {
New-Variable -Name var1 -Value 1 -PassThru
Set-Variable -Name var1 -Option Constant -ErrorAction SilentlyContinue
(Get-Variable var1).Options | should be "None"
}
It "Should not be able to delete a constant variable" {
New-Variable -Name var1 -Value 2 -Option Constant
Remove-Variable -Name var1 -ErrorAction SilentlyContinue
$var1 | Should Be 2
}
It "Should not be able to change a constant variable" {
New-Variable -Name var1 -Value 1 -Option Constant
Set-Variable -Name var1 -Value 2 -ErrorAction SilentlyContinue
$var1 | Should Not Be 2
}
It "Should be able to create a variable as private without error" {
{ New-Variable -Name var1 -Option Private } | Should Not Throw
}
It "Should be able to see the value of a private variable when within scope" {
New-Variable -Name var1 -Value 100 -Option Private
$var1 | Should Be 100
}
It "Should not be able to see the value of a private variable when out of scope" {
{New-Variable -Name var1 -Value 1 -Option Private}| Should Not Throw
$var1 | Should BeNullOrEmpty
}
It "Should be able to use the AllScope switch without error" {
{ New-Variable -Name var1 -Option AllScope } | Should Not Throw
}
It "Should be able to see variable created using the AllScope switch in a child scope" {
New-Variable -Name var1 -Value 1 -Option AllScope
&{ $var1 = 2 }
$var1 | Should Be 2
}
}
Context "Scope Tests" {
BeforeAll {
if ( get-variable -scope global -name globalVar1 -ea SilentlyContinue )
{
Remove-Variable -scope global -name globalVar1
}
if ( get-variable -scope script -name scriptvar -ea SilentlyContinue )
{
remove-variable -scope script -name scriptvar
}
# no check for local scope variable as that scope is created with test invocation
}
AfterAll {
if ( get-variable -scope global -name globalVar1 )
{
Remove-Variable -scope global -name globalVar1
}
if ( get-variable -scope script -name scriptvar )
{
remove-variable -scope script -name scriptvar
}
}
It "Should be able to create a global scope variable using the global switch" {
new-variable -Scope global -name globalvar1 -value 1
get-variable -Scope global -name globalVar1 -ValueOnly | Should be 1
}
It "Should be able to create a local scope variable using the local switch" {
Get-Variable -scope local -name localvar -ValueOnly -ea silentlycontinue | should BeNullOrEmpty
New-Variable -Scope local -Name localVar -value 10
get-variable -scope local -name localvar -ValueOnly | Should be 10
}
It "Should be able to create a script scope variable using the script switch" {
new-variable -scope script -name scriptvar -value 100
get-variable -scope script -name scriptvar -ValueOnly | should be 100
}
}
}
@@ -0,0 +1,130 @@
Describe "Out-File DRT Unit Tests" -Tags DRT{
It "Should be able to write the contens into a file with -pspath" {
$tempFile = "ExposeBug928965"
{ 1 | Out-File -PSPath $tempFile } | Should Not Throw
$fileContents = Get-Content $tempFile
$fileContents | Should be 1
Remove-Item $tempFile -Force
}
It "Should be able to write the contens into a file with -pspath" {
$tempFile = "outfileAppendTest.txt"
{ 'This is first line.' | out-file $tempFile } | Should Not Throw
{ 'This is second line.' | out-file -append $tempFile } | Should Not Throw
$tempFile |Should Contain "first"
$tempFile |Should Contain "second"
Remove-Item $tempFile -Force
}
}
Describe "Out-File" {
$expectedContent = "some test text"
$inObject = New-Object psobject -Property @{text=$expectedContent}
$testfile = Join-Path -Path $TestDrive -ChildPath outfileTest.txt
AfterEach {
Remove-Item -Path $testfile -Force
}
It "Should be able to be called without error" {
{ Out-File -FilePath $testfile } | Should Not Throw
}
It "Should be able to accept string input via piping" {
{ $expectedContent | Out-File -FilePath $testfile } | Should Not Throw
$actual = Get-Content $testfile
$actual | Should Be $expectedContent
}
It "Should be able to accept string input via the InputObject swictch" {
{ Out-File -FilePath $testfile -InputObject $expectedContent } | Should Not Throw
$actual = Get-Content $testfile
$actual | Should Be $expectedContent
}
It "Should be able to accept object input" {
{ $inObject | Out-File -FilePath $testfile } | Should Not Throw
{ Out-File -FilePath $testfile -InputObject $inObject } | Should Not Throw
}
It "Should not overwrite when the noclobber switch is used" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
Out-File -FilePath $testfile -InputObject $inObject
{ Out-File -FilePath $testfile -InputObject $inObject -NoClobber -ErrorAction SilentlyContinue } | Should Throw "already exists."
{ Out-File -FilePath $testfile -InputObject $inObject -NoOverWrite -ErrorAction SilentlyContinue } | Should Throw "already exists."
$actual = Get-Content $testfile
$actual[0] | Should Be ""
$actual[1] | Should Match "text"
$actual[2] | Should Match "----"
$actual[3] | Should Match "some test text"
}
It "Should Append a new line when the append switch is used" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
{ Out-File -FilePath $testfile -InputObject $inObject } | Should Not Throw
{ Out-File -FilePath $testfile -InputObject $inObject -Append } | Should Not Throw
$actual = Get-Content $testfile
$actual[0] | Should Be ""
$actual[1] | Should Match "text"
$actual[2] | Should Match "----"
$actual[3] | Should Match "some test text"
$actual[4] | Should Be ""
$actual[5] | Should Be ""
$actual[6] | Should Be ""
$actual[7] | Should Match "text"
$actual[8] | Should Match "----"
$actual[9] | Should Match "some test text"
$actual[10] | Should Be ""
$actual[11] | Should Be ""
}
It "Should limit each line to the specified number of characters when the width switch is used on objects" {
Out-File -FilePath $testfile -Width 10 -InputObject $inObject
$actual = Get-Content $testfile
$actual[0] | Should Be ""
$actual[1] | Should Be "text "
$actual[2] | Should Be "---- "
$actual[3] | Should Be "some te..."
}
It "Should allow the cmdlet to overwrite an existing read-only file" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
# create a read-only text file
{ Out-File -FilePath $testfile -InputObject $inObject } | Should Not Throw
Set-ItemProperty -Path $testfile -Name IsReadOnly -Value $true
# write information to the RO file
{ Out-File -FilePath $testfile -InputObject $inObject -Append -Force } | Should Not Throw
$actual = Get-Content $testfile
$actual[0] | Should Be ""
$actual[1] | Should Match "text"
$actual[2] | Should Match "----"
$actual[3] | Should Match "some test text"
$actual[4] | Should Be ""
$actual[5] | Should Be ""
$actual[6] | Should Be ""
$actual[7] | Should Match "text"
$actual[8] | Should Match "----"
$actual[9] | Should Match "some test text"
$actual[10] | Should Be ""
$actual[11] | Should Be ""
# reset to not read only so it can be deleted
Set-ItemProperty -Path $testfile -Name IsReadOnly -Value $false
}
}
@@ -0,0 +1,49 @@
Describe "Out-String DRT Unit Tests" -Tags DRT{
It "check display of properties with names containing wildcard characters" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$results = new-object psobject | add-member -passthru noteproperty 'name with square brackets: [0]' 'myvalue' | out-string
$results.Length | Should BeGreaterThan 1
$results.GetType() | Should Be string
$results.Contains("myvalue") | Should Be $true
$results.Contains("name with square brackets: [0]") | Should Be $true
}
}
Describe "Out-String" {
$nl = [Environment]::NewLine
It "Should accumulate the strings and returns them as a single string" {
$testArray = "a", " b"
$testArray.GetType().BaseType | Should Be array
$testArray | Out-String | Should Be "a$nl b$nl"
$($testArray | Out-String).GetType() | Should Be string
}
It "Should be able to return an array of strings using the stream switch" {
$testInput = "a", "b"
$($testInput | Out-String).GetType() | Should Be string
$($testInput | Out-String -Stream).GetType().BaseType.Name | Should Be array
}
It "Should send all objects through a pipeline when not using the stream switch" {
$testInput = "a", "b"
$streamoutputlength = $($testInput | Out-String -Stream).Length
$nonstreamoutputlength = $($testInput | Out-String).Length
$nonstreamoutputlength| Should BeGreaterThan $streamoutputlength
}
It "Should send a single object through a pipeline when the stream switch is used" {
$testInput = "a", "b"
$streamoutputlength = $($testInput | Out-String -Stream).Length
$nonstreamoutputlength = $($testInput | Out-String).Length
$streamoutputlength | Should BeLessThan $nonstreamoutputlength
}
}
@@ -0,0 +1,9 @@
Describe "Register-EngineEvent" {
Context "Check return type of Register-ObjectEvent" {
It "Should return System.Management.Automation.PSEventJob as return type of Register-EngineEvent" {
( Register-EngineEvent -SourceIdentifier PesterTestRegister -Action {echo registerengineevent} ).GetType() | Should Be System.Management.Automation.PSEventJob
Unregister-Event -sourceidentifier PesterTestRegister
}
}
}
@@ -0,0 +1,31 @@
Describe "Register-ObjectEvent" {
BeforeEach {
$pesterobject = (New-Object System.Collections.ObjectModel.ObservableCollection[object])
}
AfterEach {
Unregister-Event -SourceIdentifier PesterTestRegister -ErrorAction SilentlyContinue
}
Context "Check return type of Register-ObjectEvent" {
It "Should return System.Management.Automation.PSEventSubscriber as return type of New-Event with the registered sourceidentifier" {
Register-ObjectEvent -InputObject $pesterobject -EventName CollectionChanged -SourceIdentifier PesterTestRegister
(Get-EventSubscriber -SourceIdentifier PesterTestRegister).GetType() | Should Be System.Management.Automation.PSEventSubscriber
}
}
Context "Check Register-ObjectEvent can validly register events"{
It "Should return source identifier of PesterTimer " {
Register-ObjectEvent -InputObject $pesterobject -EventName CollectionChanged -SourceIdentifier PesterTestRegister
(Get-EventSubscriber -SourceIdentifier PesterTestRegister).SourceIdentifier | Should Be "PesterTestRegister"
}
It "Should return an integer greater than 0 for the SubscriptionId" {
Register-ObjectEvent -InputObject $pesterobject -EventName CollectionChanged -SourceIdentifier PesterTestRegister
(Get-EventSubscriber -SourceIdentifier PesterTestRegister).SubscriptionId | Should BeGreaterThan 0
}
}
}
@@ -0,0 +1,38 @@
Describe "Remove-Event" {
BeforeEach {
New-Event -sourceidentifier PesterTimer -sender Windows.timer -messagedata "PesterTestMessage"
}
AfterEach {
Remove-Event -sourceidentifier PesterTimer -ErrorAction SilentlyContinue
}
Context "Check Remove-Event can validly remove events" {
It "Should remove an event given a sourceidentifier" {
{ Remove-Event -sourceidentifier PesterTimer }
{ Get-Event -ErrorAction SilentlyContinue | Should Not Contain PesterTimer }
}
It "Should remove an event given an event identifier" {
{ $events = Get-Event -sourceidentifier PesterTimer }
{ $events = $events.EventIdentifier }
{ Remove-Event -EventIdentifier $events }
{ $events = Get-Event -ErrorAction SilentlyContinue}
{ $events.SourceIdentifier | Should Not Contain "PesterTimer" }
}
It "Should be able to remove an event given a pipe from Get-Event" {
{ Get-Event -sourceidentifier PesterTimer | Remove-Event }
{ Get-Event -ErrorAction SilentlyContinue | Should Not Contain "PesterTimer" }
}
It "Should NOT remove an event given the whatif flag" {
{ Remove-Event -sourceidentifier PesterTimer -whatif }
{ $events = Get-Event }
{ $events.SourceIdentifier | Should Contain "PesterTimer" }
}
}
}
@@ -0,0 +1,74 @@
Describe "Remove-PSBreakpoint" {
# Set up test script
$testScript = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath assets) -ChildPath psbreakpointtestscript.ps1
$script = "`$var = 1
`$var2 = Get-Command
# this is a comment
Get-Date
"
$script > $testScript
BeforeEach {
# set some breakpoints
$line = Set-PSBreakpoint -Line 1,2,3 -Script $testScript
$command = Set-PSBreakpoint -Command "Get-Date" -Script $testScript
$variable = Set-PSBreakpoint -Variable var2 -Script $testScript
}
Context "Basic Removal Methods Tests" {
It "Should be able to remove a breakpoint by breakpoint Id" {
$NumberOfBreakpoints = $(Get-PSBreakpoint).Id.length
$BreakID = $(Get-PSBreakpoint).Id[0]
Remove-PSBreakpoint -Id $BreakID
$(Get-PSBreakpoint).Id.length | Should Be ($NumberOfBreakpoints -1)
}
It "Should be able to remove a breakpoint by variable" {
$NumberOfBreakpoints = $(Get-PSBreakpoint).Id.length
Remove-PSBreakpoint -Breakpoint $variable
$(Get-PSBreakpoint).Id.length | Should Be ($NumberOfBreakpoints -1)
}
It "Should be able to remove a breakpoint by command" {
$NumberOfBreakpoints = $(Get-PSBreakpoint).Id.length
Remove-PSBreakpoint -Breakpoint $command
$(Get-PSBreakpoint).Id.length | Should Be ($NumberOfBreakpoints -1)
}
It "Should be able to pipe breakpoint objects to Remove-PSBreakpoint" {
$NumberOfBreakpoints = $(Get-PSBreakpoint).Id.length
$variable | Remove-PSBreakpoint
$(Get-PSBreakpoint).Id.length | Should Be ($NumberOfBreakpoints -1)
}
}
Context "Alias Tests" {
It "Should remove a breakpoint using the rbp alias" {
$NumberOfBreakpoints = $(Get-PSBreakpoint).Id.length
$BreakID = $(Get-PSBreakpoint).Id[0]
rbp -Id $BreakID
$(Get-PSBreakpoint).Id.length | Should Be ($NumberOfBreakpoints -1)
}
}
It "Should Remove all breakpoints" {
$(Get-PSBreakpoint).Id.Length | Should Not BeNullOrEmpty
Get-PSBreakpoint | Remove-PSBreakpoint
$(Get-PSBreakpoint).Id.Length | Should Be 0
}
#Clean up after ourselves
Remove-Item $testScript
}
@@ -0,0 +1,83 @@
Describe "Remove-TypeData DRT Unit Tests" -Tags DRT {
BeforeAll {
$XMLFile1 = Join-Path $TestDrive -ChildPath "testFile1.ps1xml"
$XMLFile2 = Join-Path $TestDrive -ChildPath "testFile2.ps1xml"
$content1 = @"
<Types>
<Type>
<Name>System.Array</Name>
<Members>
<AliasProperty>
<Name>Yada</Name>
<ReferencedMemberName>Length</ReferencedMemberName>
</AliasProperty>
</Members>
</Type>
</Types>
"@
$content2 = @"
<Types>
<Type>
<Name>System.Array</Name>
<Members>
<AliasProperty>
<Name>Yoda</Name>
<ReferencedMemberName>Length</ReferencedMemberName>
</AliasProperty>
</Members>
</Type>
</Types>
"@
$content1 > $XMLFile1
$content2 > $XMLFile2
}
BeforeEach {
$ps = [powershell]::Create()
$iss = [system.management.automation.runspaces.initialsessionstate]::CreateDefault2()
$rs = [system.management.automation.runspaces.runspacefactory]::CreateRunspace($iss)
$rs.Open()
$ps.Runspace = $rs
}
AfterEach {
$rs.Close()
$ps.Dispose()
}
It "Remove With Pipe line Input Pass Type Shortcut String" {
$null = $ps.AddScript("Update-TypeData -MemberType NoteProperty -MemberName TestNote -Value TestNote -TypeName int").Invoke()
$ps.Commands.Clear()
$ps.AddScript("(Get-TypeData System.Int32).TypeName").Invoke() | Should Be System.Int32
$ps.Commands.Clear()
$null = $ps.AddScript("'int' | Remove-TypeData").Invoke()
$ps.HadErrors | Should be $false
}
It "Remove Type File In Initial Session State" {
# setup
$null = $ps.AddScript("Update-TypeData -AppendPath $XMLFile1").Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript("Update-TypeData -AppendPath $XMLFile2").Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript('$a = 1..3').Invoke()
$ps.Commands.Clear()
# test
$ps.AddScript('$a.Yada').Invoke() | Should be 3
$ps.Commands.Clear()
$ps.AddScript('$a.Yoda').Invoke() | Should Be 3
$ps.Commands.Clear()
$null = $ps.AddScript("Remove-TypeData -Path $XMLFile1").Invoke()
$ps.Commands.Clear()
$ps.AddScript('$a.Yada').Invoke() | Should BeNullOrEmpty
$ps.Commands.Clear()
$ps.AddScript('$a.Yoda').Invoke() | Should Be 3
$ps.Commands.Clear()
}
It "Remove Type File In Initial Session State File Not In Cache" {
$null = $ps.AddScript("Remove-TypeData -Path fakefile").Invoke()
$ps.HadErrors | Should be $true
$ps.Streams.Error[0].FullyQualifiedErrorID | Should Be "TypePathException,Microsoft.PowerShell.Commands.RemoveTypeDataCommand"
}
}
@@ -0,0 +1,283 @@
# ensure the machine is in a clean state from the outset.
Remove-Variable -Name var1 -ErrorAction SilentlyContinue -Force
Describe "Remove-Variable" {
It "Should throw an error when a dollar sign is used in the variable name place" {
New-Variable -Name var1 -Value 4
Remove-Variable $var1 -ErrorAction SilentlyContinue | Should Throw
}
It "Should not throw error when used without the Name field, and named variable is properly specified and exists" {
New-Variable -Name var1 -Value 4
Remove-Variable var1
$var1 | Should Be #nothing. it should be Nothing at all.
}
It "Should not throw error when used with the Name field, and named variable is specified and exists" {
New-Variable -Name var1 -Value 2
Remove-Variable -Name var1
$var1 | Should Be #nothing. it should be Nothing at all.
}
It "Should throw error when used with Name field, and named variable does not exist" {
Remove-Variable -Name nonexistantVariable -ErrorAction SilentlyContinue | Should Throw
}
It "Should be able to remove a variable using the rv alias" {
New-Variable var1 -Value 2
$var1 | Should Be 2
rv -Name var1
$var1 | Should Be #nothing. it should be Nothing at all.
}
It "Should be able to remove a set of variables using wildcard characters" {
New-Variable tmpvar1 -Value "tempvalue"
New-Variable tmpvar2 -Value 2
New-Variable tmpmyvar1 -Value 234
$tmpvar1 | Should Be "tempvalue"
$tmpvar2 | Should Be 2
$tmpmyvar1 | Should Be 234
Remove-Variable -Name tmp*
$tmpvar1 | Should Be #nothing. it should be Nothing at all.
$tmpvar2 | Should Be #nothing. it should be Nothing at all.
$tmpmyvar1 | Should Be #nothing. it should be Nothing at all.
}
It "Should be able to exclude a set of variables to remove using the Exclude switch" {
New-Variable tmpvar1 -Value "tempvalue"
New-Variable tmpvar2 -Value 2
New-Variable tmpmyvar1 -Value 234
$tmpvar1 | Should Be "tempvalue"
$tmpvar2 | Should Be 2
$tmpmyvar1 | Should Be 234
Remove-Variable -Name tmp* -Exclude *my*
$tmpvar1 | Should Be #nothing. it should be Nothing at all.
$tmpvar2 | Should Be #nothing. it should be Nothing at all.
$tmpmyvar1 | Should Be 234
}
It "Should be able to include a set of variables to remove using the Include switch" {
New-Variable tmpvar1 -Value "tempvalue"
New-Variable tmpvar2 -Value 2
New-Variable tmpmyvar1 -Value 234
New-Variable thevar -Value 1
$tmpvar1 | Should Be "tempvalue"
$tmpvar2 | Should Be 2
$tmpmyvar1 | Should Be 234
$thevar | Should Be 1
Remove-Variable -Name tmp* -Include *my*
$tmpvar1 | Should Be "tempvalue"
$tmpvar2 | Should Be 2
$tmpmyvar1 | Should Be #nothing. it should be Nothing at all.
$thevar | should Be 1
Remove-Variable tmpvar1
Remove-Variable tmpvar2
Remove-Variable thevar
}
It "Should throw an error when attempting to remove a read-only variable and the Force switch is not used" {
New-Variable -Name var1 -Value 2 -Option ReadOnly
Remove-Variable -Name var1 -ErrorAction SilentlyContinue | Should Throw
$var1 | Should Be 2
Remove-Variable -Name var1 -Force
}
It "Should not throw an error when attempting to remove a read-only variable and the Force switch is used" {
New-Variable -Name var1 -Value 2 -Option ReadOnly
Remove-Variable -Name var1 -Force
$var1 | Should Be # Nothing. It should be nothing at all.
}
Context "Scope Tests" {
It "Should be able to remove a global variable using the global switch" {
New-Variable -Name var1 -Value "context" -Scope global
Remove-Variable -Name var1 -Scope global
$var1 | Should Be #Nothing.
}
It "Should not be able to clear a global variable using the local switch" {
New-Variable -Name var1 -Value "context" -Scope global
Remove-Variable -Name var1 -Scope local -ErrorAction SilentlyContinue | Should Throw
$var1 | Should Be "context"
Remove-Variable -Name var1 -Scope global
$var1 | Should Be # Nothing
}
It "Should not be able to clear a global variable using the script switch" {
New-Variable -Name var1 -Value "context" -Scope global
Remove-Variable -Name var1 -Scope local -ErrorAction SilentlyContinue | Should Throw
$var1 | Should Be "context"
Remove-Variable -Name var1 -Scope global
$var1 | Should Be # Nothing
}
It "Should be able to remove an item locally using the local switch" {
New-Variable -Name var1 -Value "context" -Scope local
Remove-Variable -Name var1 -Scope local -ErrorAction SilentlyContinue | Should Throw
$var1 | Should Be # Nothing
}
It "Should be able to remove an item locally using the global switch" {
New-Variable -Name var1 -Value "context" -Scope local
Remove-Variable -Name var1 -Scope global -ErrorAction SilentlyContinue | Should Throw
$var1 | Should Be "context"
Remove-Variable -Name var1 -Scope local
$var1 | Should Be # Nothing
}
It "Should be able to remove a local variable using the script scope switch" {
New-Variable -Name var1 -Value "context" -Scope local
Remove-Variable -Name var1 -Scope script -ErrorAction SilentlyContinue | Should Throw
$var1 | Should Be "context"
Remove-Variable -Name var1 -Scope local
$var1 | Should Be # Nothing
}
It "Should be able to remove a script variable created using the script switch" {
New-Variable -Name var1 -Value "context" -Scope script
Remove-Variable -Name var1 -Scope script | Should Throw
$var1 | Should Be # Nothing
}
It "Should not be able to remove a global script variable that was created using the script scope switch" {
New-Variable -Name var1 -Value "context" -Scope script
Remove-Variable -Name var1 -Scope global -ErrorAction SilentlyContinue | Should Throw
$var1 | Should Be "context"
}
}
}
Describe "Remove-Variable basic functionality" -Tags DRT{
It "Remove-Variable variable should works"{
New-Variable foo bar
Remove-Variable foo
$var1 = Get-Variable -Name foo -EA SilentlyContinue
$var1 | Should BeNullOrEmpty
}
It "Remove-Variable Constant variable should throw SessionStateUnauthorizedAccessException"{
New-Variable foo bar -Option Constant
try
{
Remove-Variable foo -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo | Should Match "SessionStateUnauthorizedAccessException"
$_.FullyQualifiedErrorId | Should be "VariableNotRemovable,Microsoft.PowerShell.Commands.RemoveVariableCommand"
}
}
It "Remove-Variable ReadOnly variable should throw SessionStateUnauthorizedAccessException and force remove should work"{
New-Variable foo bar -Option ReadOnly
try
{
Remove-Variable foo -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo| Should Match "SessionStateUnauthorizedAccessException"
$_.FullyQualifiedErrorId | Should be "VariableNotRemovable,Microsoft.PowerShell.Commands.RemoveVariableCommand"
}
Remove-Variable foo -Force
$var1 = Get-Variable -Name foo -EA SilentlyContinue
$var1 | Should BeNullOrEmpty
}
It "Remove-Variable Constant variable should throw SessionStateUnauthorizedAccessException and force remove should also throw exception"{
New-Variable foo bar -Option Constant
try
{
Remove-Variable foo -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo | Should Match "SessionStateUnauthorizedAccessException"
$_.FullyQualifiedErrorId | Should be "VariableNotRemovable,Microsoft.PowerShell.Commands.RemoveVariableCommand"
}
try
{
Remove-Variable foo -Force -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo | Should Match "SessionStateUnauthorizedAccessException"
$_.FullyQualifiedErrorId | Should be "VariableNotRemovable,Microsoft.PowerShell.Commands.RemoveVariableCommand"
}
}
It "Remove-Variable variable in new scope should works and Get-Variable with different scope should have different result"{
New-Variable foo bar
&{
Clear-Variable foo
Remove-Variable foo
try{
Get-Variable -Name foo -Scope local -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo | Should Match "ItemNotFoundException"
$_.FullyQualifiedErrorId | Should be "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand"
}
}
$var1 = Get-Variable -Name foo
$var1.Name | Should Be "foo"
$var1.Value | Should Be "bar"
$var1.Options | Should Be "None"
$var1.Description | Should Be ""
}
}
@@ -0,0 +1,250 @@
. (Join-Path -Path $PSScriptRoot -ChildPath Test-Mocks.ps1)
Describe "Select-Object" {
BeforeEach {
$dirObject = GetFileMock
$TestLength = 3
}
It "Handle piped input without error" {
{ $dirObject | Select-Object } | Should Not Throw
}
It "Should treat input as a single object with the inputObject parameter" {
$result = $(Select-Object -inputObject $dirObject -last $TestLength).Length
$expected = $dirObject.Length
$result | Should Be $expected
}
It "Should be able to use the alias" {
{ $dirObject | select } | Should Not Throw
}
It "Should have same result when using alias" {
$result = $dirObject | select
$expected = $dirObject | Select-Object
$result | Should Be $expected
}
It "Should return correct object with First parameter" {
$result = $dirObject | Select-Object -First $TestLength
$result.Length | Should Be $TestLength
for ($i=0; $i -lt $TestLength; $i++)
{
$result[$i].Name | Should Be $dirObject[$i].Name
}
}
It "Should return correct object with Last parameter" {
$result = $dirObject | Select-Object -Last $TestLength
$result.Length | Should Be $TestLength
for ($i=0; $i -lt $TestLength; $i++)
{
$result[$i].Name | Should Be $dirObject[$dirObject.Length - $TestLength + $i].Name
}
}
It "Should work correctly with Unique parameter" {
$result = ("a","b","c","a","a","a" | Select-Object -Unique).Length
$expected = 3
$result | Should Be $expected
}
It "Should return correct object with Skip parameter" {
$result = $dirObject | Select-Object -Skip $TestLength
$result.Length | Should Be ($dirObject.Length - $TestLength)
for ($i=0; $i -lt $TestLength; $i++)
{
$result[$i].Name | Should Be $dirObject[$TestLength + $i].Name
}
}
It "Should return an object with selected columns" {
$result = $dirObject | Select-Object -Property Name, Size
$result.Length | Should Be $dirObject.Length
$result[0].Name | Should Be $dirObject[0].Name
$result[0].Size | Should Be $dirObject[0].Size
$result[0].Mode | Should BeNullOrEmpty
}
It "Should send output to pipe properly" {
{$dirObject | Select-Object -Unique | pipelineConsume} | Should Not Throw
}
It "Should select array indices with Index parameter" {
$firstIndex = 2
$secondIndex = 4
$result = $dirObject | Select-Object -Index $firstIndex, $secondIndex
$result[0].Name | Should Be $dirObject[$firstIndex].Name
$result[1].Name | Should Be $dirObject[$secondIndex].Name
}
# Note that these two tests will modify original values of $dirObject
It "Should not wait when used without -Wait option" {
$orig1 = $dirObject[0].Size
$orig2 = $dirObject[$TestLength].Size
$result = $dirObject | addOneToSizeProperty | Select-Object -First $TestLength
$result[0].Size | Should Be ($orig1 + 1)
$dirObject[0].Size | Should Be ($orig1 + 1)
$dirObject[$TestLength].Size | Should Be $orig2
}
It "Should wait when used with -Wait option" {
$orig1 = $dirObject[0].Size
$orig2 = $dirObject[$TestLength].Size
$result = $dirObject | addOneToSizeProperty | Select-Object -First $TestLength -Wait
$result[0].Size | Should Be ($orig1 + 1)
$dirObject[0].Size | Should Be ($orig1 + 1)
$dirObject[$TestLength].Size | Should Be ($orig2 + 1)
}
}
Describe "Select-Object DRT basic functionality" -Tags DRT{
BeforeAll {
$employees = [pscustomobject]@{"FirstName"="joseph"; "LastName"="smith"; "YearsInMS"=15},
[pscustomobject]@{"FirstName"="paul"; "LastName"="smith"; "YearsInMS"=15},
[pscustomobject]@{"FirstName"="mary"; "LastName"="soe"; "YearsInMS"=5},
[pscustomobject]@{"FirstName"="edmund"; "LastName"="bush"; "YearsInMS"=9}
}
It "Select-Object with empty script block property should throw"{
try
{
"bar" | select-object -Prop {} -EA Stop
Throw "Execution OK"
}
catch
{
$_.CategoryInfo | Should Match "PSArgumentException"
$_.FullyQualifiedErrorId | Should be "EmptyScriptBlockAndNoName,Microsoft.PowerShell.Commands.SelectObjectCommand"
}
}
It "Select-Object with string property should work"{
$result = "bar" | select-object -Prop foo | Measure-Object
$result.Count | Should Be 1
}
It "Select-Object with Property First Last Overlap should work"{
$results = $employees | Select-Object -Property "YearsInMS", "L*" -First 2 -Last 3
$results.Count | Should Be 4
$results[0].LastName | Should Be $employees[0].LastName
$results[1].LastName | Should Be $employees[1].LastName
$results[2].LastName | Should Be $employees[2].LastName
$results[3].LastName | Should Be $employees[3].LastName
$results[0].YearsInMS | Should Be $employees[0].YearsInMS
$results[1].YearsInMS | Should Be $employees[1].YearsInMS
$results[2].YearsInMS | Should Be $employees[2].YearsInMS
$results[3].YearsInMS | Should Be $employees[3].YearsInMS
}
It "Select-Object with Property First Last should work"{
$results = $employees | Select-Object -Property "YearsInMS", "L*" -First 2 -Last 1
$results.Count | Should Be 3
$results[0].LastName | Should Be $employees[0].LastName
$results[1].LastName | Should Be $employees[1].LastName
$results[2].LastName | Should Be $employees[3].LastName
$results[0].YearsInMS | Should Be $employees[0].YearsInMS
$results[1].YearsInMS | Should Be $employees[1].YearsInMS
$results[2].YearsInMS | Should Be $employees[3].YearsInMS
}
It "Select-Object with Property First should work"{
$results = $employees | Select-Object -Property "YearsInMS", "L*" -First 2
$results.Count | Should Be 2
$results[0].LastName | Should Be $employees[0].LastName
$results[1].LastName | Should Be $employees[1].LastName
$results[0].YearsInMS | Should Be $employees[0].YearsInMS
$results[1].YearsInMS | Should Be $employees[1].YearsInMS
}
It "Select-Object with Property First Zero should work"{
$results = $employees | Select-Object -Property "YearsInMS", "L*" -First 0
$results.Count | Should Be 0
}
It "Select-Object with Property Last Zero should work"{
$results = $employees | Select-Object -Property "YearsInMS", "L*" -Last 0
$results.Count | Should Be 0
}
It "Select-Object with Unique should work"{
$results = $employees | Select-Object -Property "YearsInMS", "L*" -Unique:$true
$results.Count | Should Be 3
$results[0].LastName | Should Be $employees[1].LastName
$results[1].LastName | Should Be $employees[2].LastName
$results[2].LastName | Should Be $employees[3].LastName
$results[0].YearsInMS | Should Be $employees[1].YearsInMS
$results[1].YearsInMS | Should Be $employees[2].YearsInMS
$results[2].YearsInMS | Should Be $employees[3].YearsInMS
}
It "Select-Object with Simple should work"{
$employee1 = [pscustomobject]@{"FirstName"="joesph"; "LastName"="smith"; "YearsInMS"=15}
$employee2 = [pscustomobject]@{"FirstName"="paul"; "LastName"="smith"; "YearsInMS"=15}
$employee3 = [pscustomobject]@{"FirstName"="mary"; "LastName"="soe"; "YearsInMS"=15}
$employees3 = @($employee1,$employee2,$employee3,$employee4)
$results = $employees3 | Select-Object -Property "FirstName", "YearsInMS"
$results.Count | Should Be 3
$results[0].FirstName | Should Be $employees3[0].FirstName
$results[1].FirstName | Should Be $employees3[1].FirstName
$results[2].FirstName | Should Be $employees3[2].FirstName
$results[0].YearsInMS | Should Be $employees3[0].YearsInMS
$results[1].YearsInMS | Should Be $employees3[1].YearsInMS
$results[2].YearsInMS | Should Be $employees3[2].YearsInMS
}
It "Select-Object with no input should work"{
$results = $null | Select-Object -Property "FirstName", "YearsInMS", "FirstNa*"
$results.Count | Should Be 0
}
It "Select-Object with Start-Time In Idle Process should work"{
$results = Get-Process i* | Select-Object ProcessName
$results.Count | Should Not Be 0
}
It "Select-Object with Skip should work"{
$results = "1","2","3" | Select-Object -Skip 1
$results.Count | Should Be 2
$results[0] | Should Be 2
$results[1] | Should Be 3
}
It "Select-Object with Index should work"{
$results = "1","2","3" | Select-Object -Index 2
$results.Count | Should Be 1
$results[0] | Should Be "3"
}
}
@@ -0,0 +1,185 @@
Describe "Select-String" {
$nl = [Environment]::NewLine
$currentDirectory = $pwd.Path
Context "String actions" {
$testinputone = "hello","Hello","goodbye"
$testinputtwo = "hello","Hello"
it "Should be called without errors" {
{ $testinputone | Select-String -Pattern "hello" } | Should Not Throw
}
it "Should be called without error using the sls alias" {
{ $testinputone | sls -Pattern "hello" } | Should Not Throw
}
it "Should return an array data type when multiple matches are found" {
( $testinputtwo | Select-String -Pattern "hello").gettype().basetype | Should Be Array
}
it "Should return the same result for the alias sls and Select-String " {
$firstMatch = $testinputone | Select-String -Pattern "hello"
$secondMatch = $testinputone | sls -Pattern "hello"
$equal = @(compare-object $firstMatch $secondMatch).Length -eq 0
$equal | Should Be True
}
it "Should return an object type when one match is found" {
( $testinputtwo | Select-String -Pattern "hello" -CaseSensitive).gettype().basetype | Should Be System.Object
}
it "Should return matchinfo type" {
( $testinputtwo | Select-String -Pattern "hello" -CaseSensitive).gettype().name | Should Be MatchInfo
}
it "Should be called without an error using ca for casesensitive " {
{$testinputone | Select-String -Pattern "hello" -ca } | Should Not Throw
}
it "Should use the ca alias for casesenstive" {
$firstMatch = $testinputtwo | Select-String -Pattern "hello" -CaseSensitive
$secondMatch = $testinputtwo | Select-String -Pattern "hello" -ca
$equal = @(Compare-Object $firstMatch $secondMatch).Length -eq 0
$equal | Should Be True
}
it "Should only return the case sensitive match when the casesensitive switch is used" {
$testinputtwo | Select-String -Pattern "hello" -CaseSensitive | Should Be "hello"
}
it "Should accept a collection of strings from the input object" {
{ Select-String -InputObject "some stuff", "other stuff" -Pattern "other" } | Should Not Throw
}
it "Should return system.object when the input object switch is used on a collection" {
( Select-String -InputObject "some stuff", "other stuff" -pattern "other" ).gettype().basetype | Should Be System.Object
}
it "Should return null or empty when the input object switch is used on a collection and the pattern does not exist" {
Select-String -InputObject "some stuff", "other stuff" -Pattern "neither" | Should BeNullOrEmpty
}
it "Should return a bool type when the quiet switch is used" {
($testinputtwo | Select-String -Quiet "hello" -CaseSensitive).gettype() | Should Be Bool
}
it "Should be true when select string returns a positive result when the quiet switch is used" {
($testinputtwo | Select-String -Quiet "hello" -CaseSensitive) | Should Be $True
}
it "Should be empty when select string does not return a result when the quiet switch is used" {
$testinputtwo | Select-String -Quiet "goodbye" | Should BeNullOrEmpty
}
it "Should return an array of non matching strings when the switch of NotMatch is used and the string do not match" {
$testinputone | Select-String -Pattern "goodbye" -NotMatch | Should Be "hello", "hello"
}
it "Should return the same as NotMatch" {
$firstMatch = $testinputone | Select-String -pattern "goodbye" -NotMatch
$secondMatch = $testinputone | Select-String -pattern "goodbye" -n
$equal = @(Compare-Object $firstMatch $secondMatch).Length -eq 0
$equal | Should Be True
}
}
Context "Filesytem actions" {
$testDirectory = $TestDrive
$testInputFile = Join-Path -Path $testDirectory -ChildPath testfile1.txt
BeforeEach {
New-Item $testInputFile -Itemtype "file" -Force -Value "This is a text string, and another string${nl}This is the second line${nl}This is the third line${nl}This is the fourth line${nl}No matches"
}
AfterEach {
Remove-Item $testInputFile -Force
}
It "Should return an object when a match is found is the file on only one line" {
(Select-String $testInputFile -Pattern "string").GetType().BaseType | Should be System.Object
}
It "Should return an array when a match is found is the file on several lines" {
(Select-String $testInputFile -Pattern "in").GetType().BaseType | Should be array
(Select-String $testInputFile -Pattern "in")[0].GetType().Name | Should Be MatchInfo
}
It "Should return the name of the file and the string that 'string' is found if there is only one lines that has a match" {
$expected = $testInputFile + ":1:This is a text string, and another string"
Select-String $(Split-Path $testInputFile -NoQualifier) -Pattern "string" | Should Be $expected
}
It "Should return all strings where 'second' is found in testfile1 if there is only one lines that has a match" {
$expected = $testInputFile + ":2:This is the second line"
Select-String $testInputFile -Pattern "second"| Should Be $expected
}
It "Should return all strings where 'in' is found in testfile1 pattern switch is not required" {
$expected1 = "This is a text string, and another string"
$expected2 = "This is the second line"
$expected3 = "This is the third line"
$expected4 = "This is the fourth line"
(Select-String in $testInputFile)[0].Line | Should Be $expected1
(Select-String in $testInputFile)[1].Line | Should Be $expected2
(Select-String in $testInputFile)[2].Line | Should Be $expected3
(Select-String in $testInputFile)[3].Line | Should Be $expected4
(Select-String in $testInputFile)[4].Line | Should BeNullOrEmpty
}
It "Should return empty because 'for' is not found in testfile1 " {
Select-String for $testInputFile | Should BeNullOrEmpty
}
It "Should return the third line in testfile1 and the lines above and below it " {
$expectedLine = "testfile1.txt:2:This is the second line"
$expectedLineBefore = "testfile1.txt:3:This is the third line"
$expectedLineAfter = "testfile1.txt:4:This is the fourth line"
Select-String third $testInputFile -Context 1 | Should Match $expectedLine
Select-String third $testInputFile -Context 1 | Should Match $expectedLineBefore
Select-String third $testInputFile -Context 1 | Should Match $expectedLineAfter
}
It "Should return the number of matches for 'is' in textfile1 " {
(Select-String is $testInputFile -CaseSensitive).count| Should Be 4
}
It "Should return the third line in testfile1 when a relative path is used" {
$expected = "testfile1.txt:3:This is the third line"
$relativePath = Join-Path -Path $testDirectory -ChildPath ".."
$relativePath = Join-Path -Path $relativePath -ChildPath ".."
$relativePath = Join-Path -Path $relativePath -ChildPath (Split-Path $testDirectory -NoQualifier)
$relativePath = Join-Path -Path $relativePath -ChildPath testfile1.txt
Select-String third $relativePath | Should Match $expected
}
It "Should return the fourth line in testfile1 when a relative path is used" {
$expected = "testfile1.txt:5:No matches"
pushd $testDirectory
Select-String matches (Join-Path -Path $testDirectory -ChildPath testfile1.txt) | Should Match $expected
popd
}
It "Should return the fourth line in testfile1 when a regular expression is used" {
$expected = "testfile1.txt:5:No matches"
Select-String 'matc*' $testInputFile -CaseSensitive | Should Match $expected
}
It "Should return the fourth line in testfile1 when a regular expression is used, using the alias for casesensitive" {
$expected = "testfile1.txt:5:No matches"
Select-String 'matc*' $testInputFile -ca | Should Match $expected
}
}
Push-Location $currentDirectory
}
@@ -0,0 +1,28 @@
Describe "Select-XML DRT Unit Tests" -Tags DRT{
BeforeAll {
$testfile = Join-Path -Path $TestDrive -ChildPath "testfile.xml"
$xmlContent = @"
<?xml version ="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="CHILDREN">
<title lang="english">Harry Potter</title>
<price>30.00</price>
</book>
<book category="WEB">
<title lang="english">Learning XML</title>
<price>25.00</price>
</book>
</bookstore>
"@
$xmlContent >$testfile
}
It "Select-XML should work"{
$results = Select-XML -Path $testfile -XPath "/bookstore/book/title"
$results.Count | Should Be 2
$results[0].Node."#text" | Should Be "Harry Potter"
$results[1].Node."#text" | Should Be "Learning XML"
}
}
@@ -0,0 +1,109 @@
Describe "Set-Alias DRT Unit Tests" -Tags DRT{
It "Set-Alias Invalid Scope Name should throw PSArgumentException"{
try {
Set-Alias -Name "ABCD" -Value "foo" -Scope "bogus"
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "Argument,Microsoft.PowerShell.Commands.SetAliasCommand"
}
}
It "Set-Alias ReadOnly Force"{
Set-Alias -Name ABCD -Value "foo" -Option ReadOnly -Force:$true
$result=Get-Alias -Name ABCD
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo"
$result.Description| Should Be ""
$result.Options| Should Be "ReadOnly"
Set-Alias -Name ABCD -Value "foo" -Force:$true
$result=Get-Alias -Name ABCD
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
}
It "Set-Alias Name And Value Valid"{
Set-Alias -Name ABCD -Value "MyCommand"
$result=Get-Alias -Name ABCD
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "MyCommand"
$result.Description| Should Be ""
$result.Options| Should Be "None"
}
It "Set-Alias Name And Value Positional Valid"{
Set-Alias -Name ABCD "foo"
$result=Get-Alias ABCD
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
}
It "Set-Alias Description Valid"{
Set-Alias -Name ABCD -Value "MyCommand" -Description "test description"
$result=Get-Alias -Name ABCD
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "MyCommand"
$result.Description| Should Be "test description"
$result.Options| Should Be "None"
}
It "Set-Alias Scope Valid"{
Set-Alias -Name ABCD -Value "localfoo" -scope local -Force:$true
Set-Alias -Name ABCD -Value "foo1" -scope "1" -Force:$true
$result=Get-Alias -Name ABCD
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "localfoo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
$result=Get-Alias -Name ABCD -scope local
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "localfoo"
$result.Description| Should Be ""
$result.Options| Should Be "None"
$result=Get-Alias -Name ABCD -scope "1"
$result.Name| Should Be "ABCD"
$result.Definition| Should Be "foo1"
$result.Description| Should Be ""
$result.Options| Should Be "None"
}
It "Set-Alias Expose Bug 1062958, BugId:905449"{
try {
Set-Alias -Name "ABCD" -Value "foo" -Scope "-1"
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "ArgumentOutOfRange,Microsoft.PowerShell.Commands.SetAliasCommand"
}
}
}
Describe "Set-Alias" {
Mock Get-Date { return "Friday, October 30, 2015 3:38:08 PM" }
It "Should be able to set alias without error" {
{ set-alias -Name gd -Value Get-Date } | Should Not Throw
}
It "Should be able to have the same output between set-alias and the output of the function being aliased" {
set-alias -Name gd -Value Get-Date
gd | Should Be $(Get-Date)
}
It "Should be able to use the sal alias" {
{ sal gd Get-Date } | Should Not Throw
}
It "Should have the same output between the sal alias and the original set-alias cmdlet" {
sal -Name gd -Value Get-Date
Set-Alias -Name gd2 -Value Get-Date
gd2 | Should Be $(gd)
}
}
@@ -0,0 +1,229 @@
$ps = Join-Path -Path $PsHome -ChildPath "powershell"
Describe "Set-PSBreakpoint DRT Unit Tests" -Tags DRT {
#Set up
$scriptFileName = Join-Path $TestDrive -ChildPath breakpointTestScript.ps1
$scriptFileNameBug = Join-Path -Path $TestDrive -ChildPath SetPSBreakpointTests.ExposeBug154112.ps1
$contents = @"
function Hello
{
`$greeting = 'Hello, world!'
write-host `$greeting
}
function Goodbye
{
`$message = 'Good bye, cruel world!'
write-host `$message
}
Hello
Goodbye
# The following 2 statements produce null tokens (needed to verify 105473)
#
`$table = @{}
return
"@
$contentsBug = @"
set-psbreakpoint -variable foo
set-psbreakpoint -command foo
"@
$contents > $scriptFileName
$contentsBug > $scriptFileNameBug
It "Should be able to set psbreakpoints for -Line" {
$brk = Set-PSBreakpoint -Line 13 -Script $scriptFileName
$brk.Line | Should Be 13
Remove-PSBreakPoint -Id $brk.Id
}
It "Should be able to set psbreakpoints for -Line and -column" {
$brk = set-psbreakpoint -line 13 -column 1 -script $scriptFileName
$brk.Line | Should Be 13
$brk.Column | Should Be 1
Remove-PSBreakPoint -Id $brk.Id
}
It "Should be able to set psbreakpoints for -Line and -action" {
$brk = set-psbreakpoint -line 13 -action {{ break; }} -script $scriptFileName
$brk.Line | Should Be 13
$brk.Action | Should Match "break"
Remove-PSBreakPoint -Id $brk.Id
}
It "Should be able to set psbreakpoints for -Line, -column and -action" {
$brk = set-psbreakpoint -line 13 -column 1 -action {{ break; }} -script $scriptFileName
$brk.Line | Should Be 13
$brk.Column | Should Be 1
$brk.Action | Should Match "break"
Remove-PSBreakPoint -Id $brk.Id
}
It "-script and -line can take multiple items" {
$brk = sbp -line 11,12,13 -column 1 -script $scriptFileName,$scriptFileName
$brk.Line | Should Be 11,12,13
$brk.Column | Should Be 1
Remove-PSBreakPoint -Id $brk.Id
}
It "-script and -line are positional" {
$brk = sbp $scriptFileName 13
$brk.Line | Should Be 13
Remove-PSBreakPoint -Id $brk.Id
}
It "-script, -line and -column are positional" {
$brk = sbp $scriptFileName 13 1
$brk.Line | Should Be 13
$brk.Column | Should Be 1
Remove-PSBreakPoint -Id $brk.Id
}
It "Should throw Exception when missing mandatory parameter -line" -Pending {
$output = & $ps -noninteractive -command "sbp -column 1 -script $scriptFileName"
[system.string]::Join(" ", $output) | Should Match "MissingMandatoryParameter,Microsoft.PowerShell.Commands.SetPSBreakpointCommand"
}
It "Should throw Exception when missing mandatory parameter" -Pending {
$output = & $ps -noprofile -noninteractive -command "sbp -line 1"
[system.string]::Join(" ", $output) | Should Match "MissingMandatoryParameter,Microsoft.PowerShell.Commands.SetPSBreakpointCommand"
}
It "Should be able to set psbreakpoints for -command" {
$brk = set-psbreakpoint -command "write-host"
$brk.Command | Should Be "write-host"
Remove-PSBreakPoint -Id $brk.Id
}
It "Should be able to set psbreakpoints for -command, -script" {
$brk = set-psbreakpoint -command "write-host" -script $scriptFileName
$brk.Command | Should Be "write-host"
Remove-PSBreakPoint -Id $brk.Id
}
It "Should be able to set psbreakpoints for -command, -action and -script" {
$brk = set-psbreakpoint -command "write-host" -action {{ break; }} -script $scriptFileName
$brk.Action | Should Match "break"
Remove-PSBreakPoint -Id $brk.Id
}
It "-Command can take multiple items" {
$brk = set-psbreakpoint -command write-host,Hello
$brk.Command | Should Be write-host,Hello
Remove-PSBreakPoint -Id $brk.Id
}
It "-Script is positional" {
$brk = set-psbreakpoint -command "Hello" $scriptFileName
$brk.Command | Should Be "Hello"
Remove-PSBreakPoint -Id $brk.Id
$brk = set-psbreakpoint $scriptFileName -command "Hello"
$brk.Command | Should Be "Hello"
Remove-PSBreakPoint -Id $brk.Id
}
It "Should be able to set breakpoints on functions" {
$brk = set-psbreakpoint -command Hello,Goodbye -script $scriptFileName
$brk.Command | Should Be Hello,Goodbye
Remove-PSBreakPoint -Id $brk.Id
}
It "Should be throw Exception when Column number less than 1" {
try {
set-psbreakpoint -line 1 -column -1 -script $scriptFileName
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should Be "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SetPSBreakpointCommand"
}
}
It "Should be throw Exception when Line number less than 1" {
$ErrorActionPreference = "Stop"
try {
set-psbreakpoint -line -1 -script $scriptFileName
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should Be "SetPSBreakpoint:LineLessThanOne,Microsoft.PowerShell.Commands.SetPSBreakpointCommand"
}
$ErrorActionPreference = "SilentlyContinue"
}
It "Remove implicit script from 'set-psbreakpoint -script'" {
& $ps -noprofile $scriptFileNameBug
$breakpoint = Get-PSBreakpoint -Script $scriptFileNameBug
$breakpoint | Should BeNullOrEmpty
}
It "Fail to set psbreakpoints when script is a file of wrong type" {
$tempFile = [System.IO.Path]::GetTempFileName()
$ErrorActionPreference = "Stop"
{
Set-PSBreakpoint -Script $tempFile -Line 1
} | Should Throw
$ErrorActionPreference = "SilentlyContinue"
Remove-Item $tempFile -Force
}
It "Fail to set psbreakpoints when script file does not exist" {
$ErrorActionPreference = "Stop"
${script.ps1} = 10
{
Set-PSBreakpoint -Script variable:\script.ps1 -Line 1
} | Should Throw
$ErrorActionPreference = "SilentlyContinue"
}
# clean up
Remove-Item -Path $scriptFileName -Force
Remove-Item -Path $scriptFileNameBug -Force
}
Describe "Set-PSBreakpoint" {
# Set up test script
$testScript = Join-Path -Path $PSScriptRoot -ChildPath psbreakpointtestscript.ps1
"`$var = 1 " > $testScript
It "Should be able to set a psbreakpoint on a line" {
$lineNumber = 1
$brk = Set-PSBreakpoint -Line $lineNumber -Script $testScript
$brk.Line | Should Be $lineNumber
Remove-PSBreakPoint -Id $brk.Id
}
It "Should throw when a string is entered for a line number" {
{
$lineNumber = "one"
Set-PSBreakpoint -Line $lineNumber -Script $testScript
} | Should Throw
}
It "Should be able to set a psbreakpoint on a Command" {
$command = "theCommand"
$brk = Set-PSBreakpoint -Command $command -Script $testScript
$brk.Command | Should Be $command
Remove-PSBreakPoint -Id $brk.Id
}
It "Should be able to set a psbreakpoint on a variable" {
$var = "theVariable"
$brk = Set-PSBreakpoint -Command $var -Script $testScript
$brk.Command | Should Be $var
Remove-PSBreakPoint -Id $brk.Id
}
# clean up after ourselves
Remove-Item -Path $testScript
}
@@ -0,0 +1,243 @@
Describe "Set-Variable DRT Unit Tests" -Tags DRT{
It "Set-Variable normal variable Name should works"{
Set-Variable foo bar
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
}
It "Set-Variable normal variable Name with position should works"{
Set-Variable -Name foo bar
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
}
It "Set-Variable normal variable Name with scope should works"{
Set-Variable -Name foo -Value bar0
Set-Variable -Name foo -Value bar -Scope "1"
$var1=Get-Variable -Name foo -scope "1"
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
Set-Variable -Name foo -Value newValue -Scope "local"
$var1=Get-Variable -Name foo -scope "local"
$var1.Name|Should Be "foo"
$var1.Value|Should Be "newValue"
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
Set-Variable -Name foo -Value newValue2 -Scope "script"
$var1=Get-Variable -Name foo -scope "script"
$var1.Name|Should Be "foo"
$var1.Value|Should Be "newValue2"
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
}
It "Set-Variable normal variable Name with position should works"{
Set-Variable abcaVar bar
Set-Variable bcdaVar anotherVal
Set-Variable aVarfoo bogusval
Set-Variable -Name "*aV*" -Value "overwrite" -Include "*Var*" -Exclude "bcd*"
$var1=Get-Variable -Name "*aVar*" -Scope "local"
$var1[0].Name|Should Be "abcaVar"
$var1[0].Value|Should Be "overwrite"
$var1[0].Options|Should Be "None"
$var1[0].Description|Should Be ""
$var1[1].Name|Should Be "aVarfoo"
$var1[1].Value|Should Be "overwrite"
$var1[1].Options|Should Be "None"
$var1[1].Description|Should Be ""
$var1[2].Name|Should Be "bcdaVar"
$var1[2].Value|Should Be "anotherVal"
$var1[2].Options|Should Be "None"
$var1[2].Description|Should Be ""
}
It "Set-Variable normal variable Name with Description and Value should works"{
Set-Variable foo bar
Set-Variable -Name foo $null -Description "new description" -PassThru:$true -Scope "local"
$var1=Get-Variable -Name foo -Scope "local"
$var1.Name|Should Be "foo"
$var1.Value|Should Be $null
$var1.Options|Should Be "None"
$var1.Description|Should Be "new description"
}
It "Set-Variable normal variable Name with just Description should works"{
Set-Variable foo bar
Set-Variable -Name foo -Description "new description" -PassThru:$true -Scope "local"
$var1=Get-Variable -Name foo -Scope "local"
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "None"
$var1.Description|Should Be "new description"
}
It "Set-Variable overwrite Constant Option should throw SessionStateUnauthorizedAccessException"{
Set-Variable -Name abcaVar bar -Option Constant -Scope "local"
try {
Set-Variable -Name abcaVar new -Scope "local" -EA Stop
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand"
}
}
It "Set-Variable of existing Private variable without force should throw Exception"{
Set-Variable abcaVar bar -Description "new description" -Option Private
$var1=Get-Variable -Name abcaVar
$var1.Name|Should Be "abcaVar"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "Private"
$var1.Description|Should Be "new description"
Set-Variable abcaVar other -Description "new description"
$var1=Get-Variable -Name abcaVar
$var1.Name|Should Be "abcaVar"
$var1.Value|Should Be "other"
$var1.Options|Should Be "Private"
$var1.Description|Should Be "new description"
}
It "Set-Variable with Exclude, then Get-Variable it should throw ItemNotFoundException"{
Set-Variable -Name foo1,foo2 hello -Exclude foo2 -EA Stop
try {
Get-Variable -Name foo2 -EA Stop
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand"
}
}
It "Set-Variable of existing ReadOnly variable without force should throw Exception"{
Set-Variable abcaVar bar -Description "new description" -Option ReadOnly
$var1=Get-Variable -Name abcaVar
$var1.Name|Should Be "abcaVar"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "ReadOnly"
$var1.Description|Should Be "new description"
try {
Set-Variable abcaVar -Option None -EA Stop
Throw "Execution OK"
}
catch {
$_.FullyQualifiedErrorId | Should be "VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand"
}
}
It "Set-Variable of ReadOnly variable with private scope should work"{
Set-Variable foo bar -Description "new description" -Option ReadOnly -scope "private"
$var1=Get-Variable -Name foo
$var1.Name|Should Be "foo"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "ReadOnly, Private"
$var1.Description|Should Be "new description"
}
It "Set-Variable pipeline with Get-Variable should work"{
$footest1="bar"
${Get-Variable footest1 -valueonly|Set-Variable bootest1 -passthru}
$var1=Get-Variable -Name footest1
$var1.Name|Should Be "footest1"
$var1.Value|Should Be "bar"
$var1.Options|Should Be "None"
$var1.Description|Should Be ""
}
}
Describe "Set-Variable" {
It "Should create a new variable with no parameters" {
{ Set-Variable testVar } | Should Not Throw
}
It "Should assign a value to a variable it has to create" {
Set-Variable -Name testVar -Value 4
Get-Variable testVar -ValueOnly | Should Be 4
}
It "Should change the value of an already existing variable" {
$testVar=1
$testVar | Should Not Be 2
Set-Variable testVar -Value 2
$testVar | Should Be 2
}
It "Should be able to be called with the set alias" {
set testVar -Value 1
$testVar | Should Be 1
}
It "Should be able to be called with the sv alias" {
sv testVar -Value 2
$testVar | Should Be 2
}
It "Should be able to set variable name using the Name parameter" {
Set-Variable -Name testVar -Value 1
$testVar | Should Be 1
}
It "Should be able to set the value of a variable by piped input" {
$testValue = "piped input"
$testValue | Set-Variable -Name testVar
$testVar | Should Be $testValue
}
It "Should be able to pipe object properties to output using the PassThru switch" -Pending:($env:TRAVIS_OS_NAME -eq "osx") {
$in = Set-Variable -Name testVar -Value "test" -Description "test description" -PassThru
$output = $in | Format-List -Property Description | Out-String
# This will cause errors running these tests in Windows
$output.Trim() | Should Be "Description : test description"
}
It "Should be able to set the value using the value switch" {
Set-Variable -Name testVar -Value 4
$testVar | Should Be 4
Set-Variable -Name testVar -Value "test"
$testVar | Should Be "test"
}
Context "Scope Tests" {
It "Should be able to set a global scope variable using the global switch" {
{ Set-Variable globalVar -Value 1 -Scope global -Force } | Should Not Throw
}
It "Should be able to set a global variable using the script scope switch" {
{ Set-Variable globalVar -Value 1 -Scope script -Force } | Should Not Throw
}
It "Should be able to set an item locally using the local switch" {
{ Set-Variable globalVar -Value 1 -Scope local -Force } | Should Not Throw
}
}
}
@@ -0,0 +1,224 @@
Describe "Sort-Object" {
It "should be able to sort object in ascending with using Property switch" {
{ Get-ChildItem -Path $PSScriptRoot -Include *.ps1 -Recurse | Sort-Object -Property Length } | Should Not Throw
$firstLen = (Get-ChildItem -Path $PSScriptRoot -Include *.ps1 -Recurse | Sort-Object -Property Length | Select-Object -First 1).Length
$lastLen = (Get-ChildItem -Path $PSScriptRoot -Include *.ps1 -Recurse | Sort-Object -Property Length | Select-Object -Last 1).Length
$firstLen -lt $lastLen | Should be $true
}
It "should be able to sort object in descending with using Descending switch" {
{ Get-ChildItem -Path $PSScriptRoot -Include *.ps1 -Recurse | Sort-Object -Property Length -Descending } | Should Not Throw
$firstLen = (Get-ChildItem -Path $PSScriptRoot -Include *.ps1 -Recurse | Sort-Object -Property Length -Descending | Select-Object -First 1).Length
$lastLen = (Get-ChildItem -Path $PSScriptRoot -Include *.ps1 -Recurse | Sort-Object -Property Length -Descending | Select-Object -Last 1).Length
$firstLen -gt $lastLen | Should be $true
}
}
Describe "Sort-Object DRT Unit Tests" -Tags DRT{
It "Sort-Object with object array should work"{
$employee1 = [pscustomobject]@{"FirstName"="Eight"; "LastName"="Eight"; "YearsInMS"=8}
$employee2 = [pscustomobject]@{"FirstName"="Eight"; "YearsInMS"=$null}
$employee3 = [pscustomobject]@{"FirstName"="Minus"; "LastName"="Two"; "YearsInMS"=-2}
$employee4 = [pscustomobject]@{"FirstName"="One"; "LastName"="One"; "YearsInMS"=1}
$employees = @($employee1,$employee2,$employee3,$employee4)
$results = $employees | Sort-Object -Property YearsInMS
$results[0].FirstName | Should Be "Minus"
$results[0].LastName | Should Be "Two"
$results[0].YearsInMS | Should Be -2
$results[1].FirstName | Should Be "Eight"
$results[1].YearsInMS | Should BeNullOrEmpty
$results[2].FirstName | Should Be "One"
$results[2].LastName | Should Be "One"
$results[2].YearsInMS | Should Be 1
$results[3].FirstName | Should Be "Eight"
$results[3].LastName | Should Be "Eight"
$results[3].YearsInMS | Should Be 8
}
It "Sort-Object with Non Conflicting Order Entry Keys should work"{
$employee1 = [pscustomobject]@{"FirstName"="john"; "LastName"="smith"; "YearsInMS"=5}
$employee2 = [pscustomobject]@{"FirstName"="joesph"; "LastName"="smith"; "YearsInMS"=15}
$employee3 = [pscustomobject]@{"FirstName"="john"; "LastName"="smyth"; "YearsInMS"=2}
$employees = @($employee1,$employee2,$employee3)
$ht = @{"e"="YearsInMS"; "descending"=$false; "ascending"=$true}
$results = $employees | Sort-Object -Property $ht -Descending
$results[0] | Should Be $employees[2]
$results[1] | Should Be $employees[0]
$results[2] | Should Be $employees[1]
}
It "Sort-Object with Conflicting Order Entry Keys should work"{
$employee1 = [pscustomobject]@{"FirstName"="john"; "LastName"="smith"; "YearsInMS"=5}
$employee2 = [pscustomobject]@{"FirstName"="joesph"; "LastName"="smith"; "YearsInMS"=15}
$employee3 = [pscustomobject]@{"FirstName"="john"; "LastName"="smyth"; "YearsInMS"=2}
$employees = @($employee1,$employee2,$employee3)
$ht = @{"e"="YearsInMS"; "descending"=$false; "ascending"=$false}
$results = $employees | Sort-Object -Property $ht -Descending
$results[0] | Should Be $employees[1]
$results[1] | Should Be $employees[0]
$results[2] | Should Be $employees[2]
}
It "Sort-Object with One Order Entry Key should work"{
$employee1 = [pscustomobject]@{"FirstName"="john"; "LastName"="smith"; "YearsInMS"=5}
$employee2 = [pscustomobject]@{"FirstName"="joesph"; "LastName"="smith"; "YearsInMS"=15}
$employee3 = [pscustomobject]@{"FirstName"="john"; "LastName"="smyth"; "YearsInMS"=2}
$employees = @($employee1,$employee2,$employee3)
$ht = @{"e"="YearsInMS"; "descending"=$false}
$results = $employees | Sort-Object -Property $ht -Descending
$results[0] | Should Be $employees[2]
$results[1] | Should Be $employees[0]
$results[2] | Should Be $employees[1]
}
It "Sort-Object with HistoryInfo object should work"{
Add-Type -TypeDefinition "public enum PipelineState{NotStarted,Running,Stopping,Stopped,Completed,Failed,Disconnected}"
$historyInfo1 = [pscustomobject]@{"PipelineId"=1; "Cmdline"="cmd3"; "Status"=[PipelineState]::Completed; "StartTime" = [DateTime]::Now;"EndTime" = [DateTime]::Now.AddSeconds(5.0);}
$historyInfo2 = [pscustomobject]@{"PipelineId"=2; "Cmdline"="cmd1"; "Status"=[PipelineState]::Completed; "StartTime" = [DateTime]::Now;"EndTime" = [DateTime]::Now.AddSeconds(5.0);}
$historyInfo3 = [pscustomobject]@{"PipelineId"=3; "Cmdline"="cmd2"; "Status"=[PipelineState]::Completed; "StartTime" = [DateTime]::Now;"EndTime" = [DateTime]::Now.AddSeconds(5.0);}
$historyInfos = @($historyInfo1,$historyInfo2,$historyInfo3)
$results = $historyInfos | Sort-Object
$results[0] | Should Be $historyInfos[0]
$results[1] | Should Be $historyInfos[1]
$results[2] | Should Be $historyInfos[2]
}
It "Sort-Object with Non Existing And Null Script Property should work"{
$n = new-object microsoft.powershell.commands.newobjectcommand
$d = new-object microsoft.powershell.commands.newobjectcommand
$d.TypeName = 'Deetype'
$b = new-object microsoft.powershell.commands.newobjectcommand
$b.TypeName = 'btype'
$a = new-object microsoft.powershell.commands.newobjectcommand
$a.TypeName = 'atype'
$results = $n, $d, $b, 'b', $a | Sort-Object -proper {$_.TypeName}
$results.Count | Should Be 5
$results[2] | Should Be $a
$results[3] | Should Be $b
$results[4] | Should Be $d
#results[0] and [1] can be any order
}
It "Sort-Object with Non Existing And Null Property should work"{
$n = new-object microsoft.powershell.commands.newobjectcommand
$n.TypeName = $null
$d = new-object microsoft.powershell.commands.newobjectcommand
$d.TypeName = 'Deetype'
$b = new-object microsoft.powershell.commands.newobjectcommand
$b.TypeName = 'btype'
$a = new-object microsoft.powershell.commands.newobjectcommand
$a.TypeName = 'atype'
$results = $n, $d, $b, 'b', $a | Sort-Object -prop TypeName
$results.Count | Should Be 5
$results[0] | Should Be $n
$results[1] | Should Be $a
$results[2] | Should Be $b
$results[3] | Should Be $d
$results[4] | Should Be 'b'
}
It "Sort-Object with Non Case-Sensitive Unique should work"{
$employee1 = [pscustomobject]@{"FirstName"="john"; "LastName"="smith"; "YearsInMS"=5}
$employee2 = [pscustomobject]@{"FirstName"="joesph"; "LastName"="smith"; "YearsInMS"=15}
$employee3 = [pscustomobject]@{"FirstName"="john"; "LastName"="smyth"; "YearsInMS"=12}
$employees = @($employee1,$employee2,$employee3)
$results = $employees | Sort-Object -Property "LastName" -Descending -Unique
$results[0] | Should Be $employees[2]
$results[1] | Should Be $employees[1]
$results[2] | Should BeNullOrEmpty
}
It "Sort-Object with Case-Sensitive Unique should work"{
$employee1 = [pscustomobject]@{"FirstName"="john"; "LastName"="smith"; "YearsInMS"=5}
$employee2 = [pscustomobject]@{"FirstName"="joesph"; "LastName"="smith"; "YearsInMS"=15}
$employee3 = [pscustomobject]@{"FirstName"="john"; "LastName"="smyth"; "YearsInMS"=12}
$employees = @($employee1,$employee2,$employee3)
$results = $employees | Sort-Object -Property "LastName","FirstName" -Descending -Unique -CaseSensitive
$results[0] | Should Be $employees[2]
$results[1] | Should Be $employees[0]
$results[2] | Should Be $employees[1]
}
It "Sort-Object with Two Order Entry Keys should work"{
$employee1 = [pscustomobject]@{"FirstName"="john"; "LastName"="smith"; "YearsInMS"=5}
$employee2 = [pscustomobject]@{"FirstName"="joesph"; "LastName"="smith"; "YearsInMS"=15}
$employee3 = [pscustomobject]@{"FirstName"="john"; "LastName"="smyth"; "YearsInMS"=2}
$employees = @($employee1,$employee2,$employee3)
$ht1 = @{"expression"="LastName"; "ascending"=$false}
$ht2 = @{"expression"="FirstName"; "ascending"=$true}
$results = $employees | Sort-Object -Property @($ht1,$ht2) -Descending
$results[0] | Should Be $employees[2]
$results[1] | Should Be $employees[1]
$results[2] | Should Be $employees[0]
}
It "Sort-Object with -Descending:$false and Two Order Entry Keys should work"{
$employee1 = [pscustomobject]@{"FirstName"="john"; "LastName"="smith"; "YearsInMS"=5}
$employee2 = [pscustomobject]@{"FirstName"="joesph"; "LastName"="smith"; "YearsInMS"=15}
$employee3 = [pscustomobject]@{"FirstName"="john"; "LastName"="smyth"; "YearsInMS"=12}
$employees = @($employee1,$employee2,$employee3)
$results = $employees | Sort-Object -Property "LastName","FirstName" -Descending:$false
$results[0] | Should Be $employees[1]
$results[1] | Should Be $employees[0]
$results[2] | Should Be $employees[2]
}
It "Sort-Object with -Descending and Two Order Entry Keys should work"{
$employee1 = [pscustomobject]@{"FirstName"="john"; "LastName"="smith"; "YearsInMS"=5}
$employee2 = [pscustomobject]@{"FirstName"="joesph"; "LastName"="smith"; "YearsInMS"=15}
$employee3 = [pscustomobject]@{"FirstName"="john"; "LastName"="smyth"; "YearsInMS"=12}
$employees = @($employee1,$employee2,$employee3)
$results = $employees | Sort-Object -Property "LastName","FirstName" -Descending
$results[0] | Should Be $employees[2]
$results[1] | Should Be $employees[0]
$results[2] | Should Be $employees[1]
}
It "Sort-Object with Two Order Entry Keys with asc=true should work"{
$employee1 = [pscustomobject]@{"FirstName"="john"; "LastName"="smith"; "YearsInMS"=5}
$employee2 = [pscustomobject]@{"FirstName"="joesph"; "LastName"="smith"; "YearsInMS"=15}
$employee3 = [pscustomobject]@{"FirstName"="john"; "LastName"="smyth"; "YearsInMS"=12}
$employees = @($employee1,$employee2,$employee3)
$ht1 = @{"e"="FirstName"; "asc"=$true}
$ht2 = @{"e"="LastName";}
$results = $employees | Sort-Object -Property @($ht1,$ht2) -Descending
$results[0] | Should Be $employees[1]
$results[1] | Should Be $employees[2]
$results[2] | Should Be $employees[0]
}
It "Sort-Object with Descending No Property should work"{
$employee1 = 1
$employee2 = 2
$employee3 = 3
$employees = @($employee1,$employee2,$employee3)
$results = $employees | Sort-Object -Descending
$results[0] | Should Be 3
$results[1] | Should Be 2
$results[2] | Should Be 1
}
}
@@ -0,0 +1,28 @@
Describe "Start-Sleep DRT Unit Tests" -Tags DRT{
It "Should be works properly when sleeping with Second" {
$dtStart = [DateTime]::Now
Start-Sleep -Seconds 1
$dtEnd = [DateTime]::Now
$millseconds = (New-TimeSpan -Start $dtStart -End $dtEnd).TotalMilliseconds
$millseconds | Should BeGreaterThan 1000
}
It "Should be works properly when sleeping with Milliseconds" {
$dtStart = [DateTime]::Now
Start-Sleep -Milliseconds 1000
$dtEnd = [DateTime]::Now
$millseconds = (New-TimeSpan -Start $dtStart -End $dtEnd).TotalMilliseconds
$millseconds | Should BeGreaterThan 1000
}
}
Describe "Start-Sleep" {
Context "Validate Start-Sleep works properly" {
It "Should only sleep for at least 1 second" {
$result = Measure-Command { Start-Sleep -s 1 }
$result.TotalSeconds | Should BeGreaterThan 0.25
}
}
}
@@ -0,0 +1,48 @@
Describe "Tee-Object" {
Context "Validate Tee-Object is correctly forking output" {
$testfile = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath assets) -ChildPath testfile.txt
It "Should return the output to the screen and to the variable" {
$teefile = $testfile
echo teeobjecttest1 | Tee-Object -variable teeresults
$teeresults | Should Be "teeobjecttest1"
Remove-Item $teefile -ErrorAction SilentlyContinue
}
It "Should tee the output to a file" {
$teefile = $testfile
echo teeobjecttest3 | Tee-Object $teefile
Get-Content $teefile | Should Be "teeobjecttest3"
Remove-Item $teefile -ErrorAction SilentlyContinue
}
}
}
Describe "Tee-Object DRT Unit Tests" -Tags DRT {
BeforeAll {
$tempFile = Join-Path $TestDrive -ChildPath "TeeObjectTestsTempFile"
}
It "Positive File Test" {
$expected = "1", "2", "3"
$results = $expected | Tee-Object -FilePath $tempFile
$results.Length | Should be 3
$results | Should Be $expected
$content = Get-Content $tempFile
$content | Should Be $expected
}
It "Positive Variable Test" {
$expected = "1", "2", "3"
$varName = "teeObjectTestVar"
$results = $expected | Tee-Object -Variable $varName
$results.Length | Should be 3
$results | Should Be $expected
$results = Get-Variable -Name $varName -ValueOnly
$results.Length | Should be 3
$results | Should Be $expected
}
}
@@ -0,0 +1,18 @@
Function GetFileMock () {
$objs = @( [pscustomobject]@{ Size=4533816; Mode="-a---l"; LastWriteTime="9/1/2015 11:15 PM"; Name="explorer.exe" },
[pscustomobject]@{ Size=994816; Mode="-a---l"; LastWriteTime="9/1/2015 11:13 PM"; Name="HelpPane.exe" },
[pscustomobject]@{ Size=316640; Mode="-a---l"; LastWriteTime="9/1/2015 11:17 PM"; Name="WMSysPr9.prx" },
[pscustomobject]@{ Size=215040; Mode="-a---l"; LastWriteTime="9/1/2015 11:20 PM"; Name="notepad.exe" },
[pscustomobject]@{ Size=207239; Mode="-a----"; LastWriteTime="10/7/2015 2:37 PM"; Name="setupact.log" },
[pscustomobject]@{ Size=181064; Mode="-a----"; LastWriteTime="9/9/2015 11:54 PM"; Name="PSEXESVC.EXE" })
return $objs
}
filter addOneToSizeProperty() {
$_.Size += 1
$_
}
filter pipelineConsume() {
$_
}
@@ -0,0 +1,83 @@
# This came from monad/tests/ci/PowerShell/tests/Commands/Cmdlets/pester.utility.command.tests.ps1
Describe "Trace-Command" -tags "P1", "RI" {
Context "Listner options" {
BeforeAll {
$logFile = New-Item "TestDrive:/traceCommandLog.txt" -Force
$actualLogFile = New-Item "TestDrive:/actualTraceCommandLog.txt" -Force
}
AfterEach {
Remove-Item "TestDrive:/traceCommandLog.txt" -Force -ErrorAction SilentlyContinue
Remove-Item "TestDrive:/actualTraceCommandLog.txt" -Force -ErrorAction SilentlyContinue
}
# LogicalOperationStack is not in .NET Core
It "LogicalOperationStack works" -Skip:$IsCore {
$keyword = "Trace_Command_ListenerOption_LogicalOperationStack_Foo"
$stack = [System.Diagnostics.Trace]::CorrelationManager.LogicalOperationStack
$stack.Push($keyword)
Trace-Command -Name * -Expression {echo Foo} -ListenerOption LogicalOperationStack -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*LogicalOperationStack=$keyword*"}
$log.Count | Should BeGreaterThan 0
}
# GetStackTrace is not in .NET Core
It "Callstack works" -Skip:$IsCore {
Trace-Command -Name * -Expression {echo Foo} -ListenerOption Callstack -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*Callstack= * System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)*"}
$log.Count | Should BeGreaterThan 0
}
It "Datetime works" {
$expectedDate = Trace-Command -Name * -Expression {Get-Date} -ListenerOption DateTime -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*DateTime=*"}
$results = $log | ForEach-Object {[DateTime]::Parse($_.Split("=")[1])}
## allow a gap of 6 seconds. All traces should be finished within 6 seconds.
$allowedGap = [timespan](60 * 1000 * 1000)
$results | ForEach-Object {
$actualGap = $_ - $expectedDate;
if ($expectedDate -gt $_)
{
$actualGap = $expectedDate - $_;
}
$allowedGap | Should BeGreaterThan $actualGap
}
}
It "None options has no effect" {
Trace-Command -Name * -Expression {echo Foo} -ListenerOption None -FilePath $actualLogfile
Trace-Command -name * -Expression {echo Foo} -FilePath $logfile
Compare-Object (Get-Content $actualLogfile) (Get-Content $logfile) | Should BeNullOrEmpty
}
It "ThreadID works" {
Trace-Command -Name * -Expression {echo Foo} -ListenerOption ThreadId -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*ThreadID=*"}
$results = $log | ForEach-Object {$_.Split("=")[1]}
$results | % { $_ | Should Be ([threading.thread]::CurrentThread.ManagedThreadId) }
}
It "Timestamp creates logs in ascending order" {
Trace-Command -Name * -Expression {echo Foo} -ListenerOption Timestamp -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*Timestamp=*"}
$results = $log | ForEach-Object {$_.Split("=")[1]}
$sortedResults = $results | Sort-Object
$sortedResults | Should Be $results
}
It "ProcessId logs current process Id" {
Trace-Command -Name * -Expression {echo Foo} -ListenerOption ProcessId -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*ProcessID=*"}
$results = $log | ForEach-Object {$_.Split("=")[1]}
$results | ForEach-Object { $_ | Should Be $pid }
}
}
}
@@ -0,0 +1,59 @@
Describe "Update-FormatData" {
BeforeAll {
$path = Join-Path -Path $TestDrive -ChildPath "outputfile.ps1xml"
$ps = [powershell]::Create()
$iss = [system.management.automation.runspaces.initialsessionstate]::CreateDefault2()
$rs = [system.management.automation.runspaces.runspacefactory]::CreateRunspace($iss)
$rs.Open()
$ps.Runspace = $rs
}
AfterAll {
$rs.Close()
$ps.Dispose()
}
Context "Validate Update-FormatData update correctly" {
It "Should not throw upon reloading previous formatting file" {
{ Update-FormatData } | Should Not throw
}
It "Should validly load formatting data" {
Get-FormatData -typename System.Diagnostics.Process | Export-FormatData -Path $path
$null = $ps.AddScript("Update-FormatData -prependPath $path")
$ps.Invoke()
$ps.HadErrors | Should be $false
}
}
}
Describe "Update-FormatData basic functionality" -Tags DRT{
BeforeAll {
$testfilename = "testfile.ps1xml"
$testfile = Join-Path -Path $TestDrive -ChildPath $testfilename
$xmlContent=@"
<Types>
<Type>
<Name>AnyName</Name>
<Members>
<PropertySet>
<Name>PropertySetName</Name>
<ReferencedProperties>
<Name>FirstName</Name>
<Name>LastName</Name>
</ReferencedProperties>
</PropertySet>
</Members>
</Type>
</Types>
"@
$xmlContent > $testfile
}
It "Update-FormatData with WhatIf should work"{
{ Update-FormatData -Append $testfile -WhatIf } | Should Not Throw
{ Update-FormatData -Prepend $testfile -WhatIf } | Should Not Throw
}
}
@@ -0,0 +1,319 @@
Describe "Update-TypeData basic functionality" -Tags DRT{
BeforeAll {
$testfilename = "testfile.ps1xml"
$testfile = Join-Path -Path $TestDrive -ChildPath $testfilename
$invalidFileExtensionFile = Join-Path -Path $TestDrive -ChildPath "notmshxml"
$xmlContent=@"
<Types>
<Type>
<Name>AnyName</Name>
<MembersTypo>
<PropertySet>
<Name>PropertySetName</Name>
<ReferencedProperties>
<Name>FirstName</Name>
<Name>LastName</Name>
</ReferencedProperties>
</PropertySet>
</MembersTypo>
<MembersTypo2>
<PropertySet>
<Name>PropertySetName</Name>
<ReferencedProperties>
<Name>FirstName</Name>
<Name>LastName</Name>
</ReferencedProperties>
</PropertySet>
</MembersTypo2>
</Type>
</Types>
"@
$xmlContent>$testfile
}
BeforeEach {
$ps = [powershell]::Create()
$iss = [system.management.automation.runspaces.initialsessionstate]::CreateDefault2()
$rs = [system.management.automation.runspaces.runspacefactory]::CreateRunspace($iss)
$rs.Open()
$ps.Runspace = $rs
}
AfterEach {
$rs.Close()
$ps.Dispose()
}
It "Update-TypeData with Invalid TypesXml should throw Exception" {
$null = $ps.AddScript("Update-TypeData -PrependPath $testfile")
$ps.Invoke()
$ps.HadErrors | Should be $true
$ps.Streams.Error[0].FullyQualifiedErrorID | Should be "TypesXmlUpdateException,Microsoft.PowerShell.Commands.UpdateTypeDataCommand"
}
It "Update-TypeData with Invalid File Extension should throw Exception"{
$xmlContent="not really an xml file, but we will not use it"
$xmlContent>$invalidFileExtensionFile
$null = $ps.AddScript("Update-TypeData -PrependPath $invalidFileExtensionFile")
$ps.Invoke()
$ps.HadErrors | Should be $true
$ps.Streams.Error[0].FullyQualifiedErrorId | Should be "WrongExtension,Microsoft.PowerShell.Commands.UpdateTypeDataCommand"
}
It "Update-TypeData with Valid Dynamic Type NoteProperty with Force should work"{
$null = $ps.AddScript("Update-TypeData -MemberType NoteProperty -MemberName TestNote -Value 2 -TypeName System.String")
$ps.Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript("'string'.TestNote")
$ps.Invoke() | should be 2
$ps.Commands.Clear()
$null = $ps.AddScript("Update-TypeData -MemberType NoteProperty -MemberName TestNote -Value 'test' -TypeName System.String -Force")
$ps.Invoke()
$ps.commands.clear()
$null = $ps.AddScript("'string'.TestNote")
$ps.Invoke()| Should Be "test"
$ps.commands.clear()
$null = $ps.AddScript('Update-TypeData -MemberType NoteProperty -MemberName TestNote -Value $null -TypeName System.String -Force')
$ps.Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript("'string'.TestNote")
$ps.Invoke()| Should BeNullOrEmpty
}
It "Update-TypeData with Valid Dynamic Type AliasProperty with Force should work"{
# setup
$null = $ps.AddScript("Update-TypeData -MemberType AliasProperty -MemberName TestAlias -Value Length -TypeName System.String")
$ps.Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript("'string'.TestAlias.GetType().Name")
$ps.Invoke()| Should Be "Int32"
# test
$ps.Commands.Clear()
$null = $ps.AddScript("'string'.TestAlias")
$ps.Invoke()| Should Be 6
# setup
$ps.Commands.Clear()
$null = $ps.AddScript("Update-TypeData -MemberType AliasProperty -MemberName TestAlias -Value 'Length' -SecondValue 'string' -TypeName System.String -Force")
$ps.Invoke()
# test
$ps.Commands.Clear()
$null = $ps.AddScript("'string'.TestAlias.GetType().Name")
$ps.Invoke()| Should Be "String"
# test
$ps.Commands.Clear()
$null = $ps.AddScript("'string'.TestAlias")
$ps.Invoke()| Should Be 6
}
It "Update-TypeData with Valid Dynamic Type ScriptMethod with Force should work"{
$script1="script method"
$null = $ps.AddScript("Update-TypeData -MemberType ScriptMethod -MemberName TestScriptMethod -Value {'$script1'} -TypeName System.String")
$ps.Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript('"string".TestScriptMethod()')
$ps.Invoke()| Should Be "script method"
$ps.Commands.Clear()
$script2="new script method"
$null = $ps.AddScript("Update-TypeData -MemberType ScriptMethod -MemberName TestScriptMethod -Value {'$script2'} -TypeName System.String -Force")
$ps.Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript('"string".TestScriptMethod()')
$ps.Invoke() | Should Be "new script method"
}
It "Update-TypeData with Valid Dynamic Type Accept TypeData Object should work"{
$ps.Commands.AddScript('Add-Type -TypeDefinition "public class TypeDataTest{}"')
$ps.Commands.AddStatement()
$ps.Commands.AddScript('Update-TypeData -TypeName TypeDataTest -MemberType NoteProperty -MemberName TestNote1 -Value "Hello"')
$ps.Commands.AddStatement()
$ps.Commands.AddScript('Update-TypeData -MemberType NoteProperty -MemberName TestNote -Value 2 -TypeName TypeDataTest')
$ps.Commands.AddStatement()
$ps.Commands.AddScript('$result=new-object TypeDataTest')
$ps.Invoke()
# tests
$ps.Commands.Clear()
$ps.AddScript('$result.TestNote1').Invoke() | Should Be "Hello"
$ps.Commands.Clear()
$ps.AddScript('$result.TestNote').Invoke() | Should Be 2
}
It "Update-TypeData with Invalid DynamicType Null Value For AliasProperty should throw Exception"{
$null = $ps.AddScript('Update-TypeData -MemberType AliasProperty -MemberName TestAlias -Value $null -TypeName System.String')
$ps.Invoke()
$ps.HadErrors |Should be $true
$ps.Streams.Error[0].FullyQualifiedErrorId | Should be "ValueShouldBeSpecified,Microsoft.PowerShell.Commands.UpdateTypeDataCommand"
}
It "Update-TypeData with Invalid DynamicType with No MemberName should throw Exception"{
$null = $ps.AddScript('Update-TypeData -MemberType NoteProperty -Value "Error" -TypeName System.String')
$ps.Invoke()
$ps.HadErrors |Should be $true
$ps.Streams.Error[0].FullyQualifiedErrorId | Should be "MemberNameShouldBeSpecified,Microsoft.PowerShell.Commands.UpdateTypeDataCommand"
}
It "Update-TypeData with Invalid DynamicType with No Value should throw Exception"{
$null = $ps.AddScript('Update-TypeData -MemberType NoteProperty -MemberName TestNote -TypeName System.String')
$ps.Invoke()
$ps.HadErrors |Should be $true
$ps.Streams.Error[0].FullyQualifiedErrorId | Should be "ValueShouldBeSpecified,Microsoft.PowerShell.Commands.UpdateTypeDataCommand"
}
It "Update-TypeData with Invalid DynamicType with Empty TypeData should throw Exception"{
$null = $ps.AddScript("Update-TypeData -TypeName System.String")
$ps.Invoke()
$ps.HadErrors |Should be $true
$ps.Streams.Error[0].FullyQualifiedErrorId | Should be "TypeDataEmpty,Microsoft.PowerShell.Commands.UpdateTypeDataCommand"
}
It "Update-TypeData with Valid Standard Members Serialization Method String should work"{
$null = $ps.AddScript('Update-TypeData -SerializationMethod string -StringSerializationSource Length -TargetTypeForDeserialization string -TypeName System.String')
$ps.Invoke()
$ps.Commands.Clear(); $null = $ps.AddScript('"string".PSStandardMembers.SerializationMethod')
$ps.Invoke()| Should Be "String"
$ps.Commands.Clear(); $null = $ps.AddScript('"string".PSStandardMembers.StringSerializationSource')
$ps.Invoke()| Should Be 6
$ps.Commands.Clear(); $null = $ps.AddScript('"string".PSStandardMembers.TargetTypeForDeserialization')
$ps.Invoke()| Should Be "string"
}
It "Update-TypeData with Valid Standard Members Serialization Method SpecificProperties should work"{
$null = $ps.AddScript('Update-TypeData -SerializationMethod SpecificProperties -StringSerializationSource Length -PropertySerializationSet Length -InheritPropertySerializationSet $true -SerializationDepth 2 -TypeName System.String')
$ps.Invoke()
$ps.Commands.Clear();$null=$ps.AddScript('"string".PSStandardMembers.SerializationMethod')
$ps.Invoke() | Should Be "SpecificProperties"
$ps.Commands.Clear();$null=$ps.AddScript('"string".PSStandardMembers.StringSerializationSource')
$ps.Invoke() | Should Be 6
$ps.Commands.Clear();$null=$ps.AddScript('"string".PSStandardMembers.SerializationDepth')
$ps.Invoke() | Should Be 2
$ps.Commands.Clear();$null=$ps.AddScript('"string".PSStandardMembers.InheritPropertySerializationSet')
$ps.Invoke() | Should Be "True"
}
It "Update-TypeData with Valid Standard Members Serialization Method AllPublicProperties should work"{
$null = $ps.AddScript('Update-TypeData -SerializationMethod AllPublicProperties -StringSerializationSource Length -SerializationDepth 2 -TypeName System.String')
$ps.Invoke()
$ps.Commands.Clear();$ps.AddScript('"string".PSStandardMembers.SerializationMethod')
$ps.Invoke()| Should Be "AllPublicProperties"
$ps.Commands.Clear();$ps.AddScript('"string".PSStandardMembers.StringSerializationSource')
$ps.Invoke()| Should Be 6
$ps.Commands.Clear();$ps.AddScript('"string".PSStandardMembers.SerializationDepth')
$ps.Invoke()| Should Be 2
}
It "Update-TypeData with Valid ISS UpdateType Command Test With DynamicType Set should work"{
$ps.AddScript('Update-TypeData -MemberType NoteProperty -MemberName "TestNote" -Value "test the note" -SerializationMethod SpecificProperties -SerializationDepth 5 -PropertySerializationSet Length -DefaultDisplayPropertySet Length -TypeName System.String')
$ps.Invoke()
$ps.Commands.Clear();$null = $ps.AddScript('"string".TestNote')
$ps.Invoke()| Should Be "test the note"
$ps.Commands.Clear();$null = $ps.AddScript('"string".PSStandardMembers.SerializationMethod')
$ps.Invoke()| Should Be "SpecificProperties"
$ps.Commands.Clear();$null = $ps.AddScript('"string".PSStandardMembers.SerializationDepth')
$ps.Invoke()| Should Be 5
$ps.Commands.Clear();$null = $ps.AddScript('"string".PSStandardMembers.PropertySerializationSet.ReferencedPropertyNames[0]')
$ps.Invoke()| Should Be "Length"
$ps.Commands.Clear();$null = $ps.AddScript('"string".PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames[0]')
$ps.Invoke()| Should Be "Length"
$ps.Commands.Clear();$null = $ps.AddScript('Update-TypeData -MemberType NoteProperty -MemberName TestNote -Value "test the note again" -TargetTypeForDeserialization string -Force -TypeName System.String')
$ps.Invoke()
$ps.Commands.Clear();$null = $ps.AddScript('"string".TestNote')
$ps.Invoke()| Should Be "test the note again"
$ps.Commands.Clear();$null = $ps.AddScript('"string".PSStandardMembers.SerializationMethod')
$ps.Invoke()| Should Be "SpecificProperties"
$ps.Commands.Clear();$null = $ps.AddScript('"string".PSStandardMembers.SerializationDepth')
$ps.Invoke()| Should Be 5
$ps.Commands.Clear();$null = $ps.AddScript('"string".PSStandardMembers.PropertySerializationSet.ReferencedPropertyNames[0]')
$ps.Invoke()| Should Be "Length"
$ps.Commands.Clear();$null = $ps.AddScript('"string".PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames[0]')
$ps.Invoke()| Should Be "Length"
$ps.Commands.Clear();$null = $ps.AddScript('"string".PSStandardMembers.TargetTypeForDeserialization')
$ps.Invoke()| Should Be "string"
}
It "Update-TypeData with Valid ISS UpdateType Command Test With StrongType Set should work"{
$ps.AddScript('Update-TypeData -TypeName System.Array -MemberType NoteProperty -MemberName TestNote -Value "TestNote"')
$ps.Commands.AddStatement()
$ps.AddScript('Update-TypeData -TypeName System.Array -MemberType AliasProperty -MemberName TestAlias -Value "Length"')
$script1="script method"
$ps.Commands.AddStatement()
$ps.AddScript("Update-TypeData -TypeName System.Array -MemberType ScriptMethod -MemberName TestScriptMethod -Value {'$script1'}")
$script2='$this.Length'
$ps.Commands.AddStatement()
$ps.AddScript("Update-TypeData -TypeName System.Array -MemberType ScriptProperty -MemberName TestScriptProperty -Value {$script2}")
$ps.Commands.AddStatement()
$ps.AddScript('Update-TypeData -TypeName System.Array -SerializationMethod AllPublicProperties -SerializationDepth 2 -StringSerializationSource Length -TargetTypeForDeserialization string')
$ps.Invoke()
$ps.Commands.Clear();$ps.AddScript('(1, 3).TestNote').Invoke() | Should Be "TestNote"
$ps.Commands.Clear();$ps.AddScript('(1, 3).TestAlias').Invoke() | Should Be 2
$ps.Commands.Clear();$ps.AddScript('(1, 3).TestScriptMethod()').Invoke() | Should Be "script method"
$ps.Commands.Clear();$ps.AddScript('(1, 3).TestScriptProperty').Invoke() | Should Be 2
$ps.Commands.Clear();$ps.AddScript('(1, 3).PSStandardMembers.SerializationMethod').Invoke() | Should Be "AllPublicProperties"
$ps.Commands.Clear();$ps.AddScript('(1, 3).PSStandardMembers.SerializationDepth').Invoke() | Should Be 2
$ps.Commands.Clear();$ps.AddScript('(1, 3).PSStandardMembers.StringSerializationSource').Invoke() | Should Be 2
$ps.Commands.Clear();$ps.AddScript('(1, 3).PSStandardMembers.TargetTypeForDeserialization').Invoke() | Should Be "string"
}
# this looks identical to the test directly above
It "Update-TypeData with ISS Type Table API Test Add And Remove TypeData should work" -pending {
try{
Update-TypeData -TypeName System.Object[] -MemberType NoteProperty -MemberName TestNote -Value "TestNote"
Update-TypeData -TypeName System.Object[] -MemberType AliasProperty -MemberName TestAlias -Value "Length"
$script1={"script method"}
Update-TypeData -TypeName System.Object[] -MemberType ScriptMethod -MemberName TestScriptMethod -Value $script1
$script2={$this.Length}
Update-TypeData -TypeName System.Object[] -MemberType ScriptProperty -MemberName TestScriptProperty -Value $script2
Update-TypeData -TypeName System.Object[] -SerializationMethod AllPublicProperties -SerializationDepth 2 -StringSerializationSource Length -TargetTypeForDeserialization string
(1, 3).TestNote | Should Be "TestNote"
(1, 3).TestAlias | Should Be 2
(1, 3).TestScriptMethod() | Should Be "script method"
(1, 3).TestScriptProperty | Should Be 2
(1, 3).PSStandardMembers.SerializationMethod | Should Be "AllPublicProperties"
(1, 3).PSStandardMembers.SerializationDepth | Should Be 2
(1, 3).PSStandardMembers.StringSerializationSource | Should Be 2
(1, 3).PSStandardMembers.TargetTypeForDeserialization | Should Be "string"
}
finally
{
Remove-TypeData System.Object[]
}
}
Context "Duplicate XML files" {
BeforeAll {
$xmlContent=@"
<Types>
<Type>
<Name>System.Array</Name>
<Members>
<AliasProperty>
<Name>Yada</Name>
<ReferencedMemberName>Length</ReferencedMemberName>
</AliasProperty>
</Members>
</Type>
</Types>
"@
$xmlContent>$testfile
}
It "Update-TypeData with Duplicate XML Files should work"{
$null = $ps.AddScript("Update-TypeData -AppendPath $testfile")
$ps.Invoke()
$ps.Commands.Clear()
$ps.AddScript('$a=1..3').Invoke()
$ps.Commands.Clear()
$ps.AddScript('$a.Yada').Invoke() | Should Be 3
$ps.AddScript("Remove-TypeData -Path $testfile").Invoke()
$ps.HadErrors|Should be $false
}
}
}
@@ -0,0 +1,15 @@
Describe "Wait-Event" {
Context "Validate Wait-Event is waiting for events" {
It "Should time out when it does not receive a FakeEvent" {
# Don't depend on Measure-Command
$stopwatch = [System.Diagnostics.Stopwatch]::startNew()
# Testing the the timeout, so wait for an event that will never be
# raised because it is fake
Wait-Event -Timeout 1 -SourceIdentifier "FakeEvent"
$stopwatch.Stop()
$stopwatch.ElapsedMilliseconds | Should BeGreaterThan 500
$stopwatch.ElapsedMilliseconds | Should BeLessThan 1500
}
}
}
@@ -0,0 +1,117 @@
Describe "Write-Error DRT Unit Tests" -Tags DRT{
It "Should be works with command: write-error myerrortext" {
$e = Write-Error myerrortext 2>&1
$e | Should Not BeNullOrEmpty
$e.GetType().Name | Should Be 'ErrorRecord'
#Exception verification
$e.Exception.GetType().Name | Should Be 'WriteErrorException'
$e.Exception.Message | Should Be 'myerrortext'
$e.Exception.Data.Count | Should Be 0
$e.Exception.InnerException | Should BeNullOrEmpty
#ErrorCategoryInfo verification
$e.CategoryInfo | Should Not BeNullOrEmpty
$e.CategoryInfo.Category | Should Be 'NotSpecified'
$e.CategoryInfo.Activity | Should Be 'Write-Error'
$e.CategoryInfo.Reason | Should Be 'WriteErrorException'
$e.CategoryInfo.TargetName | Should BeNullOrEmpty
$e.CategoryInfo.TargetType | Should BeNullOrEmpty
$e.CategoryInfo.GetMessage() | Should Be 'NotSpecified: (:) [Write-Error], WriteErrorException'
#ErrorDetails verification
$e.ErrorDetails | Should BeNullOrEmpty
#FullyQualifiedErrorId verification
$e.FullyQualifiedErrorId | Should Be 'Microsoft.PowerShell.Commands.WriteErrorException'
#InvocationInfo verification
$e.InvocationInfo | Should Not BeNullOrEmpty
$e.InvocationInfo.MyCommand.Name | Should BeNullOrEmpty
}
#Blocked by issue #846
It "Should be works with all parameters" -Pending {
$exception = New-Object -TypeName System.ArgumentNullException -ArgumentList paramname
$e = Write-Error -Message myerrortext -Exception $exception -ErrorId myerrorid -Category syntaxerror -TargetObject TargetObject -CategoryActivity myactivity -CategoryReason myreason -CategoryTargetName mytargetname -CategoryTargetType mytargettype -RecommendedAction myrecommendedaction 2>&1
$e | Should Not BeNullOrEmpty
$e.GetType().Name | Should Be 'ErrorRecord'
#Exception verification
$e.Exception | Should Not BeNullOrEmpty
$e.Exception.GetType().Name | Should Be 'ArgumentNullException'
$e.Exception.ParamName | Should Be 'paramname'
$e.Exception.Data.Count | Should Be 0
$e.Exception.InnerException | Should BeNullOrEmpty
#TargetObject verification
$e.TargetObject | Should Be 'TargetObject'
#FullyQualifiedErrorId verification
$e.FullyQualifiedErrorId | Should Be 'myerrorid'
#ErrorCategoryInfo verification
$e.CategoryInfo | Should Not BeNullOrEmpty
$e.CategoryInfo.Category | Should Be 'SyntaxError'
$e.CategoryInfo.Activity | Should Be 'myactivity'
$e.CategoryInfo.Reason | Should Be 'myreason'
$e.CategoryInfo.TargetName | Should Be 'mytargetname'
$e.CategoryInfo.TargetType | Should Be 'mytargettype'
$e.CategoryInfo.GetMessage() | Should Be 'SyntaxError: (mytargetname:mytargettype) [myactivity], myreason'
#ErrorDetails verification
$e.ErrorDetails | Should Not BeNullOrEmpty
$e.ErrorDetails.Message | Should Be 'myerrortext'
$e.ErrorDetails.RecommendedAction | Should Be 'myrecommendedaction'
#InvocationInfo verification
$e.InvocationInfo | Should Not BeNullOrEmpty
$e.InvocationInfo.MyCommand.Name | Should BeNullOrEmpty
}
#Blocked by issue #846
It "Should be works with all parameters" -Pending {
$e = write-error -Activity fooAct -Reason fooReason -TargetName fooTargetName -TargetType fooTargetType -Message fooMessage 2>&1
$e.CategoryInfo.Activity | Should Be 'fooAct'
$e.CategoryInfo.Reason | Should Be 'fooReason'
$e.CategoryInfo.TargetName | Should Be 'fooTargetName'
$e.CategoryInfo.TargetType | Should Be 'fooTargetType'
$e.CategoryInfo.GetMessage() | Should Be 'NotSpecified: (fooTargetName:fooTargetType) [fooAct], fooReason'
}
}
Describe "Write-Error" {
It "Should be able to throw" {
Write-Error "test throw" -ErrorAction SilentlyContinue | Should Throw
}
It "Should throw a non-terminating error" {
Write-Error "test throw" -ErrorAction SilentlyContinue
1 + 1 | Should Be 2
}
It "Should trip an exception using the exception switch" {
$var = 0
try
{
Write-Error -Exception -Message "test throw"
}
catch [System.Exception]
{
$var++
}
finally
{
$var | Should Be 1
}
}
It "Should output the error message to the `$error automatic variable" {
$theError = "Error: Too many input values."
write-error -message $theError -category InvalidArgument -ErrorAction SilentlyContinue
$error[0]| Should Be $theError
}
}
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more