-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
WebCmdlets.Tests.ps1
2195 lines (1777 loc) · 92.4 KB
/
WebCmdlets.Tests.ps1
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, 2016
#
# This is a Pester test suite which validate the Web cmdlets.
#
# Note: These tests use data from http://httpbin.org/
#
# Invokes the given command via script block invocation.
#
function ExecuteWebCommand
{
param (
[ValidateNotNullOrEmpty()]
[string]
$command
)
$result = [PSObject]@{Output = $null; Error = $null}
try
{
$scriptBlock = [scriptblock]::Create($command)
$result.Output = & $scriptBlock
}
catch
{
$result.Error = $_
}
return $result
}
# This function calls either Invoke-WebRequest or Invoke-RestMethod using the OutFile parameter
# Then, the file content is read and return in a $result object.
#
function ExecuteRequestWithOutFile
{
param (
[ValidateSet("Invoke-RestMethod", "Invoke-WebRequest" )]
[string]
$cmdletName,
[string]
$uri = (Get-WebListenerUrl -Test 'Get')
)
$result = [PSObject]@{Output = $null; Error = $null}
$filePath = Join-Path $TestDrive ((Get-Random).ToString() + ".txt")
try
{
if ($cmdletName -eq "Invoke-WebRequest")
{
Invoke-WebRequest -Uri $uri -OutFile $filePath
}
else
{
Invoke-RestMethod -Uri $uri -OutFile $filePath
}
$result.Output = Get-Content $filePath -Raw -ea SilentlyContinue
}
catch
{
$result.Error = $_
}
finally
{
if (Test-Path $filePath)
{
Remove-Item $filePath -Force -ea SilentlyContinue
}
}
return $result
}
# This function calls either Invoke-WebRequest or Invoke-RestMethod with the given uri
# using the Headers parameter to disable keep-alive.
#
function ExecuteRequestWithHeaders
{
param (
[ValidateSet("Invoke-RestMethod", "Invoke-WebRequest" )]
[string]
$cmdletName,
[string]
$uri = (Get-WebListenerUrl -Test 'Get')
)
$result = [PSObject]@{Output = $null; Error = $null}
try
{
$headers = @{ Connection = 'close'}
if ($cmdletName -eq "Invoke-WebRequest")
{
$result.Output = Invoke-WebRequest -Uri $uri -TimeoutSec 5 -Headers $headers
}
else
{
$result.Output = Invoke-RestMethod -Uri $uri -TimeoutSec 5 -Headers $headers
}
}
catch
{
$result.Error = $_
}
return $result
}
# Returns test data for the given content type.
#
function GetTestData
{
param(
[ValidateSet("text/plain", "application/xml", "application/json")]
[String]
$contentType
)
$testData = @{ItemID = 987123; Name = 'TestData'}
if ($contentType -eq "text/plain")
{
$body = $testData | Out-String
}
elseif ($contentType -eq "application/xml")
{
$body = '
<?xml version="1.0" encoding="utf-8"?>
<Objects>
<Object>
<ItemID>987123</ItemID>
<Name>TestData</Name>
</Object>
</Objects>
'
}
else # "application/json"
{
$body = $testData | ConvertTo-Json -Compress
}
return $body
}
function ExecuteRedirectRequest
{
param (
[Parameter(Mandatory)]
[string]
$uri,
[ValidateSet('Invoke-WebRequest', 'Invoke-RestMethod')]
[string] $Cmdlet = 'Invoke-WebRequest',
[ValidateSet('POST', 'GET')]
[string] $Method = 'GET',
[switch] $PreserveAuthorizationOnRedirect
)
$result = [PSObject]@{Output = $null; Error = $null; Content = $null}
try
{
$headers = @{"Authorization" = "test"}
if ($Cmdlet -eq 'Invoke-WebRequest')
{
$result.Output = Invoke-WebRequest -Uri $uri -TimeoutSec 5 -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method
$result.Content = $result.Output.Content | ConvertFrom-Json
}
else
{
$result.Output = Invoke-RestMethod -Uri $uri -TimeoutSec 5 -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method
# NOTE: $result.Output should already be a PSObject (Invoke-RestMethod converts the returned json automatically)
# so simply reference $result.Output
$result.Content = $result.Output
}
}
catch
{
$result.Error = $_
}
return $result
}
# This function calls either Invoke-WebRequest or Invoke-RestMethod with the given uri
# using the custum headers and the optional SkipHeaderValidation switch.
function ExecuteRequestWithCustomHeaders
{
param (
[Parameter(Mandatory)]
[string]
$Uri,
[ValidateSet('Invoke-WebRequest', 'Invoke-RestMethod')]
[string] $Cmdlet = 'Invoke-WebRequest',
[Parameter(Mandatory)]
[ValidateNotNull()]
[Hashtable] $Headers,
[switch] $SkipHeaderValidation
)
$result = [PSObject]@{Output = $null; Error = $null; Content = $null}
try
{
if ($Cmdlet -eq 'Invoke-WebRequest')
{
$result.Output = Invoke-WebRequest -Uri $Uri -TimeoutSec 5 -Headers $Headers -SkipHeaderValidation:$SkipHeaderValidation.IsPresent
$result.Content = $result.Output.Content | ConvertFrom-Json
}
else
{
$result.Output = Invoke-RestMethod -Uri $Uri -TimeoutSec 5 -Headers $Headers -SkipHeaderValidation:$SkipHeaderValidation.IsPresent
# NOTE: $result.Output should already be a PSObject (Invoke-RestMethod converts the returned json automatically)
# so simply reference $result.Output
$result.Content = $result.Output
}
}
catch
{
$result.Error = $_
}
return $result
}
# This function calls either Invoke-WebRequest or Invoke-RestMethod with the given uri
# using the custom UserAgent and the optional SkipHeaderValidation switch.
function ExecuteRequestWithCustomUserAgent {
param (
[Parameter(Mandatory)]
[string]
$Uri,
[ValidateSet('Invoke-WebRequest', 'Invoke-RestMethod')]
[string] $Cmdlet = 'Invoke-WebRequest',
[Parameter(Mandatory)]
[ValidateNotNull()]
[string] $UserAgent,
[switch] $SkipHeaderValidation
)
$result = [PSObject]@{Output = $null; Error = $null; Content = $null}
try {
$Params = @{
Uri = $Uri
TimeoutSec = 5
UserAgent = $UserAgent
SkipHeaderValidation = $SkipHeaderValidation.IsPresent
}
if ($Cmdlet -eq 'Invoke-WebRequest') {
$result.Output = Invoke-WebRequest @Params
$result.Content = $result.Output.Content | ConvertFrom-Json
}
else {
$result.Output = Invoke-RestMethod @Params
# NOTE: $result.Output should already be a PSObject (Invoke-RestMethod converts the returned json automatically)
# so simply reference $result.Output
$result.Content = $result.Output
}
}
catch {
$result.Error = $_
}
return $result
}
# This function calls Invoke-WebRequest with the given uri
function ExecuteWebRequest
{
param (
[Parameter(Mandatory)]
[string]
$Uri,
[switch] $UseBasicParsing
)
$result = [PSObject]@{Output = $null; Error = $null; Content = $null}
try
{
$result.Output = Invoke-WebRequest -Uri $Uri -TimeoutSec 5 -UseBasicParsing:$UseBasicParsing.IsPresent
$result.Content = $result.Output.Content
}
catch
{
$result.Error = $_
}
return $result
}
[string] $verboseEncodingPrefix = 'Content encoding: '
# This function calls Invoke-WebRequest with the given uri and
# parses the verbose output to determine the encoding used for the content.
function ExecuteRestMethod
{
param
(
[Parameter(Mandatory)]
[string]
$Uri,
[switch] $UseBasicParsing
)
$result = @{Output = $null; Error = $null; Encoding = $null; Content = $null}
$verbosePreferenceSave = $VerbosePreference
$VerbosePreference = 'Continue'
try
{
$verboseFile = Join-Path $TestDrive -ChildPath ExecuteRestMethod.verbose.txt
$result.Output = Invoke-RestMethod -Uri $Uri -TimeoutSec 5 -UseBasicParsing:$UseBasicParsing.IsPresent -Verbose 4>$verboseFile
$result.Content = $result.Output
if (Test-Path -Path $verboseFile)
{
$result.Verbose = Get-Content -Path $verboseFile
foreach ($item in $result.Verbose)
{
$line = $item.Trim()
if ($line.StartsWith($verboseEncodingPrefix))
{
$encodingName = $item.SubString($verboseEncodingPrefix.Length).Trim()
$result.Encoding = [System.Text.Encoding]::GetEncoding($encodingName)
break
}
}
if ($result.Encoding -eq $null)
{
throw "Encoding not found in verbose output. Lines: $($result.Verbose.Count) Content:$($result.Verbose)"
}
}
if ($result.Verbose -eq $null)
{
throw "No verbose output was found"
}
}
catch
{
$result.Error = $_ | select-object * | Out-String
}
finally
{
$VerbosePreference = $verbosePreferenceSave
if (Test-Path -Path $verboseFile)
{
Remove-Item -Path $verboseFile -ErrorAction SilentlyContinue
}
}
return $result
}
function GetMultipartBody
{
param
(
[Switch]$String,
[Switch]$File
)
$multipartContent = [System.Net.Http.MultipartFormDataContent]::new()
if ($String.IsPresent)
{
$stringHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data")
$stringHeader.Name = "TestString"
$StringContent = [System.Net.Http.StringContent]::new("TestValue")
$StringContent.Headers.ContentDisposition = $stringHeader
$multipartContent.Add($stringContent)
}
if ($File.IsPresent)
{
$multipartFile = Join-Path $TestDrive 'multipart.txt'
"TestContent" | Set-Content $multipartFile
$FileStream = [System.IO.FileStream]::new($multipartFile, [System.IO.FileMode]::Open)
$fileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data")
$fileHeader.Name = "TestFile"
$fileHeader.FileName = 'multipart.txt'
$fileContent = [System.Net.Http.StreamContent]::new($FileStream)
$fileContent.Headers.ContentDisposition = $fileHeader
$fileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("text/plain")
$multipartContent.Add($fileContent)
}
# unary comma required to prevent $multipartContent from being unwrapped/enumerated
return ,$multipartContent
}
<#
Defines the list of redirect codes to test as well as the
expected Method when the redirection is handled.
See https://msdn.microsoft.com/en-us/library/windows/apps/system.net.httpstatuscode(v=vs.105).aspx
for additonal details.
#>
$redirectTests = @(
@{redirectType = 'MultipleChoices'; redirectedMethod='POST'}
@{redirectType = 'Ambiguous'; redirectedMethod='POST'} # Synonym for MultipleChoices
@{redirectType = 'Moved'; redirectedMethod='GET'}
@{redirectType = 'MovedPermanently'; redirectedMethod='GET'} # Synonym for Moved
@{redirectType = 'Found'; redirectedMethod='GET'}
@{redirectType = 'Redirect'; redirectedMethod='GET'} # Synonym for Found
@{redirectType = 'redirectMethod'; redirectedMethod='GET'}
@{redirectType = 'SeeOther'; redirectedMethod='GET'} # Synonym for RedirectMethod
@{redirectType = 'TemporaryRedirect'; redirectedMethod='GET'}
@{redirectType = 'RedirectKeepVerb'; redirectedMethod='GET'} # Synonym for TemporaryRedirect
)
$PendingCertificateTest = $false
# we can't check for Certificate on MacOS and Centos libcurl (currently 7.29.0) returns the following error:
# The handler does not support client authentication certificates with this combination of libcurl (7.29.0) and its SSL backend ("NSS/3.21 Basic ECC")
if ( $IsMacOS ) { $PendingCertificateTest = $true }
if ( test-path /etc/centos-release ) { $PendingCertificateTest = $true }
Describe "Invoke-WebRequest tests" -Tags "Feature" {
BeforeAll {
$response = Start-HttpListener -Port 8080
$WebListener = Start-WebListener
}
AfterAll {
$null = Stop-HttpListener -Port 8080
$response.PowerShell.Dispose()
}
# Validate the output of Invoke-WebRequest
#
function ValidateResponse
{
param ($response)
$response.Error | Should Be $null
# A successful call returns: Status = 200, and StatusDescription = "OK"
$response.Output.StatusDescription | Should Match "OK"
$response.Output.StatusCode | Should Be 200
# Make sure the response contains the following properties:
$response.Output.RawContent | Should Not Be $null
$response.Output.Headers | Should Not Be $null
$response.Output.RawContent | Should Not Be $null
$response.Output.RawContentLength | Should Not Be $null
$response.Output.Content | Should Not Be $null
}
It "Invoke-WebRequest returns User-Agent" {
$uri = Get-WebListenerUrl -Test 'Get'
$command = "Invoke-WebRequest -Uri '$uri' -TimeoutSec 5"
$result = ExecuteWebCommand -command $command
ValidateResponse -response $result
# Validate response content
$jsonContent = $result.Output.Content | ConvertFrom-Json
$jsonContent.headers.'User-Agent' | Should MatchExactly '(?<!Windows)PowerShell\/\d+\.\d+\.\d+.*'
}
It "Invoke-WebRequest returns headers dictionary" {
$uri = Get-WebListenerUrl -Test 'Get'
$command = "Invoke-WebRequest -Uri '$uri' -TimeoutSec 5"
$result = ExecuteWebCommand -command $command
ValidateResponse -response $result
# Validate response content
$jsonContent = $result.Output.Content | ConvertFrom-Json
$jsonContent.headers.Host | Should Be $Uri.Authority
}
It "Validate Invoke-WebRequest -DisableKeepAlive" {
# Operation options
$uri = Get-WebListenerUrl -Test 'Get'
$command = "Invoke-WebRequest -Uri $uri -TimeoutSec 5 -DisableKeepAlive"
$result = ExecuteWebCommand -command $command
ValidateResponse -response $result
$result.Output.Headers.Connection | Should Be "Close"
}
It "Validate Invoke-WebRequest -MaximumRedirection" {
$uri = Get-WebListenerUrl -Test 'Redirect' -TestValue '3'
$command = "Invoke-WebRequest -Uri '$uri' -MaximumRedirection 4"
$result = ExecuteWebCommand -command $command
ValidateResponse -response $result
# Validate response content
$jsonContent = $result.Output.Content | ConvertFrom-Json
$jsonContent.headers.Host | Should Match $uri.Authority
}
It "Validate Invoke-WebRequest error for -MaximumRedirection" {
$uri = Get-WebListenerUrl -Test 'Redirect' -TestValue '3'
$command = "Invoke-WebRequest -Uri '$uri' -MaximumRedirection 2"
$result = ExecuteWebCommand -command $command
$result.Error.FullyQualifiedErrorId | Should Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
}
It "Invoke-WebRequest supports request that returns page containing UTF-8 data." {
$uri = Get-WebListenerUrl -Test 'Encoding' -TestValue 'Utf8'
$command = "Invoke-WebRequest -Uri '$uri'"
$result = ExecuteWebCommand -command $command
ValidateResponse -response $result
$Result.Output.Encoding.BodyName | Should Be 'utf-8'
$Result.Output.Content | Should Match '⡌⠁⠧⠑ ⠼⠁⠒ ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌'
}
It "Invoke-WebRequest validate timeout option" {
$uri = Get-WebListenerUrl -Test 'Delay' -TestValue '5'
$command = "Invoke-WebRequest -Uri '$uri' -TimeoutSec 5"
$result = ExecuteWebCommand -command $command
$result.Error.FullyQualifiedErrorId | Should Be "System.Threading.Tasks.TaskCanceledException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
}
It "Validate Invoke-WebRequest error with -Proxy and -NoProxy option" {
$uri = Get-WebListenerUrl -Test 'Delay' -TestValue '10'
$command = "Invoke-WebRequest -Uri '$uri' -Proxy 'http://localhost:8080' -NoProxy -TimeoutSec 2"
$result = ExecuteWebCommand -command $command
$result.Error.FullyQualifiedErrorId | Should Be "AmbiguousParameterSet,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
}
$testCase = @(
@{ proxy_address = "http://localhost:9"; name = 'http_proxy'; protocol = 'http' }
@{ proxy_address = "http://localhost:9"; name = 'https_proxy'; protocol = 'https' }
)
It "Validate Invoke-WebRequest error with -Proxy option set - '<name>'" -TestCases $testCase {
param($proxy_address, $name, $protocol)
$uri = Get-WebListenerUrl -Test 'Delay' -TestValue '5' -Https:$($protocol -eq 'https')
$command = "Invoke-WebRequest -Uri '$uri' -TimeoutSec 5 -Proxy '${proxy_address}' -SkipCertificateCheck"
$result = ExecuteWebCommand -command $command
$result.Error.FullyQualifiedErrorId | Should Be "System.Threading.Tasks.TaskCanceledException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
}
It "Validate Invoke-WebRequest error with environment proxy set - '<name>'" -TestCases $testCase {
param($proxy_address, $name, $protocol)
# Configure the environment variable.
New-Item -Name ${name} -Value ${proxy_address} -ItemType Variable -Path Env: -Force
$uri = Get-WebListenerUrl -Test 'Delay' -TestValue '5' -Https:$($protocol -eq 'https')
$command = "Invoke-WebRequest -Uri '$uri' -TimeoutSec 5 -SkipCertificateCheck"
$result = ExecuteWebCommand -command $command
$result.Error.FullyQualifiedErrorId | Should Be "System.Threading.Tasks.TaskCanceledException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
}
It "Validate Invoke-WebRequest returns User-Agent where -NoProxy with envirionment proxy set - '<name>'" -TestCases $testCase {
param($proxy_address, $name, $protocol)
# Configure the environment variable.
New-Item -Name ${name} -Value ${proxy_address} -ItemType Variable -Path Env: -Force
$uri = Get-WebListenerUrl -Test 'Get' -Https:$($protocol -eq 'https')
$command = "Invoke-WebRequest -Uri '$uri' -TimeoutSec 5 -NoProxy -SkipCertificateCheck"
$result = ExecuteWebCommand -command $command
ValidateResponse -response $result
# Validate response content
$jsonContent = $result.Output.Content | ConvertFrom-Json
$jsonContent.headers.Host | Should Be $uri.Authority
}
# Perform the following operation for Invoke-WebRequest
# gzip Returns gzip-encoded data.
# deflate Returns deflate-encoded data.
# $dataEncodings = @("Chunked", "Compress", "Deflate", "GZip", "Identity")
# Note: These are the supported options, but we do not have a web service to test them all.
# $dataEncodings = @("gzip", "deflate") --> Currently there is a bug for deflate encoding. Please see '7976639:Invoke-WebRequest does not support -TransferEncoding deflate' for more info.
$dataEncodings = @("gzip")
foreach ($data in $dataEncodings)
{
It "Invoke-WebRequest supports request that returns $data-encoded data." {
$command = "Invoke-WebRequest -Uri http://httpbin.org/$data -TimeoutSec 5"
$result = ExecuteWebCommand -command $command
ValidateResponse -response $result
# Validate response content
$jsonContent = $result.Output.Content | ConvertFrom-Json
if ($data -eq "gzip")
{
$jsonContent.gzipped | Should Match $true
}
else
{
$jsonContent.deflated | Should Match $true
}
}
}
# Perform the following operation for Invoke-WebRequest using the following content types: "text/plain", "application/xml", "application/xml"
# post Returns POST data.
# patch Returns PATCH data.
# put Returns PUT data.
# delete Returns DELETE data
$testMethods = @("GET", "POST", "PATCH", "PUT", "DELETE")
$contentTypes = @("text/plain", "application/xml", "application/json")
foreach ($contentType in $contentTypes)
{
foreach ($method in $testMethods)
{
# Operation options
$operation = $method.ToLower()
$uri = "http://httpbin.org/$operation"
$body = GetTestData -contentType $contentType
if ($method -eq "GET")
{
$command = "Invoke-WebRequest -Uri $uri"
}
else
{
$command = "Invoke-WebRequest -Uri $uri -Body '$body' -Method $method -ContentType $contentType -TimeoutSec 5"
}
It "$command" {
$result = ExecuteWebCommand -command $command
ValidateResponse -response $result
# Validate response content
$jsonContent = $result.Output.Content | ConvertFrom-Json
$jsonContent.url | Should Match $uri
# For a GET request, there is no data property to validate.
if ($method -ne "GET")
{
$jsonContent.headers.'Content-Type' | Should Match $contentType
# Validate that the response Content.data field is the same as what we sent.
if ($contentType -eq "application/xml")
{
$jsonContent.data | Should Be $body
}
else
{
$jsonContent.data | Should Match $body
}
}
}
}
}
It "Validate Invoke-WebRequest -Headers --> Set KeepAlive to false via headers" {
$uri = Get-WebListenerUrl -Test 'Get'
$result = ExecuteRequestWithHeaders -cmdletName Invoke-WebRequest -uri $uri
ValidateResponse -response $result
$result.Output.Headers.Connection | Should Be "Close"
}
# Validate all available user agents for Invoke-WebRequest
$agents = @{InternetExplorer = "MSIE 9.0"
Chrome = "Chrome"
Opera = "Opera"
Safari = "Safari"
FireFox = "Firefox"
}
foreach ($agentName in $agents.Keys)
{
$expectedAgent = $agents[$agentName]
$uri = Get-WebListenerUrl -Test 'Get'
$userAgent = "[Microsoft.PowerShell.Commands.PSUserAgent]::$agentName"
$command = "Invoke-WebRequest -Uri $uri -UserAgent ($userAgent) -TimeoutSec 5"
It "Validate Invoke-WebRequest UserAgent. Execute--> $command" {
$result = ExecuteWebCommand -command $command
ValidateResponse -response $result
# Validate response content
$jsonContent = $result.Output.Content | ConvertFrom-Json
$jsonContent.headers.Host | Should Be $uri.Authority
$jsonContent.headers.'User-Agent' | Should Match $expectedAgent
}
}
It "Validate Invoke-WebRequest -OutFile" {
$uri = Get-WebListenerUrl -Test 'Get'
$result = ExecuteRequestWithOutFile -cmdletName "Invoke-WebRequest" -uri $uri
$jsonContent = $result.Output | ConvertFrom-Json
$jsonContent.headers.Host | Should Be $uri.Authority
}
It "Validate Invoke-WebRequest handles missing Content-Type in response header" {
#Validate that exception is not thrown when response headers are missing Content-Type.
$command = "Invoke-WebRequest -Uri 'http://httpbin.org/response-headers?Content-Type='"
$result = ExecuteWebCommand -command $command
$result.Error | Should BeNullOrEmpty
}
It "Validate Invoke-WebRequest StandardMethod and CustomMethod parameter sets" {
#Validate that parameter sets are functioning correctly
$errorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
{ Invoke-WebRequest -Uri 'http://http.lee.io/method' -Method GET -CustomMethod TEST } | ShouldBeErrorId $errorId
}
It "Validate Invoke-WebRequest CustomMethod method is used" {
$command = "Invoke-WebRequest -Uri 'http://http.lee.io/method' -CustomMethod TEST"
$result = ExecuteWebCommand -command $command
$result.Error | Should BeNullOrEmpty
($result.Output.Content | ConvertFrom-Json).output.method | Should Be "TEST"
}
It "Validate Invoke-WebRequest default ContentType for CustomMethod POST" {
$command = "Invoke-WebRequest -Uri 'http://httpbin.org/post' -CustomMethod POST -Body 'testparam=testvalue'"
$result = ExecuteWebCommand -command $command
($result.Output.Content | ConvertFrom-Json).form.testparam | Should Be "testvalue"
}
It "Validate Invoke-WebRequest body is converted to query params for CustomMethod GET" {
$uri = Get-WebListenerUrl -Test 'Get'
$command = "Invoke-WebRequest -Uri '$uri' -CustomMethod GET -Body @{'testparam'='testvalue'}"
$result = ExecuteWebCommand -command $command
($result.Output.Content | ConvertFrom-Json).args.testparam | Should Be "testvalue"
}
It "Validate Invoke-WebRequest returns HTTP errors in exception" {
$command = "Invoke-WebRequest -Uri http://httpbin.org/status/418"
$result = ExecuteWebCommand -command $command
$result.Error.ErrorDetails.Message | Should Match "\-=\[ teapot \]"
$result.Error.Exception | Should BeOfType Microsoft.PowerShell.Commands.HttpResponseException
$result.Error.Exception.Response.StatusCode | Should Be 418
$result.Error.Exception.Response.ReasonPhrase | Should Be "I'm a teapot"
$result.Error.Exception.Message | Should Match ": 418 \(I'm a teapot\)\."
$result.Error.FullyQualifiedErrorId | Should Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
}
It "Validate Invoke-WebRequest returns empty RelationLink property if there is no Link Header" {
$command = "Invoke-WebRequest -Uri http://localhost:8080/PowerShell?test=response"
$result = ExecuteWebCommand -command $command
$result.Output.RelationLink.Count | Should Be 0
}
It "Validate Invoke-WebRequest returns valid RelationLink property with absolute uris if Link Header is present" {
$command = "Invoke-WebRequest -Uri 'http://localhost:8080/PowerShell?test=linkheader&maxlinks=5'"
$result = ExecuteWebCommand -command $command
$result.Output.RelationLink.Count | Should BeExactly 2
$result.Output.RelationLink["next"] | Should BeExactly "http://localhost:8080/PowerShell?test=linkheader&maxlinks=5&linknumber=2"
$result.Output.RelationLink["last"] | Should BeExactly "http://localhost:8080/PowerShell?test=linkheader&maxlinks=5&linknumber=5"
}
It "Validate Invoke-WebRequest quietly ignores invalid Link Headers in RelationLink property: <type>" -TestCases @(
@{ type = "noUrl" }
@{ type = "malformed" }
@{ type = "noRel" }
) {
param($type)
$command = "Invoke-WebRequest -Uri 'http://localhost:8080/PowerShell?test=linkheader&type=$type'"
$result = ExecuteWebCommand -command $command
$result.Output.RelationLink.Count | Should BeExactly 1
$result.Output.RelationLink["last"] | Should BeExactly "http://localhost:8080/PowerShell?test=linkheader&maxlinks=3&linknumber=3"
}
#region Redirect tests
It "Validates Invoke-WebRequest with -PreserveAuthorizationOnRedirect preserves the authorization header on redirect: <redirectType> <redirectedMethod>" -TestCases $redirectTests {
param($redirectType, $redirectedMethod)
$response = ExecuteRedirectRequest -Uri "http://localhost:8080/PowerShell?test=redirect&type=$redirectType" -PreserveAuthorizationOnRedirect
$response.Error | Should BeNullOrEmpty
# ensure Authorization header has been preserved.
$response.Content.Headers -contains "Authorization" | Should Be $true
}
It "Validates Invoke-WebRequest preserves the authorization header on multiple redirects: <redirectType>" -TestCases $redirectTests {
param($redirectType)
$response = ExecuteRedirectRequest -Uri "http://localhost:8080/PowerShell?test=redirect&type=$redirectType&multiredirect=true" -PreserveAuthorizationOnRedirect
$response.Error | Should BeNullOrEmpty
# ensure Authorization header was stripped
$response.Content.Headers -contains "Authorization" | Should Be $true
}
It "Validates Invoke-WebRequest strips the authorization header on various redirects: <redirectType>" -TestCases $redirectTests {
param($redirectType)
$response = ExecuteRedirectRequest -Uri "http://localhost:8080/PowerShell?test=redirect&type=$redirectType"
$response.Error | Should BeNullOrEmpty
# ensure user-agent is present (i.e., no false positives )
$response.Content.Headers -contains "User-Agent" | Should Be $true
# ensure Authorization header has been removed.
$response.Content.Headers -contains "Authorization" | Should Be $false
}
# NOTE: Only testing redirection of POST -> GET for unique underlying values of HttpStatusCode.
# Some names overlap in underlying value.
It "Validates Invoke-WebRequest strips the authorization header redirects and switches from POST to GET when it handles the redirect: <redirectType> <redirectedMethod>" -TestCases $redirectTests {
param($redirectType, $redirectedMethod)
$response = ExecuteRedirectRequest -Uri "http://localhost:8080/PowerShell?test=redirect&type=$redirectType" -Method 'POST'
$response.Error | Should BeNullOrEmpty
# ensure user-agent is present (i.e., no false positives )
$response.Content.Headers -contains "User-Agent" | Should Be $true
# ensure Authorization header has been removed.
$response.Content.Headers -contains "Authorization" | Should Be $false
# ensure POST was changed to GET for selected redirections and remains as POST for others.
$response.Content.HttpMethod | Should Be $redirectedMethod
}
#endregion Redirect tests
#region SkipHeaderVerification Tests
It "Verifies Invoke-WebRequest default header handling with no errors" {
$headers = @{"If-Match" = "*"}
$response = ExecuteRequestWithCustomHeaders -Uri "http://localhost:8080/PowerShell?test=echo" -headers $headers
$response.Error | Should BeNullOrEmpty
$response.Content.Headers -contains "If-Match" | Should Be $true
}
It "Verifies Invoke-WebRequest default header handling reports an error is returned for an invalid If-Match header value" {
$headers = @{"If-Match" = "12345"}
$response = ExecuteRequestWithCustomHeaders -Uri "http://localhost:8080/PowerShell?test=echo" -headers $headers
$response.Error | Should Not BeNullOrEmpty
$response.Error.FullyQualifiedErrorId | Should Be "System.FormatException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
$response.Error.Exception.Message | Should Be "The format of value '12345' is invalid."
}
It "Verifies Invoke-WebRequest header handling does not report an error when using -SkipHeaderValidation" {
$headers = @{"If-Match" = "12345"}
$response = ExecuteRequestWithCustomHeaders -Uri "http://localhost:8080/PowerShell?test=echo" -headers $headers -SkipHeaderValidation
$response.Error | Should BeNullOrEmpty
$response.Content.Headers -contains "If-Match" | Should Be $true
}
It "Verifies Invoke-WebRequest default UserAgent handling with no errors" {
$UserAgent = [Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer
$response = ExecuteRequestWithCustomUserAgent -Uri "http://localhost:8080/PowerShell?test=echo" -UserAgent $UserAgent -Cmdlet "Invoke-WebRequest"
$response.Error | Should BeNullOrEmpty
$Pattern = [regex]::Escape($UserAgent)
$response.Content.UserAgent | Should Match $Pattern
}
It "Verifies Invoke-WebRequest default UserAgent handling reports an error is returned for an invalid UserAgent value" {
$UserAgent = 'Invalid:Agent'
$response = ExecuteRequestWithCustomUserAgent -Uri "http://localhost:8080/PowerShell?test=echo" -UserAgent $UserAgent -Cmdlet "Invoke-WebRequest"
$response.Error | Should Not BeNullOrEmpty
$response.Error.FullyQualifiedErrorId | Should Be "System.FormatException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
$response.Error.Exception.Message | Should Be "The format of value 'Invalid:Agent' is invalid."
}
It "Verifies Invoke-WebRequest UserAgent handling does not report an error when using -SkipHeaderValidation" {
$UserAgent = 'Invalid:Agent'
$response = ExecuteRequestWithCustomUserAgent -Uri "http://localhost:8080/PowerShell?test=echo" -UserAgent $UserAgent -SkipHeaderValidation -Cmdlet "Invoke-WebRequest"
$response.Error | Should BeNullOrEmpty
$Pattern = [regex]::Escape($UserAgent)
$response.Content.UserAgent | Should Match $Pattern
}
#endregion SkipHeaderVerification Tests
#region charset encoding tests
Context "BasicHtmlWebResponseObject Encoding tests" {
It "Verifies Invoke-WebRequest detects charset meta value when the ContentType header does not define it." {
$output = '<html><head><meta charset="Unicode"></head></html>'
$expectedEncoding = [System.Text.Encoding]::GetEncoding('Unicode')
$response = ExecuteWebRequest -Uri "http://localhost:8080/PowerShell?test=response&output=$output" -UseBasicParsing
$response.Error | Should BeNullOrEmpty
$response.Output.Encoding.EncodingName | Should Be $expectedEncoding.EncodingName
$response.Output | Should BeOfType 'Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject'
}
It "Verifies Invoke-WebRequest detects charset meta value when newlines are encountered in the element." {
$output = @'
<html>
<head>
<meta
charset="Unicode"
>
</head>
</html>
'@
$expectedEncoding = [System.Text.Encoding]::GetEncoding('Unicode')
$response = ExecuteWebRequest -Uri "http://localhost:8080/PowerShell?test=response&output=$output" -UseBasicParsing
$response.Error | Should BeNullOrEmpty
$response.Output.Encoding.EncodingName | Should Be $expectedEncoding.EncodingName
$response.Output | Should BeOfType 'Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject'
}
It "Verifies Invoke-WebRequest detects charset meta value when the attribute value is unquoted." {
$output = '<html><head><meta charset = Unicode></head></html>'
$expectedEncoding = [System.Text.Encoding]::GetEncoding('Unicode')
$response = ExecuteWebRequest -Uri "http://localhost:8080/PowerShell?test=response&output=$output" -UseBasicParsing
$response.Error | Should BeNullOrEmpty
$response.Output.Encoding.EncodingName | Should Be $expectedEncoding.EncodingName
$response.Output | Should BeOfType 'Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject'
}
It "Verifies Invoke-WebRequest detects http-equiv charset meta value when the ContentType header does not define it." {
$output = @'
<html><head>
<meta http-equiv="content-type" content="text/html; charset=Unicode">
</head>
</html>
'@
$expectedEncoding = [System.Text.Encoding]::GetEncoding('Unicode')
$response = ExecuteWebRequest -Uri "http://localhost:8080/PowerShell?test=response&output=$output" -UseBasicParsing
$response.Error | Should BeNullOrEmpty
$response.Output.Encoding.EncodingName | Should Be $expectedEncoding.EncodingName
$response.Output | Should BeOfType 'Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject'
}
It "Verifies Invoke-WebRequest detects http-equiv charset meta value newlines are encountered in the element." {
$output = @'
<html><head>
<meta
http-equiv="content-type"
content="text/html; charset=Unicode">
</head>
</html>
'@
$expectedEncoding = [System.Text.Encoding]::GetEncoding('Unicode')
$response = ExecuteWebRequest -Uri "http://localhost:8080/PowerShell?test=response&output=$output" -UseBasicParsing
$response.Error | Should BeNullOrEmpty
$response.Output.Encoding.EncodingName | Should Be $expectedEncoding.EncodingName
$response.Output | Should BeOfType 'Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject'
}
It "Verifies Invoke-WebRequest ignores meta charset value when Content-Type header defines it." {
$output = '<html><head><meta charset="utf-32"></head></html>'
# NOTE: meta charset should be ignored
$expectedEncoding = [System.Text.Encoding]::UTF8
$response = ExecuteWebRequest -Uri "http://localhost:8080/PowerShell?test=response&contenttype=text/html; charset=utf-8&output=$output" -UseBasicParsing
$response.Error | Should BeNullOrEmpty
$response.Output.Encoding.EncodingName | Should Be $expectedEncoding.EncodingName
$response.Output | Should BeOfType 'Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject'
}
It "Verifies Invoke-WebRequest honors non-utf8 charsets in the Content-Type header" {
$output = '<html><head><meta charset="utf-32"></head></html>'
# NOTE: meta charset should be ignored
$expectedEncoding = [System.Text.Encoding]::GetEncoding('utf-16')
$response = ExecuteWebRequest -Uri "http://localhost:8080/PowerShell?test=response&contenttype=text/html; charset=utf-16&output=$output" -UseBasicParsing
$response.Error | Should BeNullOrEmpty
$response.Output.Encoding.EncodingName | Should Be $expectedEncoding.EncodingName
$response.Output | Should BeOfType 'Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject'
}