update encoding on the test files - these are ascii

This commit is contained in:
James Truher
2016-08-02 12:05:24 -07:00
parent 7b836f99f5
commit dd0291be09
20 changed files with 4628 additions and 4669 deletions
@@ -1,64 +1,64 @@
Describe "History cmdlet test cases" -Tags "CI" {
It "Tests Invoke-History on a cmdlet that generates output on all streams" {
$streamSpammer = '
function StreamSpammer
{
[CmdletBinding()]
param()
Write-Debug "Debug"
Write-Error "Error"
Write-Information "Information"
Write-Progress "Progress"
Write-Verbose "Verbose"
Write-Warning "Warning"
"Output"
}
$informationPreference = "Continue"
$debugPreference = "Continue"
$verbosePreference = "Continue"
'
$invocationSettings = New-Object System.Management.Automation.PSInvocationSettings
$invocationSettings.AddToHistory = $true
$ps = [PowerShell]::Create()
$null = $ps.AddScript($streamSpammer).Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript("StreamSpammer");
$null = $ps.Invoke($null, $invocationSettings)
$ps.Commands.Clear()
$null = $ps.AddScript("Invoke-History -id 1")
$result = $ps.Invoke($null, $invocationSettings)
$outputCount = $(
$ps.Streams.Error;
$ps.Streams.Progress;
$ps.Streams.Verbose;
$ps.Streams.Debug;
$ps.Streams.Warning;
$ps.Streams.Information).Count
$ps.Dispose()
## Twice per stream - once for the original invocatgion, and once for the re-invocation
$outputCount | Should be 12
}
It "Tests Invoke-History on a private command" {
$invocationSettings = New-Object System.Management.Automation.PSInvocationSettings
$invocationSettings.AddToHistory = $true
$ps = [PowerShell]::Create()
$null = $ps.AddScript("(Get-Command Get-Process).Visibility = 'Private'").Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript("Get-Process -id $pid")
$null = $ps.Invoke($null, $invocationSettings)
$ps.Commands.Clear()
$null = $ps.AddScript("Invoke-History -id 1")
$result = $ps.Invoke($null, $invocationSettings)
$errorResult = $ps.Streams.Error[0].FullyQualifiedErrorId
$ps.Dispose()
$errorResult | Should be CommandNotFoundException
}
}
Describe "History cmdlet test cases" -Tags "CI" {
It "Tests Invoke-History on a cmdlet that generates output on all streams" {
$streamSpammer = '
function StreamSpammer
{
[CmdletBinding()]
param()
Write-Debug "Debug"
Write-Error "Error"
Write-Information "Information"
Write-Progress "Progress"
Write-Verbose "Verbose"
Write-Warning "Warning"
"Output"
}
$informationPreference = "Continue"
$debugPreference = "Continue"
$verbosePreference = "Continue"
'
$invocationSettings = New-Object System.Management.Automation.PSInvocationSettings
$invocationSettings.AddToHistory = $true
$ps = [PowerShell]::Create()
$null = $ps.AddScript($streamSpammer).Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript("StreamSpammer");
$null = $ps.Invoke($null, $invocationSettings)
$ps.Commands.Clear()
$null = $ps.AddScript("Invoke-History -id 1")
$result = $ps.Invoke($null, $invocationSettings)
$outputCount = $(
$ps.Streams.Error;
$ps.Streams.Progress;
$ps.Streams.Verbose;
$ps.Streams.Debug;
$ps.Streams.Warning;
$ps.Streams.Information).Count
$ps.Dispose()
## Twice per stream - once for the original invocatgion, and once for the re-invocation
$outputCount | Should be 12
}
It "Tests Invoke-History on a private command" {
$invocationSettings = New-Object System.Management.Automation.PSInvocationSettings
$invocationSettings.AddToHistory = $true
$ps = [PowerShell]::Create()
$null = $ps.AddScript("(Get-Command Get-Process).Visibility = 'Private'").Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript("Get-Process -id $pid")
$null = $ps.Invoke($null, $invocationSettings)
$ps.Commands.Clear()
$null = $ps.AddScript("Invoke-History -id 1")
$result = $ps.Invoke($null, $invocationSettings)
$errorResult = $ps.Streams.Error[0].FullyQualifiedErrorId
$ps.Dispose()
$errorResult | Should be CommandNotFoundException
}
}
@@ -1,52 +1,52 @@
##
## Copyright (c) Microsoft Corporation, 2015
##
Describe "Tests Get-Command with relative paths and wildcards" -Tag "CI" {
BeforeAll {
# Create temporary EXE command files
$file1 = Setup -f WildCardCommandA.exe -pass
$file2 = Setup -f WildCardCommand[B].exe -pass
#$null = New-Item -ItemType File -Path (Join-Path $TestDrive WildCardCommandA.exe) -ErrorAction Ignore
#$null = New-Item -ItemType File -Path (Join-Path $TestDRive WildCardCommand[B].exe) -ErrorAction Ignore
if ( $IsLinux -or $IsOSX ) {
/bin/chmod 777 "$file1"
/bin/chmod 777 "$file2"
}
}
It "Test wildcard with drive relative directory path" {
$pathName = Join-Path $TestDrive "WildCardCommandA*"
$driveOffset = $pathName.IndexOf(":")
$pathName = $pathName.Substring($driveOffset + 1)
$result = Get-Command -Name $pathName
$result | Should Not Be $null
$result.Name | Should Be WildCardCommandA.exe
}
It "Test wildcard with relative directory path" {
push-location $TestDrive
$result = Get-Command -Name .\WildCardCommandA*
pop-location
$result | Should Not Be $null
$result | Should Be WildCardCommandA.exe
}
It "Test with PowerShell wildcard and relative path" {
push-location $TestDrive
# This should use the wildcard to find WildCardCommandA.exe
$result = Get-Command -Name .\WildCardCommand[A].exe
$result | Should Not Be $null
$result | Should Be WildCardCommandA.exe
# This should find the file WildCardCommand[B].exe
$result = Get-Command -Name .\WildCardCommand[B].exe
$result | Should Not Be $null
$result | Should Be WildCardCommand[B].exe
Pop-Location
}
}
##
## Copyright (c) Microsoft Corporation, 2015
##
Describe "Tests Get-Command with relative paths and wildcards" -Tag "CI" {
BeforeAll {
# Create temporary EXE command files
$file1 = Setup -f WildCardCommandA.exe -pass
$file2 = Setup -f WildCardCommand[B].exe -pass
#$null = New-Item -ItemType File -Path (Join-Path $TestDrive WildCardCommandA.exe) -ErrorAction Ignore
#$null = New-Item -ItemType File -Path (Join-Path $TestDRive WildCardCommand[B].exe) -ErrorAction Ignore
if ( $IsLinux -or $IsOSX ) {
/bin/chmod 777 "$file1"
/bin/chmod 777 "$file2"
}
}
It "Test wildcard with drive relative directory path" {
$pathName = Join-Path $TestDrive "WildCardCommandA*"
$driveOffset = $pathName.IndexOf(":")
$pathName = $pathName.Substring($driveOffset + 1)
$result = Get-Command -Name $pathName
$result | Should Not Be $null
$result.Name | Should Be WildCardCommandA.exe
}
It "Test wildcard with relative directory path" {
push-location $TestDrive
$result = Get-Command -Name .\WildCardCommandA*
pop-location
$result | Should Not Be $null
$result | Should Be WildCardCommandA.exe
}
It "Test with PowerShell wildcard and relative path" {
push-location $TestDrive
# This should use the wildcard to find WildCardCommandA.exe
$result = Get-Command -Name .\WildCardCommand[A].exe
$result | Should Not Be $null
$result | Should Be WildCardCommandA.exe
# This should find the file WildCardCommand[B].exe
$result = Get-Command -Name .\WildCardCommand[B].exe
$result | Should Not Be $null
$result | Should Be WildCardCommand[B].exe
Pop-Location
}
}
File diff suppressed because it is too large Load Diff
@@ -1,26 +1,26 @@
# Tests related to TFS item 1370133 [PSUpgrade] Need -NoNewline parameter on Out-File, Add-Content and Set-Content
# Connect request https://connect.microsoft.com/PowerShell/feedback/details/524739/need-nonewline-parameter-on-out-file-add-content-and-set-content
Describe "Tests for -NoNewline parameter of Out-File, Add-Content and Set-Content" -tags "Feature" {
It "NoNewline parameter works on Out-File" {
$temp = New-TemporaryFile
1..5 | Out-File $temp.FullName -Encoding 'ASCII' -NoNewline
(Get-Content $temp -Encoding Byte).Count | Should Be 5
Remove-Item $temp -ErrorAction SilentlyContinue -Force
}
It "NoNewline parameter works on Set-Content" {
$temp = New-TemporaryFile
Set-Content -Path $temp.FullName -Value 'a','b','c' -Encoding 'ASCII' -NoNewline
(Get-Content $temp -Encoding Byte).Count | Should Be 3
Remove-Item $temp -ErrorAction SilentlyContinue -Force
}
It "NoNewline parameter works on Add-Content" {
$temp = New-TemporaryFile
1..9 | %{Add-Content -Path $temp.FullName -Value $_ -Encoding 'ASCII' -NoNewline}
(Get-Content $temp -Encoding Byte).Count | Should Be 9
Remove-Item $temp -ErrorAction SilentlyContinue -Force
}
}
# Tests related to TFS item 1370133 [PSUpgrade] Need -NoNewline parameter on Out-File, Add-Content and Set-Content
# Connect request https://connect.microsoft.com/PowerShell/feedback/details/524739/need-nonewline-parameter-on-out-file-add-content-and-set-content
Describe "Tests for -NoNewline parameter of Out-File, Add-Content and Set-Content" -tags "Feature" {
It "NoNewline parameter works on Out-File" {
$temp = New-TemporaryFile
1..5 | Out-File $temp.FullName -Encoding 'ASCII' -NoNewline
(Get-Content $temp -Encoding Byte).Count | Should Be 5
Remove-Item $temp -ErrorAction SilentlyContinue -Force
}
It "NoNewline parameter works on Set-Content" {
$temp = New-TemporaryFile
Set-Content -Path $temp.FullName -Value 'a','b','c' -Encoding 'ASCII' -NoNewline
(Get-Content $temp -Encoding Byte).Count | Should Be 3
Remove-Item $temp -ErrorAction SilentlyContinue -Force
}
It "NoNewline parameter works on Add-Content" {
$temp = New-TemporaryFile
1..9 | %{Add-Content -Path $temp.FullName -Value $_ -Encoding 'ASCII' -NoNewline}
(Get-Content $temp -Encoding Byte).Count | Should Be 9
Remove-Item $temp -ErrorAction SilentlyContinue -Force
}
}
@@ -1,221 +1,221 @@
# This is a Pester test suite to validate the Format-Hex cmdlet in the Microsoft.PowerShell.Utility module.
#
# Copyright (c) Microsoft Corporation, 2015
#
<#
Purpose:
Verify that Format-Hex display the Hexa decmial value for the input data.
Action:
Run Format-Fex.
Expected Result:
Hexa decimal equivalent of the input data is displayed.
#>
Describe "FormatHex" -tags "CI" {
BeforeAll {
Setup -d FormatHexDataDir
$inputText1 = 'Hello World'
$inputText2 = 'This is a bit more text'
$inputFile1 = setup -f "FormatHexDataDir/SourceFile-1.txt" -content $inputText1 -pass
$inputFile2 = setup -f "FormatHexDataDir/SourceFile-2.txt" -content $inputText2 -pass
}
# This test is to validate to pipeline support in Format-Hex cmdlet.
It "ValidatePipelineSupport" {
# InputObject Parameter set should get invoked and
# the input data should be treated as string.
$result = $inputText1 | Format-Hex
$result | Should Not Be $null
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate to pipeline support in Format-Hex cmdlet.
It "ValidateByteArrayInputSupport" {
# InputObject Parameter set should get invoked and
# the input data should be treated as byte[].
$inputBytes = [System.Text.Encoding]::ASCII.GetBytes($inputText1)
$result = Format-Hex -InputObject $inputBytes
$result | Should Not Be $null
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate to input given through Path paramter set in Format-Hex cmdlet.
It "ValidatePathParameterSet" {
$result = Format-Hex -Path $inputFile1
$result | Should Not Be $null
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate to Path paramter set is considered as default in Format-Hex cmdlet.
It "ValidatePathAsDefaultParameterSet" {
$result = Format-Hex $inputFile1
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate to input given through LiteralPath paramter set in Format-Hex cmdlet.
It "ValidateLiteralPathParameterSet" {
$result = Format-Hex -LiteralPath $inputFile1
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate to input given through pipeline. The input being piped from results of Get-hildItem
It "ValidateFileInfoPipelineInput" {
$result = Get-ChildItem $inputFile1 | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate Encoding formats functionality of Format-Hex cmdlet.
It "ValidateEncodingFormats" {
$result = Format-Hex -InputObject $inputText1 -Encoding ASCII
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate that integers can be piped to the format-hex
It "ValidateIntegerInput" {
$result = 1,2,3,4 | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
# whitespace sensitive
$actualResult | should be "00000000 01 02 03 04 .... "
}
# This test is to validate that integers can be piped to the format-hex
# and properly represented as characters in the string
It "ValidateIntegerInputThatPresentAsCharacters" {
$result = 65..68 | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
# whitespace sensitive
$actualResult | should be "00000000 41 42 43 44 ABCD "
}
# This test is to validate that integers can be piped to the format-hex
It "ValidateIntegerRawInput" {
$result = 1,2,3,4 | Format-Hex -Raw
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
# whitespace sensitive
$actualResult | should be "00000000 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 ................"
}
# handle int64
It "ValidateInteger64" {
$result = [int64]::MaxValue | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
# whitespace sensitive
$actualResult | Should Match "00000000 FF FF FF FF FF FF FF 7F ."
}
# handle bytes, int16, int32, and int64
It "Validate combined and reduced number formatting" {
$b = 65 # fits in a byte
$i16 = 32767 # fits in an int16
$i32 = 2147483647 # an int32
$i64 = 9223372036854775807 # an int64
$result = $b,$i16,$i32,$i64 | format-Hex
$result.GetType().Name | should be 'ByteCollection'
$actualResult = $result.ToString()
$actualResult | should Match "00000000 41 FF 7F FF FF FF 7F FF FF FF FF FF FF FF 7F A"
}
# handle bytes, int16, int32, and int64
It "Validate combined and with raw number formatting" {
$b = 65 # fits in a byte
$i16 = 32767 # fits in an int16
$i32 = 2147483647 # an int32
$i64 = 9223372036854775807 # an int64
# this will cause 2 lines to be emitted
$result = $b,$i16,$i32,$i64 | format-Hex -Raw
$result[0].GetType().Name | should be 'ByteCollection'
$result[1].GetType().Name | should be 'ByteCollection'
$result0 = $result[0].ToString()
$result0 | should match "00000000 41 00 00 00 FF 7F 00 00 FF FF FF 7F FF FF FF FF A"
$result1 = $result[1].ToString()
$result1 | should match "00000010 FF FF FF 7F .."
}
# This test is to validate that streamed text does not have buffer underrun problems
It "ValidateEachBufferHasCorrectContentForStreamingText" {
$result = "a" * 30 | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString() -split "`r`n"
$actualResult.Count | should be 2
$actualResult[0].ToString() | Should be "00000000 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 aaaaaaaaaaaaaaaa"
$actualResult[1].ToString() | Should be "00000010 61 61 61 61 61 61 61 61 61 61 61 61 61 61 aaaaaaaaaaaaaa "
}
# This test is to validate that files do not have buffer underrun problems
It "ValidateEachBufferHasCorrectContentForFiles" {
$result = Format-Hex -path $InputFile2
$result | Should Not BeNullOrEmpty
$result.Count | should be 2
$result[0].ToString() | Should be "00000000 54 68 69 73 20 69 73 20 61 20 62 69 74 20 6D 6F This is a bit mo"
if ( $IsCore ) {
$result[1].ToString() | Should be "00000010 72 65 20 74 65 78 74 re text "
}
}
# This test ensures that if we stream bytes from a file, the output is correct
It "ValidateStreamOfBytesFromFileHasProperOutput" {
$result = Get-Content $InputFile1 -Encoding Byte | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be "ByteCollection"
if ( $IsCore ) {
$result.ToString() | Should be "00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 Hello World "
}
}
# This test is to validate the alias for Format-Hex cmdlet.
It "ValidateCmdletAlias" {
try
{
$result = Get-Command fhx -ErrorAction Stop
$result | Should Not BeNullOrEmpty
$result.CommandType.ToString() | Should Be "Alias"
}
catch
{
$_ | Should BeNullOrEmpty
}
}
}
# This is a Pester test suite to validate the Format-Hex cmdlet in the Microsoft.PowerShell.Utility module.
#
# Copyright (c) Microsoft Corporation, 2015
#
<#
Purpose:
Verify that Format-Hex display the Hexa decmial value for the input data.
Action:
Run Format-Fex.
Expected Result:
Hexa decimal equivalent of the input data is displayed.
#>
Describe "FormatHex" -tags "CI" {
BeforeAll {
Setup -d FormatHexDataDir
$inputText1 = 'Hello World'
$inputText2 = 'This is a bit more text'
$inputFile1 = setup -f "FormatHexDataDir/SourceFile-1.txt" -content $inputText1 -pass
$inputFile2 = setup -f "FormatHexDataDir/SourceFile-2.txt" -content $inputText2 -pass
}
# This test is to validate to pipeline support in Format-Hex cmdlet.
It "ValidatePipelineSupport" {
# InputObject Parameter set should get invoked and
# the input data should be treated as string.
$result = $inputText1 | Format-Hex
$result | Should Not Be $null
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate to pipeline support in Format-Hex cmdlet.
It "ValidateByteArrayInputSupport" {
# InputObject Parameter set should get invoked and
# the input data should be treated as byte[].
$inputBytes = [System.Text.Encoding]::ASCII.GetBytes($inputText1)
$result = Format-Hex -InputObject $inputBytes
$result | Should Not Be $null
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate to input given through Path paramter set in Format-Hex cmdlet.
It "ValidatePathParameterSet" {
$result = Format-Hex -Path $inputFile1
$result | Should Not Be $null
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate to Path paramter set is considered as default in Format-Hex cmdlet.
It "ValidatePathAsDefaultParameterSet" {
$result = Format-Hex $inputFile1
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate to input given through LiteralPath paramter set in Format-Hex cmdlet.
It "ValidateLiteralPathParameterSet" {
$result = Format-Hex -LiteralPath $inputFile1
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate to input given through pipeline. The input being piped from results of Get-hildItem
It "ValidateFileInfoPipelineInput" {
$result = Get-ChildItem $inputFile1 | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate Encoding formats functionality of Format-Hex cmdlet.
It "ValidateEncodingFormats" {
$result = Format-Hex -InputObject $inputText1 -Encoding ASCII
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
($actualResult -match $inputText1) | Should Be $true
}
# This test is to validate that integers can be piped to the format-hex
It "ValidateIntegerInput" {
$result = 1,2,3,4 | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
# whitespace sensitive
$actualResult | should be "00000000 01 02 03 04 .... "
}
# This test is to validate that integers can be piped to the format-hex
# and properly represented as characters in the string
It "ValidateIntegerInputThatPresentAsCharacters" {
$result = 65..68 | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
# whitespace sensitive
$actualResult | should be "00000000 41 42 43 44 ABCD "
}
# This test is to validate that integers can be piped to the format-hex
It "ValidateIntegerRawInput" {
$result = 1,2,3,4 | Format-Hex -Raw
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
# whitespace sensitive
$actualResult | should be "00000000 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 ................"
}
# handle int64
It "ValidateInteger64" {
$result = [int64]::MaxValue | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString()
# whitespace sensitive
$actualResult | Should Match "00000000 FF FF FF FF FF FF FF 7F ."
}
# handle bytes, int16, int32, and int64
It "Validate combined and reduced number formatting" {
$b = 65 # fits in a byte
$i16 = 32767 # fits in an int16
$i32 = 2147483647 # an int32
$i64 = 9223372036854775807 # an int64
$result = $b,$i16,$i32,$i64 | format-Hex
$result.GetType().Name | should be 'ByteCollection'
$actualResult = $result.ToString()
$actualResult | should Match "00000000 41 FF 7F FF FF FF 7F FF FF FF FF FF FF FF 7F A"
}
# handle bytes, int16, int32, and int64
It "Validate combined and with raw number formatting" {
$b = 65 # fits in a byte
$i16 = 32767 # fits in an int16
$i32 = 2147483647 # an int32
$i64 = 9223372036854775807 # an int64
# this will cause 2 lines to be emitted
$result = $b,$i16,$i32,$i64 | format-Hex -Raw
$result[0].GetType().Name | should be 'ByteCollection'
$result[1].GetType().Name | should be 'ByteCollection'
$result0 = $result[0].ToString()
$result0 | should match "00000000 41 00 00 00 FF 7F 00 00 FF FF FF 7F FF FF FF FF A"
$result1 = $result[1].ToString()
$result1 | should match "00000010 FF FF FF 7F .."
}
# This test is to validate that streamed text does not have buffer underrun problems
It "ValidateEachBufferHasCorrectContentForStreamingText" {
$result = "a" * 30 | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be 'ByteCollection'
$actualResult = $result.ToString() -split "`r`n"
$actualResult.Count | should be 2
$actualResult[0].ToString() | Should be "00000000 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 aaaaaaaaaaaaaaaa"
$actualResult[1].ToString() | Should be "00000010 61 61 61 61 61 61 61 61 61 61 61 61 61 61 aaaaaaaaaaaaaa "
}
# This test is to validate that files do not have buffer underrun problems
It "ValidateEachBufferHasCorrectContentForFiles" {
$result = Format-Hex -path $InputFile2
$result | Should Not BeNullOrEmpty
$result.Count | should be 2
$result[0].ToString() | Should be "00000000 54 68 69 73 20 69 73 20 61 20 62 69 74 20 6D 6F This is a bit mo"
if ( $IsCore ) {
$result[1].ToString() | Should be "00000010 72 65 20 74 65 78 74 re text "
}
}
# This test ensures that if we stream bytes from a file, the output is correct
It "ValidateStreamOfBytesFromFileHasProperOutput" {
$result = Get-Content $InputFile1 -Encoding Byte | Format-Hex
$result | Should Not BeNullOrEmpty
$result.GetType().Name | Should Be "ByteCollection"
if ( $IsCore ) {
$result.ToString() | Should be "00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 Hello World "
}
}
# This test is to validate the alias for Format-Hex cmdlet.
It "ValidateCmdletAlias" {
try
{
$result = Get-Command fhx -ErrorAction Stop
$result | Should Not BeNullOrEmpty
$result.CommandType.ToString() | Should Be "Alias"
}
catch
{
$_ | Should BeNullOrEmpty
}
}
}
@@ -1,84 +1,84 @@
Describe "Using delimiters with Export-CSV and Import-CSV behave correctly" -tags "Feature" {
BeforeAll {
# note, we will not use "," as that's the default for CSV
$delimiters = "/", " ", "@", "#", "$", "\", "&", "(", ")",
"{", "}", "|", "<", ">", ";", "'",
'"', "~", "!", "%", "^", "*", "_", "+", ":",
"?", "-", "=", "[", "]", "."
$defaultDelimiter = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ListSeparator
# With CORECLR the CurrentCulture.TextInfo.ListSeparator is not writable, so
# we need to use an entirely new CultureInfo which we can modify
$enCulture = [System.Globalization.CultureInfo]::new("en-us")
$d = get-date
$testCases = @(
foreach($del in $delimiters)
{
@{ Delimiter = $del; Data = $d; ExpectedResult = $d.Ticks }
}
)
function Set-delimiter {
param ( $delimiter )
if ( $IsCore ) {
$enCulture.TextInfo.ListSeparator = $delimiter
[System.Globalization.CultureInfo]::CurrentCulture = $enCulture
}
else {
[System.Globalization.cultureInfo]::CurrentCulture.TextInfo.ListSeparator = $delimiter
}
}
}
AfterEach {
if ( $IsCore ) {
$enCulture.TextInfo.ListSeparator = $defaultDelimiter
[System.Globalization.CultureInfo]::CurrentCulture = $enCulture
}
else {
[System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ListSeparator = $defaultDelimiter
}
remove-item -force -ea silentlycontinue TESTDRIVE:/file.csv
}
It "Disallow use of null delimiter" {
$d | export-csv TESTDRIVE:/file.csv
{ import-csv -path TESTDRIVE:/file.csv -delimiter $null } | Should Throw "Delimiter"
}
It "Disallow use of delimiter with useCulture parameter" {
$d | export-csv TESTDRIVE:/file.csv
{ import-csv -path TESTDRIVE:/file.csv -useCulture "," } | Should Throw "','"
}
It "Imports the same properties as exported" {
$a = [pscustomobject]@{ a = 1; b = 2; c = 3 }
$a | export-Csv TESTDRIVE:/file.csv
$b = import-csv TESTDRIVE:/file.csv
@($b.psobject.properties).count | should be 3
$b.a | Should be $a.a
$b.b | Should be $a.b
$b.c | Should be $a.c
}
# parameter generated tests
It 'Delimiter <Delimiter> with CSV import will fail correctly when culture does not match' -testCases $testCases {
param ($delimiter, $Data, $ExpectedResult)
set-Delimiter $delimiter
$Data | export-CSV TESTDRIVE:\File.csv -useCulture
$i = Import-CSV TESTDRIVE:\File.csv
$i.Ticks | Should Not Be $ExpectedResult
}
It 'Delimiter <Delimiter> with CSV import will succeed when culture matches export' -testCases $testCases {
param ($delimiter, $Data, $ExpectedResult)
set-Delimiter $delimiter
$Data | export-CSV TESTDRIVE:\File.csv -useCulture
$i = Import-CSV TESTDRIVE:\File.csv -useCulture
$i.Ticks | Should Be $ExpectedResult
}
It 'Delimiter <Delimiter> with CSV import will succeed when delimiter is used explicitly' -testCases $testCases {
param ($delimiter, $Data, $ExpectedResult)
$Data | export-CSV TESTDRIVE:\File.csv -delimiter $delimiter
$i = Import-CSV TESTDRIVE:\File.csv -delimiter $delimiter
$i.Ticks | Should Be $ExpectedResult
}
}
Describe "Using delimiters with Export-CSV and Import-CSV behave correctly" -tags "Feature" {
BeforeAll {
# note, we will not use "," as that's the default for CSV
$delimiters = "/", " ", "@", "#", "$", "\", "&", "(", ")",
"{", "}", "|", "<", ">", ";", "'",
'"', "~", "!", "%", "^", "*", "_", "+", ":",
"?", "-", "=", "[", "]", "."
$defaultDelimiter = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ListSeparator
# With CORECLR the CurrentCulture.TextInfo.ListSeparator is not writable, so
# we need to use an entirely new CultureInfo which we can modify
$enCulture = [System.Globalization.CultureInfo]::new("en-us")
$d = get-date
$testCases = @(
foreach($del in $delimiters)
{
@{ Delimiter = $del; Data = $d; ExpectedResult = $d.Ticks }
}
)
function Set-delimiter {
param ( $delimiter )
if ( $IsCore ) {
$enCulture.TextInfo.ListSeparator = $delimiter
[System.Globalization.CultureInfo]::CurrentCulture = $enCulture
}
else {
[System.Globalization.cultureInfo]::CurrentCulture.TextInfo.ListSeparator = $delimiter
}
}
}
AfterEach {
if ( $IsCore ) {
$enCulture.TextInfo.ListSeparator = $defaultDelimiter
[System.Globalization.CultureInfo]::CurrentCulture = $enCulture
}
else {
[System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ListSeparator = $defaultDelimiter
}
remove-item -force -ea silentlycontinue TESTDRIVE:/file.csv
}
It "Disallow use of null delimiter" {
$d | export-csv TESTDRIVE:/file.csv
{ import-csv -path TESTDRIVE:/file.csv -delimiter $null } | Should Throw "Delimiter"
}
It "Disallow use of delimiter with useCulture parameter" {
$d | export-csv TESTDRIVE:/file.csv
{ import-csv -path TESTDRIVE:/file.csv -useCulture "," } | Should Throw "','"
}
It "Imports the same properties as exported" {
$a = [pscustomobject]@{ a = 1; b = 2; c = 3 }
$a | export-Csv TESTDRIVE:/file.csv
$b = import-csv TESTDRIVE:/file.csv
@($b.psobject.properties).count | should be 3
$b.a | Should be $a.a
$b.b | Should be $a.b
$b.c | Should be $a.c
}
# parameter generated tests
It 'Delimiter <Delimiter> with CSV import will fail correctly when culture does not match' -testCases $testCases {
param ($delimiter, $Data, $ExpectedResult)
set-Delimiter $delimiter
$Data | export-CSV TESTDRIVE:\File.csv -useCulture
$i = Import-CSV TESTDRIVE:\File.csv
$i.Ticks | Should Not Be $ExpectedResult
}
It 'Delimiter <Delimiter> with CSV import will succeed when culture matches export' -testCases $testCases {
param ($delimiter, $Data, $ExpectedResult)
set-Delimiter $delimiter
$Data | export-CSV TESTDRIVE:\File.csv -useCulture
$i = Import-CSV TESTDRIVE:\File.csv -useCulture
$i.Ticks | Should Be $ExpectedResult
}
It 'Delimiter <Delimiter> with CSV import will succeed when delimiter is used explicitly' -testCases $testCases {
param ($delimiter, $Data, $ExpectedResult)
$Data | export-CSV TESTDRIVE:\File.csv -delimiter $delimiter
$i = Import-CSV TESTDRIVE:\File.csv -delimiter $delimiter
$i.Ticks | Should Be $ExpectedResult
}
}
@@ -1,54 +1,54 @@
Describe "GetDateFormatUpdates" -Tags "Feature" {
It "Verifies that FileDate format works" {
$date = Get-Date
$expectedFormat = "{0:yyyyMMdd}" -f $date
$actualFormat = Get-Date -Date $date -Format FileDate
$actualFormat | Should be $expectedFormat
}
It "Verifies that FileDateUniversal format works" {
$date = (Get-Date).ToUniversalTime()
$expectedFormat = "{0:yyyyMMddZ}" -f $date
$actualFormat = Get-Date -Date $date -Format FileDateUniversal
$actualFormat | Should be $expectedFormat
}
It "Verifies that FileDateTime format works" {
$date = Get-Date
$expectedFormat = "{0:yyyyMMddTHHmmssffff}" -f $date
$actualFormat = Get-Date -Date $date -Format FileDateTime
$actualFormat | Should be $expectedFormat
}
It "Verifies that FileDateTimeUniversal format works" {
$date = (Get-Date).ToUniversalTime()
$expectedFormat = "{0:yyyyMMddTHHmmssffffZ}" -f $date
$actualFormat = Get-Date -Date $date -Format FileDateTimeUniversal
$actualFormat | Should be $expectedFormat
}
}
Describe "GetRandomMiscTests" -Tags "Feature" {
It "Shouldn't overflow when using max range" {
$hadError = $false
try
{
## Don't actually need to validate
Get-Random -Minimum ([Int32]::MinValue) -Maximum ([Int32]::MaxValue) -ErrorAction Stop
}
catch
{
$hadError = $true
}
$hadError | Should be $false
}
}
Describe "GetDateFormatUpdates" -Tags "Feature" {
It "Verifies that FileDate format works" {
$date = Get-Date
$expectedFormat = "{0:yyyyMMdd}" -f $date
$actualFormat = Get-Date -Date $date -Format FileDate
$actualFormat | Should be $expectedFormat
}
It "Verifies that FileDateUniversal format works" {
$date = (Get-Date).ToUniversalTime()
$expectedFormat = "{0:yyyyMMddZ}" -f $date
$actualFormat = Get-Date -Date $date -Format FileDateUniversal
$actualFormat | Should be $expectedFormat
}
It "Verifies that FileDateTime format works" {
$date = Get-Date
$expectedFormat = "{0:yyyyMMddTHHmmssffff}" -f $date
$actualFormat = Get-Date -Date $date -Format FileDateTime
$actualFormat | Should be $expectedFormat
}
It "Verifies that FileDateTimeUniversal format works" {
$date = (Get-Date).ToUniversalTime()
$expectedFormat = "{0:yyyyMMddTHHmmssffffZ}" -f $date
$actualFormat = Get-Date -Date $date -Format FileDateTimeUniversal
$actualFormat | Should be $expectedFormat
}
}
Describe "GetRandomMiscTests" -Tags "Feature" {
It "Shouldn't overflow when using max range" {
$hadError = $false
try
{
## Don't actually need to validate
Get-Random -Minimum ([Int32]::MinValue) -Maximum ([Int32]::MaxValue) -ErrorAction Stop
}
catch
{
$hadError = $true
}
$hadError | Should be $false
}
}
@@ -1,19 +1,19 @@
Describe "New-Guid" -Tags "CI" {
It "returns a new guid" {
$guid = New-Guid
$guid.GetType().FullName | Should Be "System.Guid"
}
It "should not be all zeros" {
$guid = New-Guid
$guid.ToString() | Should Not Be "00000000-0000-0000-0000-000000000000"
}
It "should return different guids with each call" {
$guid1 = New-Guid
$guid2 = New-Guid
$guid1.ToString() | Should Not Be $guid2.ToString()
}
}
Describe "New-Guid" -Tags "CI" {
It "returns a new guid" {
$guid = New-Guid
$guid.GetType().FullName | Should Be "System.Guid"
}
It "should not be all zeros" {
$guid = New-Guid
$guid.ToString() | Should Not Be "00000000-0000-0000-0000-000000000000"
}
It "should return different guids with each call" {
$guid1 = New-Guid
$guid2 = New-Guid
$guid1.ToString() | Should Not Be $guid2.ToString()
}
}
@@ -1,38 +1,38 @@
# This is a Pester test suite to validate the New-TemporaryFile cmdlet in the Microsoft.PowerShell.Utility module.
#
# Copyright (c) Microsoft Corporation, 2015
#
<#
Purpose:
Verify that New-TemporaryFile creates a temporary file.
Action:
Run New-TemporaryFile.
Expected Result:
A FileInfo object for the temporary file is returned.
#>
Describe "NewTemporaryFile" -Tags "CI" {
It "creates a new temporary file" {
$tempFile = New-TemporaryFile
Test-Path $tempFile | Should be $true
$tempFile.GetType().Name | Should be "FileInfo"
if(Test-Path $tempFile)
{
Remove-Item $tempFile -ErrorAction SilentlyContinue -Force
}
}
It "with WhatIf does not create a file" {
New-TemporaryFile -WhatIf | Should Be $null
}
It "has an OutputType of System.IO.FileInfo" {
(Get-Command New-TemporaryFile).OutputType | Should Be "System.IO.FileInfo"
}
}
# This is a Pester test suite to validate the New-TemporaryFile cmdlet in the Microsoft.PowerShell.Utility module.
#
# Copyright (c) Microsoft Corporation, 2015
#
<#
Purpose:
Verify that New-TemporaryFile creates a temporary file.
Action:
Run New-TemporaryFile.
Expected Result:
A FileInfo object for the temporary file is returned.
#>
Describe "NewTemporaryFile" -Tags "CI" {
It "creates a new temporary file" {
$tempFile = New-TemporaryFile
Test-Path $tempFile | Should be $true
$tempFile.GetType().Name | Should be "FileInfo"
if(Test-Path $tempFile)
{
Remove-Item $tempFile -ErrorAction SilentlyContinue -Force
}
}
It "with WhatIf does not create a file" {
New-TemporaryFile -WhatIf | Should Be $null
}
It "has an OutputType of System.IO.FileInfo" {
(Get-Command New-TemporaryFile).OutputType | Should Be "System.IO.FileInfo"
}
}
@@ -1,86 +1,86 @@
Describe "Tests for the Import-PowerShellDataFile cmdlet" -Tags "Feature" {
It "Validates error on a missing path" {
$foundError = ""
try
{
Import-PowerShellDataFile -Path /SomeMissingDirectory -ErrorAction Stop
}
catch
{
$foundError = $_.FullyQualifiedErrorId
}
$foundError | Should be "PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand"
}
It "Validates error on a directory" {
$foundError = ""
try
{
Import-PowerShellDataFile ${TESTDRIVE} -ErrorAction Stop
}
catch
{
$foundError = $_.FullyQualifiedErrorId
}
$foundError | Should be "CouldNotParseAsPowerShellDataFile,Import-PowerShellDataFile"
}
It "Generates a good error on an insecure file" {
$path = New-TemporaryFile
Set-Content $path '@{ Foo = Get-Process }'
$foundError = ""
try
{
Import-PowerShellDataFile $path -ErrorAction Stop
}
catch
{
$foundError = $_.FullyQualifiedErrorId
}
finally
{
Remove-Item $path
}
$foundError | Should be "InvalidOperationException,Import-PowerShellDataFile"
}
It "Generates a good error on a file that isn't a PowerShell Data File (missing the hashtable root)" {
$path = New-TemporaryFile
Set-Content $path '"Hello World"'
$foundError = ""
try
{
Import-PowerShellDataFile $path -ErrorAction Stop
}
catch
{
$foundError = $_.FullyQualifiedErrorId
}
finally
{
Remove-Item $path
}
$foundError | Should be "CouldNotParseAsPowerShellDataFileNoHashtableRoot,Import-PowerShellDataFile"
}
It "Can parse a PowerShell Data File (detailed tests are in AST.SafeGetValue tests)" {
$path = New-TemporaryFile
Set-Content $path '@{ "Hello" = "World" }'
$result = Import-PowerShellDataFile $path -ErrorAction Stop
$result.Hello | Should be "World"
}
}
Describe "Tests for the Import-PowerShellDataFile cmdlet" -Tags "Feature" {
It "Validates error on a missing path" {
$foundError = ""
try
{
Import-PowerShellDataFile -Path /SomeMissingDirectory -ErrorAction Stop
}
catch
{
$foundError = $_.FullyQualifiedErrorId
}
$foundError | Should be "PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand"
}
It "Validates error on a directory" {
$foundError = ""
try
{
Import-PowerShellDataFile ${TESTDRIVE} -ErrorAction Stop
}
catch
{
$foundError = $_.FullyQualifiedErrorId
}
$foundError | Should be "CouldNotParseAsPowerShellDataFile,Import-PowerShellDataFile"
}
It "Generates a good error on an insecure file" {
$path = New-TemporaryFile
Set-Content $path '@{ Foo = Get-Process }'
$foundError = ""
try
{
Import-PowerShellDataFile $path -ErrorAction Stop
}
catch
{
$foundError = $_.FullyQualifiedErrorId
}
finally
{
Remove-Item $path
}
$foundError | Should be "InvalidOperationException,Import-PowerShellDataFile"
}
It "Generates a good error on a file that isn't a PowerShell Data File (missing the hashtable root)" {
$path = New-TemporaryFile
Set-Content $path '"Hello World"'
$foundError = ""
try
{
Import-PowerShellDataFile $path -ErrorAction Stop
}
catch
{
$foundError = $_.FullyQualifiedErrorId
}
finally
{
Remove-Item $path
}
$foundError | Should be "CouldNotParseAsPowerShellDataFileNoHashtableRoot,Import-PowerShellDataFile"
}
It "Can parse a PowerShell Data File (detailed tests are in AST.SafeGetValue tests)" {
$path = New-TemporaryFile
Set-Content $path '@{ "Hello" = "World" }'
$result = Import-PowerShellDataFile $path -ErrorAction Stop
$result.Hello | Should be "World"
}
}
@@ -1,160 +1,160 @@
Describe "Alias tests" -Tags "CI" {
BeforeAll {
$testPath = Join-Path testdrive:\ ("testAlias\[.test")
New-Item -ItemType Directory -Path $testPath -Force | Out-Null
class TestData
{
[string] $testName
[string] $testFile
[string] $expectedError
TestData($name, $file, $error)
{
$this.testName = $name
$this.testFile = $file
$this.expectedError = $error
}
}
}
Context "Export-Alias literal path" {
BeforeAll {
$csvFile = Join-Path $testPath "alias.csv"
$ps1File = Join-Path $testPath "alias.ps1"
$testCases = @()
$testCases += [TestData]::new("CSV", $csvFile, [NullString]::Value)
$testCases += [TestData]::new("PS1", $ps1File, [NullString]::Value)
$testCases += [TestData]::new("Empty string", "", "ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ExportAliasCommand")
$testCases += [TestData]::new("Null", [NullString]::Value, "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportAliasCommand")
$testCases += [TestData]::new("Non filesystem provider", 'cert:\alias.ps1', "ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportAliasCommand")
}
$testCases | % {
It "for $($_.testName)" {
$test = $_
try
{
Export-Alias -LiteralPath $test.testFile -ErrorAction SilentlyContinue
}
catch
{
$exportAliasError = $_
}
if($test.expectedError -eq $null)
{
Test-Path -LiteralPath $test.testFile | Should Be $true
}
else
{
$exportAliasError.FullyqualifiedErrorId | Should Be $test.expectedError
}
}
AfterEach {
Remove-Item -LiteralPath $test.testFile -Force -ErrorAction SilentlyContinue
}
}
It "when file exists with NoClobber" {
Export-Alias -LiteralPath $csvFile
try
{
Export-Alias -LiteralPath $csvFile -NoClobber
}
catch
{
$exportAliasError = $_
}
$exportAliasError.FullyQualifiedErrorId | Should Be "NoClobber,Microsoft.PowerShell.Commands.ExportAliasCommand"
}
}
Context "Export-All inside a literal path" {
BeforeEach {
Push-Location -LiteralPath $testPath
}
It "with a CSV file" {
Export-Alias "alias.csv"
Test-Path -LiteralPath (Join-Path $testPath "alias.csv") | Should Be $true
}
It "with NoClobber" {
$path = Export-Alias alias.csv
try
{
Export-Alias alias.csv -NoClobber
}
catch
{
$exportAliasError = $_
}
$exportAliasError.FullyQualifiedErrorId | Should Be "NoClobber,Microsoft.PowerShell.Commands.ExportAliasCommand"
}
AfterEach {
Pop-Location
}
}
Context "Import-Alias literal path" {
BeforeAll {
$csvFile = Join-Path $testPath "alias.csv"
$ps1File = Join-Path $testPath "alias.ps1"
$testCases = @()
$testCases += [TestData]::new("Empty string", "", "ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ImportAliasCommand")
$testCases += [TestData]::new("Null", [NullString]::Value, "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ImportAliasCommand")
$testCases += [TestData]::new("Non filesystem provider", 'cert:\alias.ps1', "NotSupported,Microsoft.PowerShell.Commands.ImportAliasCommand")
}
$testCases | % {
It "for $($_.testName)" {
$test = $_
try
{
Import-Alias -LiteralPath $test.testFile -ErrorAction SilentlyContinue
}
catch
{
$exportAliasError = $_
}
$exportAliasError.FullyqualifiedErrorId | Should Be $test.expectedError
}
}
It "can be done from a CSV file" {
# alias file definition content
$aliasDefinition = @'
"myuh","update-help","","ReadOnly, AllScope"
'@
$aliasFile = Join-Path $testPath "alias.csv"
$aliasDefinition | Out-File -LiteralPath $aliasFile
Import-Alias -LiteralPath $aliasFile
# Verify that the alias was imported
$definedAlias = Get-Alias myuh
$definedAlias | Should Not Be $null
$definedAlias.Name | Should Be "myuh"
$definedAlias.Definition | Should Be "update-help"
}
}
}
Describe "Alias tests" -Tags "CI" {
BeforeAll {
$testPath = Join-Path testdrive:\ ("testAlias\[.test")
New-Item -ItemType Directory -Path $testPath -Force | Out-Null
class TestData
{
[string] $testName
[string] $testFile
[string] $expectedError
TestData($name, $file, $error)
{
$this.testName = $name
$this.testFile = $file
$this.expectedError = $error
}
}
}
Context "Export-Alias literal path" {
BeforeAll {
$csvFile = Join-Path $testPath "alias.csv"
$ps1File = Join-Path $testPath "alias.ps1"
$testCases = @()
$testCases += [TestData]::new("CSV", $csvFile, [NullString]::Value)
$testCases += [TestData]::new("PS1", $ps1File, [NullString]::Value)
$testCases += [TestData]::new("Empty string", "", "ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ExportAliasCommand")
$testCases += [TestData]::new("Null", [NullString]::Value, "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportAliasCommand")
$testCases += [TestData]::new("Non filesystem provider", 'cert:\alias.ps1', "ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportAliasCommand")
}
$testCases | % {
It "for $($_.testName)" {
$test = $_
try
{
Export-Alias -LiteralPath $test.testFile -ErrorAction SilentlyContinue
}
catch
{
$exportAliasError = $_
}
if($test.expectedError -eq $null)
{
Test-Path -LiteralPath $test.testFile | Should Be $true
}
else
{
$exportAliasError.FullyqualifiedErrorId | Should Be $test.expectedError
}
}
AfterEach {
Remove-Item -LiteralPath $test.testFile -Force -ErrorAction SilentlyContinue
}
}
It "when file exists with NoClobber" {
Export-Alias -LiteralPath $csvFile
try
{
Export-Alias -LiteralPath $csvFile -NoClobber
}
catch
{
$exportAliasError = $_
}
$exportAliasError.FullyQualifiedErrorId | Should Be "NoClobber,Microsoft.PowerShell.Commands.ExportAliasCommand"
}
}
Context "Export-All inside a literal path" {
BeforeEach {
Push-Location -LiteralPath $testPath
}
It "with a CSV file" {
Export-Alias "alias.csv"
Test-Path -LiteralPath (Join-Path $testPath "alias.csv") | Should Be $true
}
It "with NoClobber" {
$path = Export-Alias alias.csv
try
{
Export-Alias alias.csv -NoClobber
}
catch
{
$exportAliasError = $_
}
$exportAliasError.FullyQualifiedErrorId | Should Be "NoClobber,Microsoft.PowerShell.Commands.ExportAliasCommand"
}
AfterEach {
Pop-Location
}
}
Context "Import-Alias literal path" {
BeforeAll {
$csvFile = Join-Path $testPath "alias.csv"
$ps1File = Join-Path $testPath "alias.ps1"
$testCases = @()
$testCases += [TestData]::new("Empty string", "", "ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ImportAliasCommand")
$testCases += [TestData]::new("Null", [NullString]::Value, "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ImportAliasCommand")
$testCases += [TestData]::new("Non filesystem provider", 'cert:\alias.ps1', "NotSupported,Microsoft.PowerShell.Commands.ImportAliasCommand")
}
$testCases | % {
It "for $($_.testName)" {
$test = $_
try
{
Import-Alias -LiteralPath $test.testFile -ErrorAction SilentlyContinue
}
catch
{
$exportAliasError = $_
}
$exportAliasError.FullyqualifiedErrorId | Should Be $test.expectedError
}
}
It "can be done from a CSV file" {
# alias file definition content
$aliasDefinition = @'
"myuh","update-help","","ReadOnly, AllScope"
'@
$aliasFile = Join-Path $testPath "alias.csv"
$aliasDefinition | Out-File -LiteralPath $aliasFile
Import-Alias -LiteralPath $aliasFile
# Verify that the alias was imported
$definedAlias = Get-Alias myuh
$definedAlias | Should Not Be $null
$definedAlias.Name | Should Be "myuh"
$definedAlias.Definition | Should Be "update-help"
}
}
}
@@ -1,187 +1,187 @@
Describe "CliXml test" -Tags "CI" {
BeforeAll {
$testFilePath = Join-Path "testdrive:\" "testCliXml"
$subFilePath = Join-Path $testFilePath ".test"
if(test-path $testFilePath)
{
Remove-Item $testFilePath -Force -Recurse
}
# Create the test File and push the location into specified path
New-Item -Path $testFilePath -ItemType Directory | Out-Null
New-Item -Path $subFilePath -ItemType Directory | Out-Null
Push-Location $testFilePath
class TestData
{
[string] $testName
[object] $inputObject
[string] $expectedError
[string] $testFile
TestData($name, $file, $inputObj, $error)
{
$this.testName = $name
$this.inputObject = $inputObj
$this.expectedError = $error
$this.testFile = $file
}
}
}
AfterAll {
Pop-Location
}
Context "Export-CliXml" {
BeforeAll {
$gpsList = Get-Process powershell
$gps = $gpsList | Select-Object -First 1
$filePath = Join-Path $subFilePath 'gps.xml'
$testData = @()
$testData += [TestData]::new("with path as Null", [NullString]::Value, $gps, "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportClixmlCommand")
$testData += [TestData]::new("with path as Empty string", "", $gps, "ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ExportClixmlCommand")
$testData += [TestData]::new("with path as non filesystem provider", "cert:\", $gps, "ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportClixmlCommand")
}
AfterEach {
Remove-Item $filePath -Force -ErrorAction SilentlyContinue
}
$testData | % {
It "$($_.testName)" {
$test = $_
try
{
Export-Clixml -LiteralPath $test.testFile -InputObject $test.inputObject -Force
}
catch
{
$exportCliXmlError = $_
}
$exportCliXmlError.FullyQualifiedErrorId | Should Be $test.expectedError
}
}
It "can be created with literal path" {
$filePath = Join-Path $subFilePath 'gps.xml'
Export-Clixml -LiteralPath $filePath -InputObject ($gpsList | Select-Object -First 1)
$filePath | Should Exist
$fileContent = Get-Content $filePath
$isExisted = $false
foreach($item in $fileContent)
{
foreach($gpsItem in $gpsList)
{
$checkId = $gpsItem.Id
if (($null -ne $(Select-String -InputObject $item -SimpleMatch $checkId)) -and ($null -ne $(Select-String -InputObject $item -SimpleMatch "Id")))
{
$isExisted = $true
break;
}
}
}
$isExisted | Should Be $true
}
It "can be created with literal path using pipeline" {
$filePath = Join-Path $subFilePath 'gps.xml'
($gpsList | Select-Object -First 1) | Export-Clixml -LiteralPath $filePath
$filePath | Should Exist
$fileContent = Get-Content $filePath
$isExisted = $false
foreach($item in $fileContent)
{
foreach($gpsItem in $gpsList)
{
$checkId = $gpsItem.Id
if (($null -ne $(Select-String -InputObject $item -SimpleMatch $checkId)) -and ($null -ne $(Select-String -InputObject $item -SimpleMatch "Id")))
{
$isExisted = $true
break;
}
}
}
$isExisted | Should Be $true
}
}
Context "Import-CliXML" {
BeforeAll {
$gpsList = Get-Process powershell
$gps = $gpsList | Select-Object -First 1
$filePath = Join-Path $subFilePath 'gps.xml'
$testData = @()
$testData += [TestData]::new("with path as Null", [NullString]::Value, $null, "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ImportClixmlCommand")
$testData += [TestData]::new("with path as Empty string", "", $null, "ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ImportClixmlCommand")
$testData += [TestData]::new("with path as non filesystem provider", "cert:\", $null, "ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ImportClixmlCommand")
}
$testData | % {
It "$($_.testName)" {
$test = $_
try
{
Import-Clixml -LiteralPath $test.testFile
}
catch
{
$importCliXmlError = $_
}
$importCliXmlError.FullyQualifiedErrorId | Should Be $test.expectedError
}
}
It "can import from a literal path" {
Export-Clixml -LiteralPath $filePath -InputObject $gps
$filePath | Should Exist
$fileContent = Get-Content $filePath
$fileContent | Should Not Be $null
$importedProcess = Import-Clixml $filePath
$gps.ProcessName | Should Be $importedProcess.ProcessName
$gps.Id | Should Be $importedProcess.Id
}
It "can import from a literal path using pipeline" {
$gps | Export-Clixml -LiteralPath $filePath
$filePath | Should Exist
$fileContent = Get-Content $filePath
$fileContent | Should Not Be $null
$importedProcess = Import-Clixml $filePath
$gps.ProcessName | Should Be $importedProcess.ProcessName
$gps.Id | Should Be $importedProcess.Id
}
It "test follow-up for WinBlue: 161470 - Export-CliXml errors in WhatIf scenarios" {
$testPath = "testdrive:\Bug161470NonExistPath.txt"
Export-Clixml -Path $testPath -InputObject "string" -WhatIf
$testPath | Should Not Exist
}
}
}
Describe "CliXml test" -Tags "CI" {
BeforeAll {
$testFilePath = Join-Path "testdrive:\" "testCliXml"
$subFilePath = Join-Path $testFilePath ".test"
if(test-path $testFilePath)
{
Remove-Item $testFilePath -Force -Recurse
}
# Create the test File and push the location into specified path
New-Item -Path $testFilePath -ItemType Directory | Out-Null
New-Item -Path $subFilePath -ItemType Directory | Out-Null
Push-Location $testFilePath
class TestData
{
[string] $testName
[object] $inputObject
[string] $expectedError
[string] $testFile
TestData($name, $file, $inputObj, $error)
{
$this.testName = $name
$this.inputObject = $inputObj
$this.expectedError = $error
$this.testFile = $file
}
}
}
AfterAll {
Pop-Location
}
Context "Export-CliXml" {
BeforeAll {
$gpsList = Get-Process powershell
$gps = $gpsList | Select-Object -First 1
$filePath = Join-Path $subFilePath 'gps.xml'
$testData = @()
$testData += [TestData]::new("with path as Null", [NullString]::Value, $gps, "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportClixmlCommand")
$testData += [TestData]::new("with path as Empty string", "", $gps, "ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ExportClixmlCommand")
$testData += [TestData]::new("with path as non filesystem provider", "cert:\", $gps, "ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportClixmlCommand")
}
AfterEach {
Remove-Item $filePath -Force -ErrorAction SilentlyContinue
}
$testData | % {
It "$($_.testName)" {
$test = $_
try
{
Export-Clixml -LiteralPath $test.testFile -InputObject $test.inputObject -Force
}
catch
{
$exportCliXmlError = $_
}
$exportCliXmlError.FullyQualifiedErrorId | Should Be $test.expectedError
}
}
It "can be created with literal path" {
$filePath = Join-Path $subFilePath 'gps.xml'
Export-Clixml -LiteralPath $filePath -InputObject ($gpsList | Select-Object -First 1)
$filePath | Should Exist
$fileContent = Get-Content $filePath
$isExisted = $false
foreach($item in $fileContent)
{
foreach($gpsItem in $gpsList)
{
$checkId = $gpsItem.Id
if (($null -ne $(Select-String -InputObject $item -SimpleMatch $checkId)) -and ($null -ne $(Select-String -InputObject $item -SimpleMatch "Id")))
{
$isExisted = $true
break;
}
}
}
$isExisted | Should Be $true
}
It "can be created with literal path using pipeline" {
$filePath = Join-Path $subFilePath 'gps.xml'
($gpsList | Select-Object -First 1) | Export-Clixml -LiteralPath $filePath
$filePath | Should Exist
$fileContent = Get-Content $filePath
$isExisted = $false
foreach($item in $fileContent)
{
foreach($gpsItem in $gpsList)
{
$checkId = $gpsItem.Id
if (($null -ne $(Select-String -InputObject $item -SimpleMatch $checkId)) -and ($null -ne $(Select-String -InputObject $item -SimpleMatch "Id")))
{
$isExisted = $true
break;
}
}
}
$isExisted | Should Be $true
}
}
Context "Import-CliXML" {
BeforeAll {
$gpsList = Get-Process powershell
$gps = $gpsList | Select-Object -First 1
$filePath = Join-Path $subFilePath 'gps.xml'
$testData = @()
$testData += [TestData]::new("with path as Null", [NullString]::Value, $null, "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ImportClixmlCommand")
$testData += [TestData]::new("with path as Empty string", "", $null, "ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ImportClixmlCommand")
$testData += [TestData]::new("with path as non filesystem provider", "cert:\", $null, "ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ImportClixmlCommand")
}
$testData | % {
It "$($_.testName)" {
$test = $_
try
{
Import-Clixml -LiteralPath $test.testFile
}
catch
{
$importCliXmlError = $_
}
$importCliXmlError.FullyQualifiedErrorId | Should Be $test.expectedError
}
}
It "can import from a literal path" {
Export-Clixml -LiteralPath $filePath -InputObject $gps
$filePath | Should Exist
$fileContent = Get-Content $filePath
$fileContent | Should Not Be $null
$importedProcess = Import-Clixml $filePath
$gps.ProcessName | Should Be $importedProcess.ProcessName
$gps.Id | Should Be $importedProcess.Id
}
It "can import from a literal path using pipeline" {
$gps | Export-Clixml -LiteralPath $filePath
$filePath | Should Exist
$fileContent = Get-Content $filePath
$fileContent | Should Not Be $null
$importedProcess = Import-Clixml $filePath
$gps.ProcessName | Should Be $importedProcess.ProcessName
$gps.Id | Should Be $importedProcess.Id
}
It "test follow-up for WinBlue: 161470 - Export-CliXml errors in WhatIf scenarios" {
$testPath = "testdrive:\Bug161470NonExistPath.txt"
Export-Clixml -Path $testPath -InputObject "string" -WhatIf
$testPath | Should Not Exist
}
}
}
@@ -1,80 +1,80 @@
Describe "Trace-Command" -tags "Feature" {
Context "Listner options" {
BeforeAll {
$logFile = setup -f traceCommandLog.txt -pass
$actualLogFile = setup -f actualTraceCommandLog.txt -pass
}
AfterEach {
if ( test-path $logfile ) { Remove-Item $logFile }
if ( test-path $actualLogFile ) { Remove-Item $actualLogFile }
}
It "LogicalOperationStack works" -pending:($IsCore) {
$keyword = "Trace_Command_ListenerOption_LogicalOperationStack_Foo"
$stack = [System.Diagnostics.Trace]::CorrelationManager.LogicalOperationStack
$stack.Push($keyword)
Trace-Command -Name * -Expression {write-output Foo} -ListenerOption LogicalOperationStack -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*LogicalOperationStack=$keyword*"}
$log.Count | Should BeGreaterThan 0
}
It "Callstack works" -pending:($IsCore) {
Trace-Command -Name * -Expression {write-output 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 {write-output Foo} -ListenerOption None -FilePath $actualLogfile
Trace-Command -name * -Expression {write-output Foo} -FilePath $logfile
Compare-Object (Get-Content $actualLogfile) (Get-Content $logfile) | Should BeNullOrEmpty
}
It "ThreadID works" {
Trace-Command -Name * -Expression {write-output 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 {write-output 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 {write-output 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 }
}
}
}
Describe "Trace-Command" -tags "Feature" {
Context "Listner options" {
BeforeAll {
$logFile = setup -f traceCommandLog.txt -pass
$actualLogFile = setup -f actualTraceCommandLog.txt -pass
}
AfterEach {
if ( test-path $logfile ) { Remove-Item $logFile }
if ( test-path $actualLogFile ) { Remove-Item $actualLogFile }
}
It "LogicalOperationStack works" -pending:($IsCore) {
$keyword = "Trace_Command_ListenerOption_LogicalOperationStack_Foo"
$stack = [System.Diagnostics.Trace]::CorrelationManager.LogicalOperationStack
$stack.Push($keyword)
Trace-Command -Name * -Expression {write-output Foo} -ListenerOption LogicalOperationStack -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*LogicalOperationStack=$keyword*"}
$log.Count | Should BeGreaterThan 0
}
It "Callstack works" -pending:($IsCore) {
Trace-Command -Name * -Expression {write-output 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 {write-output Foo} -ListenerOption None -FilePath $actualLogfile
Trace-Command -name * -Expression {write-output Foo} -FilePath $logfile
Compare-Object (Get-Content $actualLogfile) (Get-Content $logfile) | Should BeNullOrEmpty
}
It "ThreadID works" {
Trace-Command -Name * -Expression {write-output 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 {write-output 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 {write-output 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 }
}
}
}
@@ -1,64 +1,64 @@
Describe "FormatData" -tags "Feature" {
Context "Export" {
It "can export all types" {
try
{
$expectAllFormat = Get-FormatData -typename *
$expectAllFormat | Export-FormatData -path $TESTDRIVE\allformat.ps1xml -IncludeScriptBlock
$sessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$sessionState.Formats.Clear()
$sessionState.Types.Clear()
$runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($sessionState)
$runspace.Open()
$runspace.CreatePipeline("Update-FormatData -AppendPath $TESTDRIVE\allformat.ps1xml").Invoke()
$actualAllFormat = $runspace.CreatePipeline("Get-FormatData -TypeName *").Invoke()
$expectAllFormat.Count | Should Be $actualAllFormat.Count
Compare-Object $expectAllFormat $actualAllFormat | Should Be $null
$runspace.Close()
}
finally
{
Remove-Item -Path $TESTDRIVE\allformat.ps1xml -Force -ErrorAction SilentlyContinue
}
}
It "works with literal path" {
$filename = 'TestDrive:\[formats.ps1xml'
Get-FormatData -TypeName * | Export-FormatData -LiteralPath $filename
(Test-Path -LiteralPath $filename) | Should Be $true
}
It "should overwrite the destination file" {
$filename = 'TestDrive:\ExportFormatDataWithForce.ps1xml'
$unexpected = "SHOULD BE OVERWRITTEN"
$unexpected | Out-File -FilePath $filename -Force
$file = Get-Item $filename
$file.IsReadOnly = $true
Get-FormatData -TypeName * | Export-FormatData -Path $filename -Force
$actual = @(Get-Content $filename)[0]
$actual | Should Not Be $unexpected
}
It "should not overwrite the destination file with NoClobber" {
$filename = "TestDrive:\ExportFormatDataWithNoClobber.ps1xml"
Get-FormatData -TypeName * | Export-FormatData -LiteralPath $filename
try
{
Get-FormatData -TypeName * | Export-FormatData -LiteralPath $filename -NoClobber
}
catch
{
$exportFormatError = $_
}
$exportFormatError.FullyQualifiedErrorId | Should Be 'NoClobber,Microsoft.PowerShell.Commands.ExportFormatDataCommand'
}
}
}
Describe "FormatData" -tags "Feature" {
Context "Export" {
It "can export all types" {
try
{
$expectAllFormat = Get-FormatData -typename *
$expectAllFormat | Export-FormatData -path $TESTDRIVE\allformat.ps1xml -IncludeScriptBlock
$sessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$sessionState.Formats.Clear()
$sessionState.Types.Clear()
$runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($sessionState)
$runspace.Open()
$runspace.CreatePipeline("Update-FormatData -AppendPath $TESTDRIVE\allformat.ps1xml").Invoke()
$actualAllFormat = $runspace.CreatePipeline("Get-FormatData -TypeName *").Invoke()
$expectAllFormat.Count | Should Be $actualAllFormat.Count
Compare-Object $expectAllFormat $actualAllFormat | Should Be $null
$runspace.Close()
}
finally
{
Remove-Item -Path $TESTDRIVE\allformat.ps1xml -Force -ErrorAction SilentlyContinue
}
}
It "works with literal path" {
$filename = 'TestDrive:\[formats.ps1xml'
Get-FormatData -TypeName * | Export-FormatData -LiteralPath $filename
(Test-Path -LiteralPath $filename) | Should Be $true
}
It "should overwrite the destination file" {
$filename = 'TestDrive:\ExportFormatDataWithForce.ps1xml'
$unexpected = "SHOULD BE OVERWRITTEN"
$unexpected | Out-File -FilePath $filename -Force
$file = Get-Item $filename
$file.IsReadOnly = $true
Get-FormatData -TypeName * | Export-FormatData -Path $filename -Force
$actual = @(Get-Content $filename)[0]
$actual | Should Not Be $unexpected
}
It "should not overwrite the destination file with NoClobber" {
$filename = "TestDrive:\ExportFormatDataWithNoClobber.ps1xml"
Get-FormatData -TypeName * | Export-FormatData -LiteralPath $filename
try
{
Get-FormatData -TypeName * | Export-FormatData -LiteralPath $filename -NoClobber
}
catch
{
$exportFormatError = $_
}
$exportFormatError.FullyQualifiedErrorId | Should Be 'NoClobber,Microsoft.PowerShell.Commands.ExportFormatDataCommand'
}
}
}
@@ -1,100 +1,100 @@
Describe "Object cmdlets" -Tags "CI" {
Context "Group-Object" {
It "AsHashtable returns a hashtable" {
$result = Get-Process | Group-Object -Property ProcessName -AsHashTable
$result["powershell"].Count | Should BeGreaterThan 0
}
It "AsString returns a string" {
$processes = Get-Process | Group-Object -Property ProcessName -AsHashTable -AsString
$result = $processes.Keys | ForEach-Object {$_.GetType()}
$result[0].Name | Should Be "String"
}
}
Context "Tee-Object" {
It "with literal path" {
$path = "TestDrive:\[TeeObjectLiteralPathShouldWorkForSpecialFilename].txt"
Write-Output "Test" | Tee-Object -LiteralPath $path | Tee-Object -Variable TeeObjectLiteralPathShouldWorkForSpecialFilename
$TeeObjectLiteralPathShouldWorkForSpecialFilename | Should Be (Get-Content -LiteralPath $path)
}
}
}
Describe "Object cmdlets" -Tags "CI" {
Context "Measure-Object" {
BeforeAll {
## Powershell language prefers , as an array seperator without "".
## If a number has comma in them it considers it to be the 1000 seperator like "1,000".
## In de-DE language the comma is used as decimal point, but powershell still uses it as a 1000 seperator.
## In case the number has a comma, it is ignored. So, "99,1" becomes 991.
## To work around that behavior, we use ToString() on the expected answer and . for decimal in the input.
$firstValue = "9995788.71"
$expectedFirstValue = $null
$null = [System.Management.Automation.LanguagePrimitives]::TryConvertTo($firstValue, [double], [cultureinfo]::InvariantCulture, [ref] $expectedFirstValue)
$firstObject = new-object psobject
$firstObject | Add-Member -NotePropertyName Header -NotePropertyValue $firstValue
$secondValue = "15847577.7"
$expectedSecondValue = $null
$null = [System.Management.Automation.LanguagePrimitives]::TryConvertTo($secondValue, [double], [cultureinfo]::InvariantCulture, [ref] $expectedSecondValue)
$secondObject = new-object psobject
$secondObject | Add-Member -NotePropertyName Header -NotePropertyValue $secondValue
$testCases = @(
@{ data = @("abc","ABC","Def"); min = "abc"; max = "Def"},
@{ data = @([datetime]::Today, [datetime]::Today.AddDays(-1)); min = ([datetime]::Today.AddDays(-1)).ToString() ; max = [datetime]::Today.ToString() }
@{ data = @(1,2,3,"ABC"); min = 1; max = "ABC"},
@{ data = @(4,2,3,"ABC",1); min = 1; max = "ABC"},
@{ data = @(4,2,3,"ABC",1,"DEF"); min = 1; max = "DEF"},
@{ data = @("111 Test","19"); min = "111 Test"; max = "19"},
@{ data = @("19", "111 Test"); min = "111 Test"; max = "19"},
@{ data = @("111 Test",19); min = "111 Test"; max = 19},
@{ data = @(19, "111 Test"); min = "111 Test"; max = 19},
@{ data = @(100,2,3, "A", 1); min = 1; max = "A"},
@{ data = @(4,2,3, "ABC", 1, "DEF"); min = 1; max = "DEF"},
@{ data = @("abc",[Datetime]::Today,"def"); min = [Datetime]::Today.ToString(); max = "def"}
)
}
It "can compare string representation for minimum" {
$minResult = $firstObject, $secondObject | Measure-Object Header -Minimum
$minResult.Minimum.ToString() | Should Be $expectedFirstValue.ToString()
}
It "can compare string representation for maximum" {
$maxResult = $firstObject, $secondObject | Measure-Object Header -Maximum
$maxResult.Maximum.ToString() | Should Be $expectedSecondValue.ToString()
}
It 'correctly find minimum of (<data>)' -TestCases $testCases {
param($data, $min, $max)
$output = $data | Measure-Object -Minimum
$output.Minimum.ToString() | Should Be $min
}
It 'correctly find maximum of (<data>)' -TestCases $testCases {
param($data, $min, $max)
$output = $data | Measure-Object -Maximum
$output.Maximum.ToString() | Should Be $max
}
It 'returns a GenericMeasureInfoObject' {
$gmi = 1,2,3 | measure-object -max -min
$gmi.GetType().FullName | Should Be 'Microsoft.PowerShell.Commands.GenericMeasureInfo'
}
It 'should return correct error for non-numeric input' {
$gmi = "abc",[Datetime]::Now | measure -sum -max -ev err -ea silentlycontinue
$err | % { $_.FullyQualifiedErrorId | Should Be 'NonNumericInputObject,Microsoft.PowerShell.Commands.MeasureObjectCommand' }
}
It 'should have the correct count' {
$gmi = "abc",[Datetime]::Now | measure -sum -max -ev err -ea silentlycontinue
$gmi.Count | Should Be 2
}
}
}
Describe "Object cmdlets" -Tags "CI" {
Context "Group-Object" {
It "AsHashtable returns a hashtable" {
$result = Get-Process | Group-Object -Property ProcessName -AsHashTable
$result["powershell"].Count | Should BeGreaterThan 0
}
It "AsString returns a string" {
$processes = Get-Process | Group-Object -Property ProcessName -AsHashTable -AsString
$result = $processes.Keys | ForEach-Object {$_.GetType()}
$result[0].Name | Should Be "String"
}
}
Context "Tee-Object" {
It "with literal path" {
$path = "TestDrive:\[TeeObjectLiteralPathShouldWorkForSpecialFilename].txt"
Write-Output "Test" | Tee-Object -LiteralPath $path | Tee-Object -Variable TeeObjectLiteralPathShouldWorkForSpecialFilename
$TeeObjectLiteralPathShouldWorkForSpecialFilename | Should Be (Get-Content -LiteralPath $path)
}
}
}
Describe "Object cmdlets" -Tags "CI" {
Context "Measure-Object" {
BeforeAll {
## Powershell language prefers , as an array seperator without "".
## If a number has comma in them it considers it to be the 1000 seperator like "1,000".
## In de-DE language the comma is used as decimal point, but powershell still uses it as a 1000 seperator.
## In case the number has a comma, it is ignored. So, "99,1" becomes 991.
## To work around that behavior, we use ToString() on the expected answer and . for decimal in the input.
$firstValue = "9995788.71"
$expectedFirstValue = $null
$null = [System.Management.Automation.LanguagePrimitives]::TryConvertTo($firstValue, [double], [cultureinfo]::InvariantCulture, [ref] $expectedFirstValue)
$firstObject = new-object psobject
$firstObject | Add-Member -NotePropertyName Header -NotePropertyValue $firstValue
$secondValue = "15847577.7"
$expectedSecondValue = $null
$null = [System.Management.Automation.LanguagePrimitives]::TryConvertTo($secondValue, [double], [cultureinfo]::InvariantCulture, [ref] $expectedSecondValue)
$secondObject = new-object psobject
$secondObject | Add-Member -NotePropertyName Header -NotePropertyValue $secondValue
$testCases = @(
@{ data = @("abc","ABC","Def"); min = "abc"; max = "Def"},
@{ data = @([datetime]::Today, [datetime]::Today.AddDays(-1)); min = ([datetime]::Today.AddDays(-1)).ToString() ; max = [datetime]::Today.ToString() }
@{ data = @(1,2,3,"ABC"); min = 1; max = "ABC"},
@{ data = @(4,2,3,"ABC",1); min = 1; max = "ABC"},
@{ data = @(4,2,3,"ABC",1,"DEF"); min = 1; max = "DEF"},
@{ data = @("111 Test","19"); min = "111 Test"; max = "19"},
@{ data = @("19", "111 Test"); min = "111 Test"; max = "19"},
@{ data = @("111 Test",19); min = "111 Test"; max = 19},
@{ data = @(19, "111 Test"); min = "111 Test"; max = 19},
@{ data = @(100,2,3, "A", 1); min = 1; max = "A"},
@{ data = @(4,2,3, "ABC", 1, "DEF"); min = 1; max = "DEF"},
@{ data = @("abc",[Datetime]::Today,"def"); min = [Datetime]::Today.ToString(); max = "def"}
)
}
It "can compare string representation for minimum" {
$minResult = $firstObject, $secondObject | Measure-Object Header -Minimum
$minResult.Minimum.ToString() | Should Be $expectedFirstValue.ToString()
}
It "can compare string representation for maximum" {
$maxResult = $firstObject, $secondObject | Measure-Object Header -Maximum
$maxResult.Maximum.ToString() | Should Be $expectedSecondValue.ToString()
}
It 'correctly find minimum of (<data>)' -TestCases $testCases {
param($data, $min, $max)
$output = $data | Measure-Object -Minimum
$output.Minimum.ToString() | Should Be $min
}
It 'correctly find maximum of (<data>)' -TestCases $testCases {
param($data, $min, $max)
$output = $data | Measure-Object -Maximum
$output.Maximum.ToString() | Should Be $max
}
It 'returns a GenericMeasureInfoObject' {
$gmi = 1,2,3 | measure-object -max -min
$gmi.GetType().FullName | Should Be 'Microsoft.PowerShell.Commands.GenericMeasureInfo'
}
It 'should return correct error for non-numeric input' {
$gmi = "abc",[Datetime]::Now | measure -sum -max -ev err -ea silentlycontinue
$err | % { $_.FullyQualifiedErrorId | Should Be 'NonNumericInputObject,Microsoft.PowerShell.Commands.MeasureObjectCommand' }
}
It 'should have the correct count' {
$gmi = "abc",[Datetime]::Now | measure -sum -max -ev err -ea silentlycontinue
$gmi.Count | Should Be 2
}
}
}
@@ -1,63 +1,63 @@
Describe "String cmdlets" -Tags "CI" {
Context "Select-String" {
BeforeAll {
$sep = [io.path]::DirectorySeparatorChar
$fileName = New-Item 'TestDrive:\selectStr[ingLi]teralPath.txt'
"abc" | Out-File -LiteralPath $fileName.fullname
"bcd" | Out-File -LiteralPath $fileName.fullname -Append
"cde" | Out-File -LiteralPath $fileName.fullname -Append
$fileNameWithDots = $fileName.FullName.Replace("\", "\.\")
$tempFile = New-TemporaryFile
"abc" | Out-File -LiteralPath $tempFile.fullname
"bcd" | Out-File -LiteralPath $tempFile.fullname -Append
"cde" | Out-File -LiteralPath $tempFile.fullname -Append
$driveLetter = $tempFile.PSDrive.Name
$fileNameAsNetworkPath = "\\localhost\$driveLetter`$" + $tempFile.FullName.SubString(2)
Push-Location "$fileName\.."
}
AfterAll {
Remove-Item $tempFile -Force -ErrorAction SilentlyContinue
Pop-Location
}
It "LiteralPath with relative path" {
(select-string -LiteralPath (Get-Item -LiteralPath $fileName).Name "b").count | Should Be 2
}
It "LiteralPath with absolute path" {
(select-string -LiteralPath $fileName "b").count | Should Be 2
}
It "LiteralPath with dots in path" {
(select-string -LiteralPath $fileNameWithDots "b").count | Should Be 2
}
It "Network path" -skip:($IsCore) {
(select-string -LiteralPath $fileNameAsNetworkPath "b").count | Should Be 2
}
It "throws error for non filesystem providers" {
$aaa = "aaaaaaaaaa"
select-string -literalPath variable:\aaa "a" -ErrorAction SilentlyContinue -ErrorVariable selectStringError
$selectStringError.FullyQualifiedErrorId | Should Be 'ProcessingFile,Microsoft.PowerShell.Commands.SelectStringCommand'
}
It "throws parameter binding exception for invalid context" {
{ select-string It $PSScriptRoot -Context -1,-1 } | Should Throw Context
}
It "match object supports RelativePath method" {
$file = "Modules${sep}Microsoft.PowerShell.Utility${sep}Microsoft.PowerShell.Utility.psd1"
$match = Select-String CmdletsToExport $pshome/$file
$match.RelativePath($pshome) | Should Be $file
$match.RelativePath($pshome.ToLower()) | Should Be $file
$match.RelativePath($pshome.ToUpper()) | Should Be $file
}
}
}
Describe "String cmdlets" -Tags "CI" {
Context "Select-String" {
BeforeAll {
$sep = [io.path]::DirectorySeparatorChar
$fileName = New-Item 'TestDrive:\selectStr[ingLi]teralPath.txt'
"abc" | Out-File -LiteralPath $fileName.fullname
"bcd" | Out-File -LiteralPath $fileName.fullname -Append
"cde" | Out-File -LiteralPath $fileName.fullname -Append
$fileNameWithDots = $fileName.FullName.Replace("\", "\.\")
$tempFile = New-TemporaryFile
"abc" | Out-File -LiteralPath $tempFile.fullname
"bcd" | Out-File -LiteralPath $tempFile.fullname -Append
"cde" | Out-File -LiteralPath $tempFile.fullname -Append
$driveLetter = $tempFile.PSDrive.Name
$fileNameAsNetworkPath = "\\localhost\$driveLetter`$" + $tempFile.FullName.SubString(2)
Push-Location "$fileName\.."
}
AfterAll {
Remove-Item $tempFile -Force -ErrorAction SilentlyContinue
Pop-Location
}
It "LiteralPath with relative path" {
(select-string -LiteralPath (Get-Item -LiteralPath $fileName).Name "b").count | Should Be 2
}
It "LiteralPath with absolute path" {
(select-string -LiteralPath $fileName "b").count | Should Be 2
}
It "LiteralPath with dots in path" {
(select-string -LiteralPath $fileNameWithDots "b").count | Should Be 2
}
It "Network path" -skip:($IsCore) {
(select-string -LiteralPath $fileNameAsNetworkPath "b").count | Should Be 2
}
It "throws error for non filesystem providers" {
$aaa = "aaaaaaaaaa"
select-string -literalPath variable:\aaa "a" -ErrorAction SilentlyContinue -ErrorVariable selectStringError
$selectStringError.FullyQualifiedErrorId | Should Be 'ProcessingFile,Microsoft.PowerShell.Commands.SelectStringCommand'
}
It "throws parameter binding exception for invalid context" {
{ select-string It $PSScriptRoot -Context -1,-1 } | Should Throw Context
}
It "match object supports RelativePath method" {
$file = "Modules${sep}Microsoft.PowerShell.Utility${sep}Microsoft.PowerShell.Utility.psd1"
$match = Select-String CmdletsToExport $pshome/$file
$match.RelativePath($pshome) | Should Be $file
$match.RelativePath($pshome.ToLower()) | Should Be $file
$match.RelativePath($pshome.ToUpper()) | Should Be $file
}
}
}
@@ -1,68 +1,68 @@
Describe "XML cmdlets" -Tags "Feature" {
Context "Select-XML" {
BeforeAll {
$fileName = New-Item -Path 'TestDrive:\testSelectXml.xml'
Push-Location "$fileName\.."
"<Root>" | out-file -LiteralPath $fileName
" <Node Attribute='blah' />" | out-file -LiteralPath $fileName -Append
"</Root>" | out-file -LiteralPath $fileName -Append
$fileNameWithDots = $fileName.FullName.Replace("\", "\.\")
$driveLetter = [string]($fileName.FullName)[0]
$fileNameAsNetworkPath = "\\localhost\$driveLetter`$" + $fileName.FullName.SubString(2)
class TestData
{
[string] $testName
[hashtable] $parameters
TestData($name, $parameters)
{
$this.testName = $name
$this.parameters = $parameters
}
}
$testcases = @()
$testcases += [TestData]::new('literalpath with relative paths', @{LiteralPath = $fileName.Name; XPath = 'Root'})
$testcases += [TestData]::new('literalpath with absolute paths', @{LiteralPath = $fileName.FullName; XPath = 'Root'})
$testcases += [TestData]::new('literalpath with path with dots', @{LiteralPath = $fileNameWithDots; XPath = 'Root'})
if ( ! $IsCore ) {
$testcases += [TestData]::new('literalpath with network path', @{LiteralPath = $fileNameAsNetworkPath; XPath = 'Root'})
}
$testcases += [TestData]::new('path with relative paths', @{Path = $fileName.Name; XPath = 'Root'})
$testcases += [TestData]::new('path with absolute paths', @{Path = $fileName.FullName; XPath = 'Root'})
$testcases += [TestData]::new('path with path with dots', @{Path = $fileNameWithDots; XPath = 'Root'})
if ( ! $IsCore ) {
$testcases += [TestData]::new('path with network path', @{Path = $fileNameAsNetworkPath; XPath = 'Root'})
}
}
AfterAll {
Remove-Item -LiteralPath $fileName -Force -ErrorAction SilentlyContinue
Pop-Location
}
$testcases | % {
$params = $_.parameters
It $_.testName {
@(Select-XML @params).Count | Should Be 1
}
}
It "literalpath with non filesystem path" {
$__data = "abcdefg"
Select-XML -literalPath variable:__data "Root" -ErrorVariable selectXmlError -ErrorAction SilentlyContinue
$selectXmlError.FullyQualifiedErrorId | Should Be 'ProcessingFile,Microsoft.PowerShell.Commands.SelectXmlCommand'
}
It "path with non filesystem path" {
$__data = "abcdefg"
Select-XML -Path variable:\__data "Root" -ErrorVariable selectXmlError -ErrorAction SilentlyContinue
$selectXmlError.FullyQualifiedErrorId | Should Be 'ProcessingFile,Microsoft.PowerShell.Commands.SelectXmlCommand'
}
}
}
Describe "XML cmdlets" -Tags "Feature" {
Context "Select-XML" {
BeforeAll {
$fileName = New-Item -Path 'TestDrive:\testSelectXml.xml'
Push-Location "$fileName\.."
"<Root>" | out-file -LiteralPath $fileName
" <Node Attribute='blah' />" | out-file -LiteralPath $fileName -Append
"</Root>" | out-file -LiteralPath $fileName -Append
$fileNameWithDots = $fileName.FullName.Replace("\", "\.\")
$driveLetter = [string]($fileName.FullName)[0]
$fileNameAsNetworkPath = "\\localhost\$driveLetter`$" + $fileName.FullName.SubString(2)
class TestData
{
[string] $testName
[hashtable] $parameters
TestData($name, $parameters)
{
$this.testName = $name
$this.parameters = $parameters
}
}
$testcases = @()
$testcases += [TestData]::new('literalpath with relative paths', @{LiteralPath = $fileName.Name; XPath = 'Root'})
$testcases += [TestData]::new('literalpath with absolute paths', @{LiteralPath = $fileName.FullName; XPath = 'Root'})
$testcases += [TestData]::new('literalpath with path with dots', @{LiteralPath = $fileNameWithDots; XPath = 'Root'})
if ( ! $IsCore ) {
$testcases += [TestData]::new('literalpath with network path', @{LiteralPath = $fileNameAsNetworkPath; XPath = 'Root'})
}
$testcases += [TestData]::new('path with relative paths', @{Path = $fileName.Name; XPath = 'Root'})
$testcases += [TestData]::new('path with absolute paths', @{Path = $fileName.FullName; XPath = 'Root'})
$testcases += [TestData]::new('path with path with dots', @{Path = $fileNameWithDots; XPath = 'Root'})
if ( ! $IsCore ) {
$testcases += [TestData]::new('path with network path', @{Path = $fileNameAsNetworkPath; XPath = 'Root'})
}
}
AfterAll {
Remove-Item -LiteralPath $fileName -Force -ErrorAction SilentlyContinue
Pop-Location
}
$testcases | % {
$params = $_.parameters
It $_.testName {
@(Select-XML @params).Count | Should Be 1
}
}
It "literalpath with non filesystem path" {
$__data = "abcdefg"
Select-XML -literalPath variable:__data "Root" -ErrorVariable selectXmlError -ErrorAction SilentlyContinue
$selectXmlError.FullyQualifiedErrorId | Should Be 'ProcessingFile,Microsoft.PowerShell.Commands.SelectXmlCommand'
}
It "path with non filesystem path" {
$__data = "abcdefg"
Select-XML -Path variable:\__data "Root" -ErrorVariable selectXmlError -ErrorAction SilentlyContinue
$selectXmlError.FullyQualifiedErrorId | Should Be 'ProcessingFile,Microsoft.PowerShell.Commands.SelectXmlCommand'
}
}
}