-
Notifications
You must be signed in to change notification settings - Fork 8.2k
Expand file tree
/
Copy pathConsoleHost.Tests.ps1
More file actions
1253 lines (1071 loc) · 51.1 KB
/
ConsoleHost.Tests.ps1
File metadata and controls
1253 lines (1071 loc) · 51.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
using namespace System.Diagnostics
# Minishell (Singleshell) is a powershell concept.
# Its primary use-case is when somebody executes a scriptblock in the new powershell process.
# The objects are automatically marshelled to the child process and
# back to the parent session, so users can avoid custom
# serialization to pass objects between two processes.
Describe 'minishell for native executables' -Tag 'CI' {
BeforeAll {
$powershell = Join-Path -Path $PSHOME -ChildPath "pwsh"
}
Context 'Streams from minishell' {
It 'gets a hashtable object from minishell' {
$output = & $powershell -noprofile { @{'a' = 'b'} }
($output | Measure-Object).Count | Should -Be 1
$output | Should -BeOfType Hashtable
$output['a'] | Should -Be 'b'
}
It 'gets the error stream from minishell' {
$PSNativeCommandUseErrorActionPreference = $false
$output = & $powershell -noprofile { Write-Error 'foo' } 2>&1
($output | Measure-Object).Count | Should -Be 1
$output | Should -BeOfType System.Management.Automation.ErrorRecord
$output.FullyQualifiedErrorId | Should -Be 'Microsoft.PowerShell.Commands.WriteErrorException'
}
It 'gets the information stream from minishell' {
$output = & $powershell -noprofile { Write-Information 'foo' } 6>&1
($output | Measure-Object).Count | Should -Be 1
$output | Should -BeOfType System.Management.Automation.InformationRecord
$output | Should -Be 'foo'
}
}
Context 'Streams to minishell' {
It "passes input into minishell" {
$a = 1,2,3
$val = $a | & $powershell -noprofile -command { $input }
$val.Count | Should -Be 3
$val[0] | Should -Be 1
$val[1] | Should -Be 2
$val[2] | Should -Be 3
}
}
}
Describe "ConsoleHost unit tests" -tags "Feature" {
BeforeAll {
$powershell = Join-Path -Path $PSHOME -ChildPath "pwsh"
$ExitCodeBadCommandLineParameter = 64
function NewProcessStartInfo([string]$CommandLine, [switch]$RedirectStdIn)
{
return [ProcessStartInfo]@{
FileName = $powershell
Arguments = $CommandLine
RedirectStandardInput = $RedirectStdIn
RedirectStandardOutput = $true
RedirectStandardError = $true
UseShellExecute = $false
}
}
function RunPowerShell([ProcessStartInfo]$si)
{
$process = [Process]::Start($si)
return $process
}
function EnsureChildHasExited([Process]$process, [int]$WaitTimeInMS = 15000)
{
$process.WaitForExit($WaitTimeInMS)
if (!$process.HasExited)
{
$process.HasExited | Should -BeTrue
$process.Kill()
}
}
}
AfterEach {
$error.Clear()
}
It "Clear-Host does not injects data into PowerShell output stream" {
if (Test-IsWindowsArm64) {
Set-ItResult -Pending -Because "ARM64 runs in non-interactively mode and Clear-Host does not work."
}
& { Clear-Host; 'hi' } | Should -BeExactly 'hi'
}
Context "ShellInterop" {
It "Verify Parsing Error Output Format Single Shell should throw exception" {
{ & $powershell -outp blah -comm { $input } } | Should -Throw -ErrorId "IncorrectValueForFormatParameter"
}
It "Verify Validate Output Format As Text Explicitly Child Single Shell does not throw" {
{
"blahblah" | & $powershell -noprofile -out text -com { $input }
} | Should -Not -Throw
}
It "Verify Parsing Error Input Format Single Shell should throw exception" {
{ & $powershell -input blah -comm { $input } } | Should -Throw -ErrorId "IncorrectValueForFormatParameter"
}
}
Context "CommandLine" {
It "simple -args" {
& $powershell -noprofile { $args[0] } -args "hello world" | Should -Be "hello world"
}
It "array -args" {
& $powershell -noprofile { $args[0] } -args 1,(2,3) | Should -Be 1
(& $powershell -noprofile { $args[1] } -args 1,(2,3))[1] | Should -Be 3
}
foreach ($x in "--help", "-help", "-h", "-?", "--he", "-hel", "--HELP", "-hEl") {
It "Accepts '$x' as a parameter for help" {
& $powershell -noprofile $x | Where-Object { $_ -match "pwsh[.exe] -Help | -? | /?" } | Should -Not -BeNullOrEmpty
}
}
It "Should accept a Base64 encoded command" {
$commandString = "Get-Location"
$encodedCommand = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($commandString))
# We don't compare to `Get-Location` directly because object and formatted output comparisons are difficult
$expected = & $powershell -noprofile -command $commandString
$actual = & $powershell -noprofile -EncodedCommand $encodedCommand
$actual | Should -Be $expected
}
It "-Version should return the engine version using: -version <value>" -TestCases @(
@{value = ""},
@{value = "2"},
@{value = "-command 1-1"}
) {
$currentVersion = "PowerShell " + $PSVersionTable.GitCommitId.ToString()
$observed = & $powershell -version $value 2>&1
$observed | Should -Be $currentVersion
$LASTEXITCODE | Should -Be 0
}
It "-File should be default parameter" {
Set-Content -Path $testdrive/test.ps1 -Value "'hello'"
$observed = & $powershell -NoProfile $testdrive/test.ps1
$observed | Should -Be "hello"
}
It "-File accepts scripts with .ps1 extension" {
$Filename = 'test.ps1'
Set-Content -Path $testdrive/$Filename -Value "'hello'"
$observed = & $powershell -NoProfile -File $testdrive/$Filename
$observed | Should -Be "hello"
}
It "-File accepts scripts without .ps1 extension to support shebang" -Skip:($IsWindows) {
$Filename = 'test.xxx'
Set-Content -Path $testdrive/$Filename -Value "'hello'"
$observed = & $powershell -NoProfile -File $testdrive/$Filename
$observed | Should -Be "hello"
}
It "-File should fail for script without .ps1 extension" -Skip:(!$IsWindows) {
$Filename = 'test.xxx'
Set-Content -Path $testdrive/$Filename -Value "'hello'"
& $powershell -NoProfile -File $testdrive/$Filename 2>&1 $null
$LASTEXITCODE | Should -Be 64
}
It "-File should pass additional arguments to script" {
Set-Content -Path $testdrive/script.ps1 -Value 'foreach($arg in $args){$arg}'
$observed = & $powershell -NoProfile $testdrive/script.ps1 foo bar
$observed.Count | Should -Be 2
$observed[0] | Should -Be "foo"
$observed[1] | Should -Be "bar"
}
It "-File should be able to pass bool string values as string to parameters: <BoolString>" -TestCases @(
# validates case is preserved
@{BoolString = '$truE'},
@{BoolString = '$falSe'},
@{BoolString = 'trUe'},
@{BoolString = 'faLse'}
) {
param([string]$BoolString)
Set-Content -Path $testdrive/test.ps1 -Value 'param([string]$bool) $bool'
$observed = & $powershell -NoProfile -Nologo -File $testdrive/test.ps1 -Bool $BoolString
$observed | Should -Be $BoolString
}
It "-File should be able to pass bool string values as string to positional parameters: <BoolString>" -TestCases @(
# validates case is preserved
@{BoolString = '$tRue'},
@{BoolString = '$falSe'},
@{BoolString = 'tRUe'},
@{BoolString = 'fALse'}
) {
param([string]$BoolString)
Set-Content -Path $testdrive/test.ps1 -Value 'param([string]$bool) $bool'
$observed = & $powershell -NoProfile -Nologo -File $testdrive/test.ps1 $BoolString
$observed | Should -BeExactly $BoolString
}
It "-File should be able to pass bool string values as bool to switches: <BoolString>" -TestCases @(
@{BoolString = '$tRue'; BoolValue = 'True'},
@{BoolString = '$faLse'; BoolValue = 'False'},
@{BoolString = 'tRue'; BoolValue = 'True'},
@{BoolString = 'fAlse'; BoolValue = 'False'}
) {
param([string]$BoolString, [string]$BoolValue)
Set-Content -Path $testdrive/test.ps1 -Value 'param([switch]$switch) $switch.IsPresent'
$observed = & $powershell -NoProfile -Nologo -File $testdrive/test.ps1 -switch:$BoolString
$observed | Should -Be $BoolValue
}
It "-File should return exit code from script" {
$Filename = 'test.ps1'
Set-Content -Path $testdrive/$Filename -Value 'exit 123'
& $powershell $testdrive/$Filename
$LASTEXITCODE | Should -Be 123
}
It "A single dash should be passed as an arg" {
$testScript = @'
[CmdletBinding()]param(
[string]$p1,
[string]$p2,
[Parameter(ValueFromPipeline)][string]$InputObject
)
process{
$input.replace($p1, $p2)
}
'@
$testFilePath = Join-Path $TestDrive "test.ps1"
Set-Content -Path $testFilePath -Value $testScript
$observed = echo hello | & $powershell -noprofile $testFilePath e -
$observed | Should -BeExactly "h-llo"
}
It "Missing command should fail" {
& $powershell -noprofile -c
$LASTEXITCODE | Should -Be 64
}
It "Empty space command should succeed on non-Windows" -skip:$IsWindows {
& $powershell -noprofile -c '' | Should -BeNullOrEmpty
$LASTEXITCODE | Should -Be 0
}
It "Whitespace command should succeed" {
& $powershell -noprofile -c ' ' | Should -BeNullOrEmpty
$LASTEXITCODE | Should -Be 0
}
}
Context "-Login pwsh switch" {
BeforeAll {
$profilePath = "~/.profile"
$backupProfilePath = "profile.bak"
if (Test-Path $profilePath) {
Move-Item -Path $profilePath -Destination $backupProfilePath -Force
}
$envVarName = 'PSTEST_PROFILE_LOAD'
$guid = New-Guid
Set-Content -Force -Path $profilePath -Value @"
export $envVarName='$guid'
"@
}
AfterAll {
if (Test-Path $backupProfilePath) {
Move-Item -Path $backupProfilePath -Destination $profilePath -Force
}
}
It "Doesn't run the login profile when -Login not used" {
$result = & $powershell -noprofile -Command "`$env:$envVarName"
$result | Should -BeNullOrEmpty
$LASTEXITCODE | Should -Be 0
}
It "Doesn't falsely recognise -Login when elsewhere in the invocation" {
$result = & $powershell -nop -c 'Write-Output "-login"'
$result | Should -BeExactly '-login'
$LASTEXITCODE | Should -Be 0
}
It "Doesn't falsely recognise -Login when used after -Command" {
$result = & $powershell -nop -c 'Write-Output' -Login
$result | Should -BeExactly '-Login'
$LASTEXITCODE | Should -Be 0
}
It "Accepts the <LoginSwitch> switch for -Login and behaves correctly" -TestCases @(
@{ LoginSwitch = '-l' }
@{ LoginSwitch = '-L' }
@{ LoginSwitch = '-login' }
@{ LoginSwitch = '-Login' }
@{ LoginSwitch = '-LOGIN' }
@{ LoginSwitch = '-log' }
) {
param($LoginSwitch)
$result = & $powershell $LoginSwitch -NoProfile -Command "`$env:$envVarName"
if ($IsWindows) {
$result | Should -BeNullOrEmpty
$LASTEXITCODE | Should -Be 0
return
}
$result | Should -BeExactly $guid
$LASTEXITCODE | Should -Be 0
}
It "Starts as a login shell with '-' prepended to name" -Skip:(-not (Get-Command -Name /bin/bash -ErrorAction Ignore)) {
$quoteEscapedPwsh = $powershell.Replace("'", "\'")
$pwshCommand = "`$env:$envVarName"
$bashCommand = "exec -a '-pwsh' '$quoteEscapedPwsh' -NoProfile -Command '`$env:$envVarName' ''"
$result = /bin/bash -c $bashCommand
$result | Should -BeExactly $guid
$LASTEXITCODE | Should -Be 0 # Exit code will be PowerShell's since it was exec'd
}
}
Context "-SettingsFile Commandline switch" {
BeforeAll {
if ($IsWindows) {
$CustomSettingsFile = Join-Path -Path $TestDrive -ChildPath 'Powershell.test.json'
$DefaultExecutionPolicy = 'RemoteSigned'
}
}
BeforeEach {
if ($IsWindows) {
# reset the content of the settings file to a known state.
Set-Content -Path $CustomSettingsfile -Value "{`"Microsoft.PowerShell:ExecutionPolicy`":`"$DefaultExecutionPolicy`"}" -ErrorAction Stop
}
}
# NOTE: The -settingsFile command-line option only reads settings for the local machine. As a result, the tests that use Set/Get-ExecutionPolicy
# must use an explicit scope of LocalMachine to ensure the setting is written to the expected file.
# Skip the tests on Unix platforms because *-ExecutionPolicy cmdlets don't work by design.
It "Verifies PowerShell reads from the custom -settingsFile" -Skip:(!$IsWindows) {
$actualValue = & $powershell -NoProfile -SettingsFile $CustomSettingsFile -Command {(Get-ExecutionPolicy -Scope LocalMachine).ToString()}
$actualValue | Should -Be $DefaultExecutionPolicy
}
It "Verifies PowerShell writes to the custom -settingsFile" -Skip:(!$IsWindows) {
$expectedValue = 'AllSigned'
# Update the execution policy; this should update the settings file.
& $powershell -NoProfile -SettingsFile $CustomSettingsFile -Command {Set-ExecutionPolicy -ExecutionPolicy AllSigned -Scope LocalMachine }
# ensure the setting was written to the settings file.
$content = (Get-Content -Path $CustomSettingsFile | ConvertFrom-Json)
$content.'Microsoft.PowerShell:ExecutionPolicy' | Should -Be $expectedValue
# ensure the setting is applied on next run
$actualValue = & $powershell -NoProfile -SettingsFile $CustomSettingsFile -Command {(Get-ExecutionPolicy -Scope LocalMachine).ToString()}
$actualValue | Should -Be $expectedValue
}
It "Verify PowerShell removes a setting from the custom -settingsFile" -Skip:(!$IsWindows) {
# Remove the LocalMachine execution policy; this should update the settings file.
& $powershell -NoProfile -SettingsFile $CustomSettingsFile -Command {Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope LocalMachine }
# ensure the setting was removed from the settings file.
$content = (Get-Content -Path $CustomSettingsFile | ConvertFrom-Json)
$content.'Microsoft.PowerShell:ExecutionPolicy' | Should -Be $null
}
}
Context "-SettingsFile Commandline switch set 'PSModulePath'" {
BeforeAll {
$CustomSettingsFile = Join-Path -Path $TestDrive -ChildPath 'powershell.test.json'
$mPath1 = Join-Path $PSHOME 'Modules'
$mPath2 = Join-Path $TestDrive 'NonExist'
$pathSep = [System.IO.Path]::PathSeparator
## Use multiple paths in the setting.
$ModulePath = "${mPath1}${pathSep}${mPath2}".Replace('\', "\\")
Set-Content -Path $CustomSettingsfile -Value "{`"Microsoft.PowerShell:ExecutionPolicy`":`"Unrestricted`", `"PSModulePath`": `"$ModulePath`" }" -ErrorAction Stop
}
It "Verify PowerShell PSModulePath should contain paths from config file" {
$psModulePath = & $powershell -NoProfile -SettingsFile $CustomSettingsFile -Command '$env:PSModulePath'
## $mPath1 already exists in the value of env PSModulePath, so it won't be added again.
$index = $psModulePath.IndexOf("${mPath1}${pathSep}", [System.StringComparison]::OrdinalIgnoreCase)
$index | Should -BeGreaterThan 0
$index += $mPath1.Length
$psModulePath.IndexOf($mPath1, $index, [System.StringComparison]::OrdinalIgnoreCase) | Should -BeExactly -1
## $mPath2 should be added at the index position 0.
$psModulePath.StartsWith("${mPath2}${pathSep}", [System.StringComparison]::OrdinalIgnoreCase) | Should -BeTrue
}
}
Context "Pipe to/from powershell" {
BeforeAll {
if ($null -ne $PSStyle) {
$outputRendering = $PSStyle.OutputRendering
$PSStyle.OutputRendering = 'plaintext'
}
$p = [PSCustomObject]@{X=10;Y=20}
}
AfterAll {
if ($null -ne $PSStyle) {
$PSStyle.OutputRendering = $outputRendering
}
}
It "xml input" {
$p | & $powershell -noprofile { $input | ForEach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } } | Should -Be 30
$p | & $powershell -noprofile -inputFormat xml { $input | ForEach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } } | Should -Be 30
}
It "text input" {
# Join (multiple lines) and remove whitespace (we don't care about spacing) to verify we converted to string (by generating a table)
$p | & $powershell -noprofile -inputFormat text { -join ($input -replace "\s","") } | Should -Be "XY--1020"
}
It "xml output" {
& $powershell -noprofile { [PSCustomObject]@{X=10;Y=20} } | ForEach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } | Should -Be 30
& $powershell -noprofile -outputFormat xml { [PSCustomObject]@{X=10;Y=20} } | ForEach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } | Should -Be 30
}
It "text output" {
# Join (multiple lines) and remove whitespace (we don't care about spacing) to verify we converted to string (by generating a table)
-join (& $powershell -noprofile -outputFormat text { $PSStyle.OutputRendering = 'PlainText'; [PSCustomObject]@{X=10;Y=20} }) -replace "\s","" | Should -Be "XY--1020"
}
It "errors are in text if error is redirected, encoded command, non-interactive, and outputformat specified" {
$p = [Diagnostics.Process]::new()
$p.StartInfo.FileName = "pwsh"
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('throw "boom"'))
$p.StartInfo.Arguments = "-EncodedCommand $encoded -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -OutputFormat text"
$p.StartInfo.UseShellExecute = $false
$p.StartInfo.RedirectStandardError = $true
$p.Start() | Out-Null
$out = $p.StandardError.ReadToEnd()
$out | Should -Not -BeNullOrEmpty
$out = $out.Split([Environment]::NewLine)[0]
[System.Management.Automation.Internal.StringDecorated]::new($out).ToString("PlainText") | Should -BeExactly "Exception: boom"
}
It "Progress is not emitted when stdout is redirected" {
$ps = [powershell]::Create()
$null = $ps.AddScript('$a = & ([Environment]::ProcessPath) -Command "Write-Progress -Activity progress"; $a')
$actual = $ps.Invoke()
$ps.HadErrors | Should -BeFalse
$actual | Should -BeNullOrEmpty
$ps.Streams.Progress | Should -BeNullOrEmpty
}
It "Progress is still emitted with redireciton with XML output" {
$ps = [powershell]::Create()
$null = $ps.AddScript('$a = & ([Environment]::ProcessPath) -OutputFormat xml -Command "Write-Progress -Activity progress"; $a')
$actual = $ps.Invoke()
$ps.HadErrors | Should -BeFalse
$actual | Should -BeNullOrEmpty
$ps.Streams.Progress.Count | Should -Be 1
$ps.Streams.Progress[0].Activity | Should -Be progress
}
}
Context "Redirected standard output" {
It "Simple redirected output" {
$si = NewProcessStartInfo "-noprofile -c 1+1"
$process = RunPowerShell $si
$process.StandardOutput.ReadToEnd() | Should -Be 2
EnsureChildHasExited $process
}
}
Context "Input redirected but not reading from stdin (not really interactive)" {
# Tests under this context are testing that we do not read from StandardInput
# even though it is redirected - we want to make sure we don't stop responding.
# So none of these tests should close StandardInput
It "Redirected input w/ implicit -Command w/ -NonInteractive" {
$si = NewProcessStartInfo "-NonInteractive -noprofile -c 1+1" -RedirectStdIn
$process = RunPowerShell $si
$process.StandardOutput.ReadToEnd() | Should -Be 2
EnsureChildHasExited $process
}
It "Redirected input w/ implicit -Command w/o -NonInteractive" {
$si = NewProcessStartInfo "-noprofile -c 1+1" -RedirectStdIn
$process = RunPowerShell $si
$process.StandardOutput.ReadToEnd() | Should -Be 2
EnsureChildHasExited $process
}
It "Redirected input w/ explicit -Command w/ -NonInteractive" {
$si = NewProcessStartInfo "-NonInteractive -noprofile -Command 1+1" -RedirectStdIn
$process = RunPowerShell $si
$process.StandardOutput.ReadToEnd() | Should -Be 2
EnsureChildHasExited $process
}
It "Redirected input w/ explicit -Command w/o -NonInteractive" {
$si = NewProcessStartInfo "-noprofile -Command 1+1" -RedirectStdIn
$process = RunPowerShell $si
$process.StandardOutput.ReadToEnd() | Should -Be 2
EnsureChildHasExited $process
}
It "Redirected input w/ -File w/ -NonInteractive" {
'1+1' | Out-File -Encoding Ascii -FilePath TestDrive:test.ps1 -Force
$si = NewProcessStartInfo "-noprofile -NonInteractive -File $testDrive\test.ps1" -RedirectStdIn
$process = RunPowerShell $si
$process.StandardOutput.ReadToEnd() | Should -Be 2
EnsureChildHasExited $process
}
It "Redirected input w/ -File w/o -NonInteractive" {
'1+1' | Out-File -Encoding Ascii -FilePath TestDrive:test.ps1 -Force
$si = NewProcessStartInfo "-noprofile -File $testDrive\test.ps1" -RedirectStdIn
$process = RunPowerShell $si
$process.StandardOutput.ReadToEnd() | Should -Be 2
EnsureChildHasExited $process
}
}
Context "Redirected standard input for 'interactive' use" {
BeforeAll {
$nl = [Environment]::Newline
$oldColor = $env:NO_COLOR
$env:NO_COLOR = 1
}
AfterAll {
$env:NO_COLOR = $oldColor
}
# All of the following tests replace the prompt (either via an initial command or interactively)
# so that we can read StandardOutput and reliably know exactly what the prompt is.
It "Interactive redirected input: <InteractiveSwitch>" -Pending:($IsWindows) -TestCases @(
@{InteractiveSwitch = ""}
@{InteractiveSwitch = " -IntERactive"}
@{InteractiveSwitch = " -i"}
) {
param($interactiveSwitch)
$si = NewProcessStartInfo "-noprofile -nologo$interactiveSwitch" -RedirectStdIn
$process = RunPowerShell $si
$process.StandardInput.Write("`$function:prompt = { 'PS> ' }`n")
$null = $process.StandardOutput.ReadLine()
$process.StandardInput.Write("1+1`n")
$process.StandardOutput.ReadLine() | Should -Be "PS> 1+1"
$process.StandardOutput.ReadLine() | Should -Be "2"
$process.StandardInput.Write("1+2`n")
$process.StandardOutput.ReadLine() | Should -Be "PS> 1+2"
$process.StandardOutput.ReadLine() | Should -Be "3"
# Backspace should work as expected
$process.StandardInput.Write("1+2`b3`n")
# A real console should render 2`b3 as just 3, but we're just capturing exactly what is written
$process.StandardOutput.ReadLine() | Should -Be "PS> 1+2`b3"
$process.StandardOutput.ReadLine() | Should -Be "4"
$process.StandardInput.Close()
$process.StandardOutput.ReadToEnd() | Should -Be "PS> "
EnsureChildHasExited $process
}
It "Interactive redirected input w/ initial command" -Pending:($IsWindows) {
$si = NewProcessStartInfo "-noprofile -noexit -c ""`$function:prompt = { 'PS> ' }""" -RedirectStdIn
$process = RunPowerShell $si
$process.StandardInput.Write("1+1`n")
$process.StandardOutput.ReadLine() | Should -Be "PS> 1+1"
$process.StandardOutput.ReadLine() | Should -Be "2"
$process.StandardInput.Write("1+2`n")
$process.StandardOutput.ReadLine() | Should -Be "PS> 1+2"
$process.StandardOutput.ReadLine() | Should -Be "3"
$process.StandardInput.Close()
$process.StandardOutput.ReadToEnd() | Should -Be "PS> "
EnsureChildHasExited $process
}
It "Redirected input explicit prompting (-File -)" -Pending:($IsWindows) {
$si = NewProcessStartInfo "-noprofile -" -RedirectStdIn
$process = RunPowerShell $si
$process.StandardInput.Write("`$function:prompt = { 'PS> ' }`n")
$null = $process.StandardOutput.ReadLine()
$process.StandardInput.Write("1+1`n")
$process.StandardOutput.ReadLine() | Should -Be "PS> 1+1"
$process.StandardOutput.ReadLine() | Should -Be "2"
$process.StandardInput.Close()
$process.StandardOutput.ReadToEnd() | Should -Be "PS> "
EnsureChildHasExited $process
}
It "Redirected input no prompting (-Command -)" -Pending:($IsWindows) {
$si = NewProcessStartInfo "-noprofile -Command -" -RedirectStdIn
$process = RunPowerShell $si
$process.StandardInput.Write("1+1`n")
$process.StandardOutput.ReadLine() | Should -Be "2"
# Multi-line input
$process.StandardInput.Write("if (1)`n{`n 42`n}`n`n")
$process.StandardOutput.ReadLine() | Should -Be "42"
$process.StandardInput.Write(@"
function foo
{
'in foo'
}
foo
"@)
$process.StandardOutput.ReadLine() | Should -Be "in foo"
# Backspace sent through stdin should be in the final string
$process.StandardInput.Write("`"a`bc`".Length`n")
$process.StandardOutput.ReadLine() | Should -Be "3"
# Last command with no newline - should be accepted and
# produce output after closing stdin.
$process.StandardInput.Write('22 + 22')
$process.StandardInput.Close()
$process.StandardOutput.ReadLine() | Should -Be "44"
EnsureChildHasExited $process
}
It "Redirected input w/ nested prompt" -Pending:($IsWindows) {
$si = NewProcessStartInfo "-noprofile -noexit -c ""`$function:prompt = { 'PS' + ('>'*(`$NestedPromptLevel+1)) + ' ' }""" -RedirectStdIn
$process = RunPowerShell $si
$process.StandardInput.Write("`$PSStyle.OutputRendering='plaintext'`n")
$null = $process.StandardOutput.ReadLine()
$process.StandardInput.Write("`$Host.EnterNestedPrompt()`n")
$process.StandardOutput.ReadLine() | Should -Be "PS> `$Host.EnterNestedPrompt()"
$process.StandardInput.Write("exit`n")
$process.StandardOutput.ReadLine() | Should -Be "PS>> exit"
$process.StandardInput.Close()
$process.StandardOutput.ReadToEnd() | Should -Be "PS> "
EnsureChildHasExited $process
}
}
Context "Exception handling" {
BeforeAll {
# the default stack size in PowerShell is 10000000, set the stack
# to something much smaller which will produce the error much faster
# I saw a reduction from 65 seconds to 79 milliseconds.
$classDefinition = @'
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
namespace StackTest {
public class StackDepthTest {
public static PowerShell ps;
public static int size = 512 * 1024;
public static void CauseError() {
Thread t = new Thread(RunPS, size);
t.Start();
t.Join();
}
public static void RunPS() {
InitialSessionState iss = InitialSessionState.CreateDefault2();
iss.ThreadOptions = PSThreadOptions.UseCurrentThread;
ps = PowerShell.Create(iss);
ps.AddScript("function recurse { recurse }; recurse").Invoke();
}
public static void GetPSError() {
if ( ps.Streams.Error.Count > 0) {
throw ps.Streams.Error[0].Exception.InnerException;
}
}
}
}
'@
$TestType = Add-Type -PassThru -TypeDefinition $classDefinition
}
It "Should handle a CallDepthOverflow" {
$TestType::CauseError()
{ $TestType::GetPSError() } | Should -Throw -ErrorId "CallDepthOverflow"
}
}
Context "Data, Config, and Cache locations" {
BeforeEach {
$XDG_CACHE_HOME = $env:XDG_CACHE_HOME
$XDG_DATA_HOME = $env:XDG_DATA_HOME
$XDG_CONFIG_HOME = $env:XDG_CONFIG_HOME
}
AfterEach {
$env:XDG_CACHE_HOME = $XDG_CACHE_HOME
$env:XDG_DATA_HOME = $XDG_DATA_HOME
$env:XDG_CONFIG_HOME = $XDG_CONFIG_HOME
}
It "Should start if Data, Config, and Cache location is not accessible" -Skip:($IsWindows) {
$env:XDG_CACHE_HOME = "/dev/cpu"
$env:XDG_DATA_HOME = "/dev/cpu"
$env:XDG_CONFIG_HOME = "/dev/cpu"
$output = & $powershell -noprofile -Command { (Get-Command).count }
[int]$output | Should -BeGreaterThan 0
}
}
Context "HOME environment variable" {
It "Should start if HOME is not defined" -Skip:($IsWindows) {
bash -c "unset HOME;$powershell -c '1+1'" | Should -BeExactly 2
}
It "Same user should use the same temporary HOME directory for different sessions" -Skip:($IsWindows) {
$results = bash -c @"
unset HOME;
$powershell -c '[System.Management.Automation.Platform]::SelectProductNameForDirectory([System.Management.Automation.Platform+XDG_Type]::DEFAULT)';
$powershell -c '[System.Management.Automation.Platform]::SelectProductNameForDirectory([System.Management.Automation.Platform+XDG_Type]::DEFAULT)';
"@
$results | Should -HaveCount 2
$results[0] | Should -BeExactly $results[1]
$tempHomeName = "pwsh-{0}-98288ff9-5712-4a14-9a11-23693b9cd91a" -f [System.Environment]::UserName
$defaultPath = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "$tempHomeName/.config/powershell"
$results[0] | Should -BeExactly $defaultPath
}
}
Context "PATH environment variable" {
It "`$PSHOME should be in front so that pwsh.exe starts current running PowerShell" {
& $powershell -v | Should -Match $PSVersionTable.GitCommitId
}
It "powershell starts if PATH is not set" -Skip:($IsWindows) {
bash -c "unset PATH;$powershell -nop -c '1+1'" | Should -BeExactly 2
}
}
Context "Ambiguous arguments" {
It "Ambiguous argument '<testArg>' should return possible matches" -TestCases @(
@{testArg="-no";expectedMatches=@("-nologo","-noexit","-noprofile","-noninteractive")},
@{testArg="-format";expectedMatches=@("-inputformat","-outputformat")}
) {
param($testArg, $expectedMatches)
$output = & $powershell $testArg -File foo 2>&1
$LASTEXITCODE | Should -Be $ExitCodeBadCommandLineParameter
$outString = [String]::Join(",", $output)
foreach ($expectedMatch in $expectedMatches)
{
$outString | Should -Match $expectedMatch
}
}
}
Context "-WorkingDirectory parameter" {
BeforeAll {
$folderName = (New-Guid).ToString() + " test";
New-Item -Path ~/$folderName -ItemType Directory
$ExitCodeBadCommandLineParameter = 64
}
AfterAll {
Remove-Item ~/$folderName -Force -ErrorAction SilentlyContinue
}
It "Can set working directory to '<value>'" -TestCases @(
@{ value = "~" ; expectedPath = $((Get-Item ~).FullName) },
@{ value = "~/$folderName"; expectedPath = $((Get-Item ~/$folderName).FullName) },
@{ value = "~\$folderName"; expectedPath = $((Get-Item ~\$folderName).FullName) }
) {
param($value, $expectedPath)
$output = & $powershell -NoProfile -WorkingDirectory "$value" -Command '(Get-Location).Path'
$output | Should -BeExactly $expectedPath
}
It "Can use '<parameter>' to set working directory" -TestCases @(
@{ parameter = '-workingdirectory' },
@{ parameter = '-wd' },
@{ parameter = '-wo' }
) {
param($parameter)
$output = & $powershell -NoProfile $parameter ~ -Command "`$PWD.Path"
$output | Should -BeExactly $((Get-Item ~).FullName)
}
It "Error case if -WorkingDirectory isn't given argument as last on command line" {
$output = & $powershell -WorkingDirectory 2>&1
$LASTEXITCODE | Should -Be $ExitCodeBadCommandLineParameter
$output | Should -Not -BeNullOrEmpty
}
It "-WorkingDirectory should be processed before profiles" {
if (Test-Path $PROFILE) {
$currentProfile = Get-Content $PROFILE
}
else {
New-Item -ItemType File -Path $PROFILE -Force
}
@"
(Get-Location).Path
Set-Location $testdrive
"@ > $PROFILE
try {
$out = & $powershell -workingdirectory ~ -c '(Get-Location).Path'
$out | Should -HaveCount 2
$out[0] | Should -BeExactly (Get-Item ~).FullName
$out[1] | Should -BeExactly "$testdrive"
}
finally {
if ($currentProfile) {
Set-Content $PROFILE -Value $currentProfile
}
else {
Remove-Item $PROFILE
}
}
}
}
Context "CustomPipeName startup tests" {
It "Should create pipe file if CustomPipeName is specified" {
$pipeName = [System.IO.Path]::GetRandomFileName()
$pipePath = Get-PipePath $pipeName
# The pipePath should be created by the time the -Command is executed.
& $powershell -CustomPipeName $pipeName -Command "Test-Path '$pipePath'" | Should -BeTrue
}
It "Should throw if CustomPipeName is too long on Linux or macOS" -Skip:($IsWindows) {
# Generate a string that is larger than the max pipe name length.
$longPipeName = [string]::new("A", 200)
"`$PID" | & $powershell -CustomPipeName $longPipeName -c -
$LASTEXITCODE | Should -Be $ExitCodeBadCommandLineParameter
}
}
Context "ApartmentState WPF tests" -Tag Slow {
It "WPF requires STA and will work" -Skip:(!$IsWindows -or [System.Management.Automation.Platform]::IsNanoServer) {
Add-Type -AssemblyName presentationframework
$xaml = [xml]@"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window" Title="Initial Window" WindowStartupLocation = "CenterScreen"
Width = "400" Height = "300" ShowInTaskbar = "True">
</Window>
"@
$reader = [System.Xml.XmlNodeReader]::new($xaml)
$Window = [System.Windows.Markup.XamlReader]::Load($reader)
# This will throw an exception if MTA
{ $Window.Show() } | Should -Not -Throw
$Window.Close()
}
}
Context "ApartmentState tests" {
It "Default apartment state for main thread is STA" -Skip:(!$IsWindows -or [System.Management.Automation.Platform]::IsNanoServer) {
[System.Threading.Thread]::CurrentThread.GetApartmentState() | Should -BeExactly "STA"
}
It "Default apartment state for new runspace is MTA" -Skip:(!$IsWindows) {
$ps = [powershell]::Create()
$ps.AddScript({[System.Threading.Thread]::CurrentThread.GetApartmentState()})
$ps.Invoke() | Should -BeExactly "MTA"
}
It "Should be able to set apartment state to: <apartment>" -Skip:(!$IsWindows -or [System.Management.Automation.Platform]::IsNanoServer) -TestCases @(
@{ apartment = "STA"; switch = "-sta" }
@{ apartment = "MTA"; switch = "-mta" }
) {
param ($apartment, $switch)
& $powershell $switch -noprofile -command "[System.Threading.Thread]::CurrentThread.GetApartmentState()" | Should -BeExactly $apartment
}
It "Should fail to set apartment state to: <switch>" -Skip:($IsWindows -and ![System.Management.Automation.Platform]::IsNanoServer) -TestCases @(
@{ switch = "-sta" }
@{ switch = "-mta" }
) {
param ($switch)
& $powershell $switch -noprofile -command exit
$LASTEXITCODE | Should -Be $ExitCodeBadCommandLineParameter
}
}
Context "Startup banner text tests" -Tag Slow {
BeforeAll {
$outputPath = "Temp:\StartupBannerTest-Output-${Pid}.txt"
$inputPath = "Temp:\StartupBannerTest-Input.txt"
"exit" > $inputPath
# Not testing update notification banner text here
$oldPowerShellUpdateCheck = $env:POWERSHELL_UPDATECHECK
$env:POWERSHELL_UPDATECHECK = "Off"
# Set TERM to "dumb" to avoid DECCKM codes in the output
$oldTERM = $env:TERM
$env:TERM = "dumb"
$escPwd = [regex]::Escape($pwd)
$expectedPromptPattern = "^PS ${escPwd}> exit`$"
$spArgs = @{
FilePath = $powershell
ArgumentList = @("-NoProfile")
RedirectStandardInput = $inputPath
RedirectStandardOutput = $outputPath
WorkingDirectory = $pwd
PassThru = $true
NoNewWindow = $true
UseNewEnvironment = $false
}
}
AfterAll {
$env:TERM = $oldTERM
$env:POWERSHELL_UPDATECHECK = $oldPowerShellUpdateCheck
Remove-Item $inputPath -Force -ErrorAction Ignore
Remove-Item $outputPath -Force -ErrorAction Ignore
}
BeforeEach {
Remove-Item $outputPath -Force -ErrorAction Ignore
}
It "Displays expected startup banner text by default" {
$process = Start-Process @spArgs
Wait-UntilTrue -sb { $process.HasExited } -TimeoutInMilliseconds 5000 -IntervalInMilliseconds 250 | Should -BeTrue
$out = @(Get-Content $outputPath)
$out.Count | Should -Be 2
$out[0] | Should -BeExactly "PowerShell $($PSVersionTable.GitCommitId)"
$out[1] | Should -MatchExactly $expectedPromptPattern
}
It "Displays only the prompt with -NoLogo" {
$spArgs["ArgumentList"] += "-NoLogo"
$process = Start-Process @spArgs
Wait-UntilTrue -sb { $process.HasExited } -TimeoutInMilliseconds 5000 -IntervalInMilliseconds 250 | Should -BeTrue
$out = @(Get-Content $outputPath)
$out.Count | Should -Be 1
$out[0] | Should -MatchExactly $expectedPromptPattern
}
}
Context 'CommandWithArgs tests' {
It 'Should be able to run a pipeline with arguments using <param>' -TestCases @(
@{ param = '-commandwithargs' }
@{ param = '-cwa' }
){
param($param)
$out = pwsh -nologo -noprofile $param '$args | % { "[$_]" }' '$fun' '@times'
$out.Count | Should -Be 2 -Because ($out | Out-String)
$out[0] | Should -BeExactly '[$fun]'
$out[1] | Should -BeExactly '[@times]'
}
It 'Should be able to handle boolean switch: <param>' -TestCases @(
@{ param = '-switch:$true'; expected = 'True'}
@{ param = '-switch:$false'; expected = 'False'}
){
param($param, $expected)
$out = pwsh -nologo -noprofile -cwa 'param([switch]$switch) $switch.IsPresent' $param
$out | Should -Be $expected
}
}
It 'Errors for invalid ExecutionPolicy string' {
$out = pwsh -nologo -noprofile -executionpolicy NonExistingExecutionPolicy -c 'exit 0' 2>&1
$out | Should -Not -BeNullOrEmpty
$LASTEXITCODE | Should -Be $ExitCodeBadCommandLineParameter
}
}