-
-
Notifications
You must be signed in to change notification settings - Fork 473
/
Main.ps1
1282 lines (1057 loc) · 53.5 KB
/
Main.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
function Assert-ValidAssertionName {
param([string]$Name)
if ($Name -notmatch '^\S+$') {
throw "Assertion name '$name' is invalid, assertion name must be a single word."
}
}
function Assert-ValidAssertionAlias {
param([string[]]$Alias)
if ($Alias -notmatch '^\S+$') {
throw "Assertion alias '$string' is invalid, assertion alias must be a single word."
}
}
function Add-ShouldOperator {
<#
.SYNOPSIS
Register a Should Operator with Pester
.DESCRIPTION
This function allows you to create custom Should assertions.
.PARAMETER Name
The name of the assertion. This will become a Named Parameter of Should.
.PARAMETER Test
The test function. The function must return a PSObject with a [Bool]succeeded and a [string]failureMessage property.
.PARAMETER Alias
A list of aliases for the Named Parameter.
.PARAMETER SupportsArrayInput
Does the test function support the passing an array of values to test.
.PARAMETER InternalName
If -Name is different from the actual function name, record the actual function name here.
Used by Get-ShouldOperator to pull function help.
.EXAMPLE
```powershell
function BeAwesome($ActualValue, [switch] $Negate) {
[bool] $succeeded = $ActualValue -eq 'Awesome'
if ($Negate) { $succeeded = -not $succeeded }
if (-not $succeeded) {
if ($Negate) {
$failureMessage = "{$ActualValue} is Awesome"
}
else {
$failureMessage = "{$ActualValue} is not Awesome"
}
}
return [PSCustomObject]@{
Succeeded = $succeeded
FailureMessage = $failureMessage
}
}
Add-ShouldOperator -Name BeAwesome `
-Test $function:BeAwesome `
-Alias 'BA'
PS C:\> "bad" | Should -BeAwesome
{bad} is not Awesome
```
Example of how to create a simple custom assertion that checks if the input string is 'Awesome'
.LINK
https://pester.dev/docs/commands/Add-ShouldOperator
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string] $Name,
[Parameter(Mandatory = $true)]
[scriptblock] $Test,
[ValidateNotNullOrEmpty()]
[AllowEmptyCollection()]
[string[]] $Alias = @(),
[Parameter()]
[string] $InternalName,
[switch] $SupportsArrayInput
)
Assert-BoundScriptBlockInput -ScriptBlock $Test
$entry = [PSCustomObject]@{
Test = $Test
SupportsArrayInput = [bool]$SupportsArrayInput
Name = $Name
Alias = $Alias
InternalName = If ($InternalName) { $InternalName } else { $Name }
}
if (Test-AssertionOperatorIsDuplicate -Operator $entry) {
# This is an exact duplicate of an existing assertion operator.
return
}
# https://github.com/pester/Pester/issues/1355 and https://github.com/PowerShell/PowerShell/issues/9372
if ($script:AssertionOperators.Count -ge 32) {
throw 'Max number of assertion operators (32) has already been reached. This limitation is due to maximum allowed parameter sets in PowerShell.'
}
$namesToCheck = @(
$Name
$Alias
)
Assert-AssertionOperatorNameIsUnique -Name $namesToCheck
$script:AssertionOperators[$Name] = $entry
foreach ($string in $Alias | & $SafeCommands['Where-Object'] { -not ([string]::IsNullOrWhiteSpace($_)) }) {
Assert-ValidAssertionAlias -Alias $string
$script:AssertionAliases[$string] = $Name
}
Add-AssertionDynamicParameterSet -AssertionEntry $entry
}
function Set-ShouldOperatorHelpMessage {
<#
.SYNOPSIS
Sets the helpmessage for a Should-operator. Used in Should's online help for the switch-parameter.
.PARAMETER OperatorName
The name of the assertion/operator.
.PARAMETER HelpMessage
Help message for switch-parameter for the operator in Should.
.NOTES
Internal function as it's only useful for built-in Should operators/assertion atm. to improve online docs.
Can be merged into Add-ShouldOperator later if we'd like to make it pulic and include value in Get-ShouldOperator
https://github.com/pester/Pester/issues/2335
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string] $OperatorName,
[Parameter(Mandatory = $true, Position = 1)]
[string] $HelpMessage
)
end {
$OperatorParam = $script:AssertionDynamicParams[$OperatorName]
if ($null -eq $OperatorParam) {
throw "Should operator '$OperatorName' is not registered"
}
foreach ($attr in $OperatorParam.Attributes) {
if ($attr -is [System.Management.Automation.ParameterAttribute]) {
$attr.HelpMessage = $HelpMessage
}
}
}
}
function Test-AssertionOperatorIsDuplicate {
param (
[psobject] $Operator
)
$existing = $script:AssertionOperators[$Operator.Name]
if (-not $existing) {
return $false
}
return $Operator.SupportsArrayInput -eq $existing.SupportsArrayInput -and
$Operator.Test.ToString() -eq $existing.Test.ToString() -and
-not (& $SafeCommands['Compare-Object'] $Operator.Alias $existing.Alias)
}
function Assert-AssertionOperatorNameIsUnique {
param (
[string[]] $Name
)
foreach ($string in $name | & $SafeCommands['Where-Object'] { -not ([string]::IsNullOrWhiteSpace($_)) }) {
Assert-ValidAssertionName -Name $string
if ($script:AssertionOperators.ContainsKey($string)) {
throw "Assertion operator name '$string' has been added multiple times."
}
if ($script:AssertionAliases.ContainsKey($string)) {
throw "Assertion operator name '$string' already exists as an alias for operator '$($script:AssertionAliases[$key])'"
}
}
}
function Add-AssertionDynamicParameterSet {
param (
[object] $AssertionEntry
)
${function:__AssertionTest__} = $AssertionEntry.Test
$commandInfo = & $SafeCommands['Get-Command'] __AssertionTest__ -CommandType Function
$metadata = [System.Management.Automation.CommandMetadata]$commandInfo
$attribute = [Management.Automation.ParameterAttribute]::new()
$attribute.ParameterSetName = $AssertionEntry.Name
$attributeCollection = [Collections.ObjectModel.Collection[Attribute]]::new()
$null = $attributeCollection.Add($attribute)
if (-not ([string]::IsNullOrWhiteSpace($AssertionEntry.Alias))) {
Assert-ValidAssertionAlias -Alias $AssertionEntry.Alias
$attribute = [System.Management.Automation.AliasAttribute]::new($AssertionEntry.Alias)
$attributeCollection.Add($attribute)
}
# Register assertion
$dynamic = [System.Management.Automation.RuntimeDefinedParameter]::new($AssertionEntry.Name, [switch], $attributeCollection)
$null = $script:AssertionDynamicParams.Add($AssertionEntry.Name, $dynamic)
# Register -Not in the assertion's parameter set. Create parameter if not already present (first assertion).
if ($script:AssertionDynamicParams.ContainsKey('Not')) {
$dynamic = $script:AssertionDynamicParams['Not']
}
else {
$dynamic = [System.Management.Automation.RuntimeDefinedParameter]::new('Not', [switch], ([System.Collections.ObjectModel.Collection[Attribute]]::new()))
$null = $script:AssertionDynamicParams.Add('Not', $dynamic)
}
$attribute = [System.Management.Automation.ParameterAttribute]::new()
$attribute.ParameterSetName = $AssertionEntry.Name
$attribute.Mandatory = $false
$attribute.HelpMessage = 'Reverse the assertion'
$null = $dynamic.Attributes.Add($attribute)
# Register required parameters in the assertion's parameter set. Create parameter if not already present.
$i = 1
foreach ($parameter in $metadata.Parameters.Values) {
# common parameters that are already defined
if ($parameter.Name -eq 'ActualValue' -or $parameter.Name -eq 'Not' -or $parameter.Name -eq 'Negate') {
continue
}
if ($script:AssertionOperators.ContainsKey($parameter.Name) -or $script:AssertionAliases.ContainsKey($parameter.Name)) {
throw "Test block for assertion operator $($AssertionEntry.Name) contains a parameter named $($parameter.Name), which conflicts with another assertion operator's name or alias."
}
foreach ($alias in $parameter.Aliases) {
if ($script:AssertionOperators.ContainsKey($alias) -or $script:AssertionAliases.ContainsKey($alias)) {
throw "Test block for assertion operator $($AssertionEntry.Name) contains a parameter named $($parameter.Name) with alias $alias, which conflicts with another assertion operator's name or alias."
}
}
if ($script:AssertionDynamicParams.ContainsKey($parameter.Name)) {
$dynamic = $script:AssertionDynamicParams[$parameter.Name]
}
else {
# We deliberately use a type of [object] here to avoid conflicts between different assertion operators that may use the same parameter name.
# We also don't bother to try to copy transformation / validation attributes here for the same reason.
# Because we'll be passing these parameters on to the actual test function later, any errors will come out at that time.
# few years later: using [object] causes problems with switch params (in my case -PassThru), because then we cannot use them without defining a value
# so for switches we must prefer the conflicts over type
if ([switch] -eq $parameter.ParameterType) {
$type = [switch]
}
else {
$type = [object]
}
$dynamic = [System.Management.Automation.RuntimeDefinedParameter]::new($parameter.Name, $type, ([System.Collections.ObjectModel.Collection[Attribute]]::new()))
$null = $script:AssertionDynamicParams.Add($parameter.Name, $dynamic)
}
$attribute = [Management.Automation.ParameterAttribute]::new()
$attribute.ParameterSetName = $AssertionEntry.Name
$attribute.Mandatory = $false
$attribute.Position = ($i++)
# Only visible in command reference on https://pester.dev. Remove if/when migrated to external help (markdown as source).
$attribute.HelpMessage = 'Depends on operator being used. See `Get-ShouldOperator -Name <Operator>` or https://pester.dev/docs/assertions/ for help.'
$null = $dynamic.Attributes.Add($attribute)
}
}
function Get-AssertionOperatorEntry([string] $Name) {
return $script:AssertionOperators[$Name]
}
function Get-AssertionDynamicParams {
return $script:AssertionDynamicParams
}
function Invoke-Pester {
<#
.SYNOPSIS
Runs Pester tests
.DESCRIPTION
The Invoke-Pester function runs Pester tests, including *.Tests.ps1 files and
Pester tests in PowerShell scripts.
You can run scripts that include Pester tests just as you would any other
Windows PowerShell script, including typing the full path at the command line
and running in a script editing program. Typically, you use Invoke-Pester to run
all Pester tests in a directory, or to use its many helpful parameters,
including parameters that generate custom objects or XML files.
By default, Invoke-Pester runs all *.Tests.ps1 files in the current directory
and all subdirectories recursively. You can use its parameters to select tests
by file name, test name, or tag.
To run Pester tests in scripts that take parameter values, use the Script
parameter with a hash table value.
Also, by default, Pester tests write test results to the console host, much like
Write-Host does, but you can use the Show parameter set to None to suppress the host
messages, use the PassThru parameter to generate a custom object
(PSCustomObject) that contains the test results, use the OutputXml and
OutputFormat parameters to write the test results to an XML file, and use the
EnableExit parameter to return an exit code that contains the number of failed
tests.
You can also use the Strict parameter to fail all skipped tests.
This feature is ideal for build systems and other processes that require success
on every test.
To help with test design, Invoke-Pester includes a CodeCoverage parameter that
lists commands, classes, functions, and lines of code that did not run during test
execution and returns the code that ran as a percentage of all tested code.
Invoke-Pester, and the Pester module that exports it, are products of an
open-source project hosted on GitHub. To view, comment, or contribute to the
repository, see https://github.com/Pester.
.PARAMETER CI
(Introduced v5)
Enable Test Results and Exit after Run.
Replace with ConfigurationProperty
TestResult.Enabled = $true
Run.Exit = $true
Since 5.2.0, this option no longer enables CodeCoverage.
To also enable CodeCoverage use this configuration option:
CodeCoverage.Enabled = $true
.PARAMETER CodeCoverage
(Deprecated v4)
Replace with ConfigurationProperty CodeCoverage.Enabled = $true
Adds a code coverage report to the Pester tests. Takes strings or hash table values.
A code coverage report lists the lines of code that did and did not run during
a Pester test. This report does not tell whether code was tested; only whether
the code ran during the test.
By default, the code coverage report is written to the host program
(like Write-Host). When you use the PassThru parameter, the custom object
that Invoke-Pester returns has an additional CodeCoverage property that contains
a custom object with detailed results of the code coverage test, including lines
hit, lines missed, and helpful statistics.
However, NUnitXml and JUnitXml output (OutputXML, OutputFormat) do not include
any code coverage information, because it's not supported by the schema.
Enter the path to the files of code under test (not the test file).
Wildcard characters are supported. If you omit the path, the default is local
directory, not the directory specified by the Script parameter. Pester test files
are by default excluded from code coverage when a directory is provided. When you
provide a test file directly using string, code coverage will be measured. To include
tests in code coverage of a directory, use the dictionary syntax and provide
IncludeTests = $true option, as shown below.
To run a code coverage test only on selected classes, functions or lines in a script,
enter a hash table value with the following keys:
-- Path (P)(mandatory) <string>: Enter one path to the files. Wildcard characters
are supported, but only one string is permitted.
-- IncludeTests <bool>: Includes code coverage for Pester test files (*.tests.ps1).
Default is false.
One of the following: Class/Function or StartLine/EndLine
-- Class (C) <string>: Enter the class name. Wildcard characters are
supported, but only one string is permitted. Default is *.
-- Function (F) <string>: Enter the function name. Wildcard characters are
supported, but only one string is permitted. Default is *.
-or-
-- StartLine (S): Performs code coverage analysis beginning with the specified
line. Default is line 1.
-- EndLine (E): Performs code coverage analysis ending with the specified line.
Default is the last line of the script.
.PARAMETER CodeCoverageOutputFile
(Deprecated v4)
Replace with ConfigurationProperty CodeCoverage.OutputPath
The path where Invoke-Pester will save formatted code coverage results file.
The path must include the location and name of the folder and file name with
a required extension (usually the xml).
If this path is not provided, no file will be generated.
.PARAMETER CodeCoverageOutputFileEncoding
(Deprecated v4)
Replace with ConfigurationProperty CodeCoverage.OutputEncoding
Sets the output encoding of CodeCoverageOutputFileFormat
Default is utf8
.PARAMETER CodeCoverageOutputFileFormat
(Deprecated v4)
Replace with ConfigurationProperty CodeCoverage.OutputFormat
The name of a code coverage report file format.
Default value is: JaCoCo.
Currently supported formats are:
- JaCoCo - this XML file format is compatible with Azure Devops, VSTS/TFS
The ReportGenerator tool can be used to consolidate multiple reports and provide code coverage reporting.
https://github.com/danielpalme/ReportGenerator
.PARAMETER Configuration
[PesterConfiguration] object for Advanced Configuration created using `New-PesterConfiguration`.
For help on each option see about_PesterConfiguration or inspect the object.
.PARAMETER Container
Specifies one or more ContainerInfo-objects that define containers with tests.
ContainerInfo-objects are generated using New-PesterContainer. Useful for
scenarios where data-driven test are generated, e.g. parametrized test files.
.PARAMETER EnableExit
(Deprecated v4)
Replace with ConfigurationProperty Run.Exit
Will cause Invoke-Pester to exit with a exit code equal to the number of failed
tests once all tests have been run. Use this to "fail" a build when any tests fail.
.PARAMETER ExcludePath
(Deprecated v4)
Replace with ConfigurationProperty Run.ExcludePath
.PARAMETER ExcludeTagFilter
(Deprecated v4)
Replace with ConfigurationProperty Filter.ExcludeTag
.PARAMETER FullNameFilter
(Deprecated v4)
Replace with ConfigurationProperty Filter.FullName
.PARAMETER Output
(Deprecated v4)
Replace with ConfigurationProperty Output.Verbosity
Supports Diagnostic, Detailed, Normal, Minimal, None
Default value is: Normal
.PARAMETER OutputFile
(Deprecated v4)
Replace with ConfigurationProperty TestResult.OutputPath
The path where Invoke-Pester will save formatted test results log file.
The path must include the location and name of the folder and file name with
the xml extension.
If this path is not provided, no log will be generated.
.PARAMETER OutputFormat
(Deprecated v4)
Replace with ConfigurationProperty TestResult.OutputFormat
The format of output. Currently NUnitXml and JUnitXml is supported.
.PARAMETER PassThru
Replace with ConfigurationProperty Run.PassThru
Returns a custom object (PSCustomObject) that contains the test results.
By default, Invoke-Pester writes to the host program, not to the output stream (stdout).
If you try to save the result in a variable, the variable is empty unless you
use the PassThru parameter.
To suppress the host output, use the Show parameter set to None.
.PARAMETER Path
Aliases Script
Specifies one or more paths to files containing tests. The value is a path\file
name or name pattern. Wildcards are permitted.
.PARAMETER PesterOption
(Deprecated v4)
This parameter is ignored in v5, and is only present for backwards compatibility
when migrating from v4.
.PARAMETER Quiet
(Deprecated v4)
The parameter Quiet is deprecated since Pester v4.0 and will be deleted
in the next major version of Pester. Please use the parameter Show
with value 'None' instead.
The parameter Quiet suppresses the output that Pester writes to the host program,
including the result summary and CodeCoverage output.
This parameter does not affect the PassThru custom object or the XML output that
is written when you use the Output parameters.
.PARAMETER Show
(Deprecated v4)
Replace with ConfigurationProperty Output.Verbosity
Customizes the output Pester writes to the screen. Available options are None, Default,
Passed, Failed, Skipped, Inconclusive, Describe, Context, Summary, Header, All, Fails.
The options can be combined to define presets.
ConfigurationProperty Output.Verbosity supports the following values:
None
Minimal
Normal
Detailed
Diagnostic
Show parameter supports the following parameter values:
None - (None) to write no output to the screen.
All - (Detailed) to write all available information (this is default option).
Default - (Detailed)
Detailed - (Detailed)
Fails - (Normal) to write everything except Passed (but including Describes etc.).
Diagnostic - (Diagnostic)
Normal - (Normal)
Minimal - (Minimal)
A common setting is also Failed, Summary, to write only failed tests and test summary.
This parameter does not affect the PassThru custom object or the XML output that
is written when you use the Output parameters.
.PARAMETER Strict
(Deprecated v4)
Makes Skipped tests to Failed tests. Useful for continuous
integration where you need to make sure all tests passed.
.PARAMETER TagFilter
(Deprecated v4)
Aliases Tag, Tags
Replace with ConfigurationProperty Filter.Tag
.EXAMPLE
Invoke-Pester
This command runs all *.Tests.ps1 files in the current directory and its subdirectories.
.EXAMPLE
Invoke-Pester -Path .\Util*
This commands runs all *.Tests.ps1 files in subdirectories with names that begin
with 'Util' and their subdirectories.
.EXAMPLE
```powershell
$config = [PesterConfiguration]@{
Should = @{ # <- Should configuration.
ErrorAction = 'Continue' # <- Always run all Should-assertions in a test
}
}
Invoke-Pester -Configuration $config
```
This example runs all *.Tests.ps1 files in the current directory and its subdirectories.
It shows how advanced configuration can be used by casting a hashtable to override
default settings, in this case to make Pester run all Should-assertions in a test
even if the first fails.
.EXAMPLE
$config = New-PesterConfiguration
$config.TestResult.Enabled = $true
Invoke-Pester -Configuration $config
This example runs all *.Tests.ps1 files in the current directory and its subdirectories.
It uses advanced configuration to enable testresult-output to file. Access $config.TestResult
to see other testresult options like output path and format and their default values.
.LINK
https://pester.dev/docs/commands/Invoke-Pester
.LINK
https://pester.dev/docs/quick-start
#>
# Currently doesn't work. $IgnoreUnsafeCommands filter used in rule as workaround
# [Diagnostics.CodeAnalysis.SuppressMessageAttribute('Pester.BuildAnalyzerRules\Measure-SafeCommands', 'Remove-Variable', Justification = 'Remove-Variable can't remove "optimized variables" when using "alias" for Remove-Variable.')]
[CmdletBinding(DefaultParameterSetName = 'Simple')]
[OutputType([Pester.Run])]
param(
[Parameter(Position = 0, Mandatory = 0, ParameterSetName = "Simple")]
[Parameter(Position = 0, Mandatory = 0, ParameterSetName = "Legacy")] # Legacy set for v4 compatibility during migration - deprecated
[Alias("Script")] # Legacy set for v4 compatibility during migration - deprecated
[String[]] $Path = '.',
[Parameter(ParameterSetName = "Simple")]
[String[]] $ExcludePath = @(),
[Parameter(ParameterSetName = "Simple")]
[Parameter(Position = 4, Mandatory = 0, ParameterSetName = "Legacy")] # Legacy set for v4 compatibility during migration - deprecated
[Alias("Tag")] # Legacy set for v4 compatibility during migration - deprecated
[Alias("Tags")] # Legacy set for v4 compatibility during migration - deprecated
[string[]] $TagFilter,
[Parameter(ParameterSetName = "Simple")]
[Parameter(ParameterSetName = "Legacy")] # Legacy set for v4 compatibility during migration - deprecated
[string[]] $ExcludeTagFilter,
[Parameter(Position = 1, Mandatory = 0, ParameterSetName = "Legacy")] # Legacy set for v4 compatibility during migration - deprecated
[Parameter(ParameterSetName = "Simple")]
[Alias("Name")] # Legacy set for v4 compatibility during migration - deprecated
[string[]] $FullNameFilter,
[Parameter(ParameterSetName = "Simple")]
[Switch] $CI,
[Parameter(ParameterSetName = "Simple")]
[ValidateSet("Diagnostic", "Detailed", "Normal", "Minimal", "None")]
[String] $Output = "Normal",
[Parameter(ParameterSetName = "Simple")]
[Parameter(ParameterSetName = "Legacy")] # Legacy set for v4 compatibility during migration - deprecated
[Switch] $PassThru,
[Parameter(ParameterSetName = "Simple")]
[Pester.ContainerInfo[]] $Container,
[Parameter(ParameterSetName = "Advanced")]
[PesterConfiguration] $Configuration,
# rest of the Legacy set
[Parameter(Position = 2, Mandatory = 0, ParameterSetName = "Legacy", DontShow)] # Legacy set for v4 compatibility during migration - deprecated
[switch]$EnableExit,
[Parameter(ParameterSetName = "Legacy", DontShow)] # Legacy set for v4 compatibility during migration - deprecated
[object[]] $CodeCoverage = @(),
[Parameter(ParameterSetName = "Legacy", DontShow)] # Legacy set for v4 compatibility during migration - deprecated
[string] $CodeCoverageOutputFile,
[Parameter(ParameterSetName = "Legacy", DontShow)] # Legacy set for v4 compatibility during migration - deprecated
[string] $CodeCoverageOutputFileEncoding = 'utf8',
[Parameter(ParameterSetName = "Legacy", DontShow)] # Legacy set for v4 compatibility during migration - deprecated
[ValidateSet('JaCoCo')]
[String]$CodeCoverageOutputFileFormat = "JaCoCo",
[Parameter(ParameterSetName = "Legacy", DontShow)] # Legacy set for v4 compatibility during migration - deprecated
[Switch]$Strict,
[Parameter(ParameterSetName = "Legacy", DontShow)] # Legacy set for v4 compatibility during migration - deprecated
[string] $OutputFile,
[Parameter(ParameterSetName = "Legacy", DontShow)] # Legacy set for v4 compatibility during migration - deprecated
[ValidateSet('NUnitXml', 'NUnit2.5', 'JUnitXml')]
[string] $OutputFormat = 'NUnitXml',
[Parameter(ParameterSetName = "Legacy", DontShow)] # Legacy set for v4 compatibility during migration - deprecated
[Switch]$Quiet,
[Parameter(ParameterSetName = "Legacy", DontShow)] # Legacy set for v4 compatibility during migration - deprecated
[object]$PesterOption,
[Parameter(ParameterSetName = "Legacy", DontShow)] # Legacy set for v4 compatibility during migration - deprecated
[String] $Show = 'All'
)
begin {
$start = [DateTime]::Now
# this will inherit to child scopes and allow Describe / Context to run directly from a file or command line
$invokedViaInvokePester = $true
if ($null -eq $state) {
# Cleanup any leftover mocks from previous runs, but only if we are not running in a nested Pester-run
# todo: move mock cleanup to BeforeAllBlockContainer when there is any?
Remove-MockFunctionsAndAliases -SessionState $PSCmdlet.SessionState
}
else {
# this will inherit to child scopes and affect behavior of ex. TestDrive/TestRegistry
$runningPesterInPester = $true
}
# this will inherit to child scopes and allow Pester to run in Pester, not checking if this is
# already defined because we want a clean state for this Invoke-Pester even if it runs inside another
# testrun (which calls Invoke-Pester itself)
$state = New-PesterState
# store CWD so we can revert any changes at the end
$initialPWD = $pwd.Path
}
end {
try {
# populate config from parameters and remove them (variables) so we
# don't inherit them to child functions by accident
if ('Simple' -eq $PSCmdlet.ParameterSetName) {
# dot-sourcing the function to allow removing local variables
$Configuration = . Convert-PesterSimpleParameterSet -BoundParameters $PSBoundParameters
}
elseif ('Legacy' -eq $PSCmdlet.ParameterSetName) {
& $SafeCommands['Write-Warning'] 'You are using Legacy parameter set that adapts Pester 5 syntax to Pester 4 syntax. This parameter set is deprecated, and does not work 100%. The -Strict and -PesterOption parameters are ignored, and providing advanced configuration to -Path (-Script), and -CodeCoverage via a hash table does not work. Please refer to https://github.com/pester/Pester/releases/tag/5.0.1#legacy-parameter-set for more information.'
# dot-sourcing the function to allow removing local variables
$Configuration = . Convert-PesterLegacyParameterSet -BoundParameters $PSBoundParameters
}
# maybe -IgnorePesterPreference to avoid using $PesterPreference from the context
$callerPreference = [PesterConfiguration] $PSCmdlet.SessionState.PSVariable.GetValue("PesterPreference")
$hasCallerPreference = $null -ne $callerPreference
# we never want to use and keep the pester preference directly,
# because then the settings are modified on an object that outlives the
# invoke-pester run and we leak changes from this run to the next
# such as filters set in the first run will end up in the next run as well
#
# preference is inherited in all subsequent calls in this session state
# but we still pass it explicitly where practical
if (-not $hasCallerPreference) {
if ($PSBoundParameters.ContainsKey('Configuration')) {
# Advanced configuration used, merging to get new reference
[PesterConfiguration] $PesterPreference = [PesterConfiguration]::Merge([PesterConfiguration]::Default, $Configuration)
}
else {
[PesterConfiguration] $PesterPreference = $Configuration
}
}
elseif ($hasCallerPreference) {
[PesterConfiguration] $PesterPreference = [PesterConfiguration]::Merge($callerPreference, $Configuration)
}
& $SafeCommands['Get-Variable'] 'Configuration' -Scope Local | Remove-Variable
# $sessionState = Set-SessionStateHint -PassThru -Hint "Caller - Captured in Invoke-Pester" -SessionState $PSCmdlet.SessionState
$sessionState = $PSCmdlet.SessionState
$pluginConfiguration = @{}
$pluginData = @{}
$plugins = [System.Collections.Generic.List[object]]@()
# Processing Output-configuration before any use of Write-PesterStart and Write-PesterDebugMessage.
# Write-PesterDebugMessage is used regardless of WriteScreenPlugin.
Resolve-OutputConfiguration -PesterPreference $PesterPreference
if ('None' -ne $PesterPreference.Output.Verbosity.Value) {
$plugins.Add((Get-WriteScreenPlugin -Verbosity $PesterPreference.Output.Verbosity.Value))
}
$plugins.Add((
# decorator plugin needs to be added after output
# because on teardown they will run in opposite order
# and that way output can consume the fixed object that decorator
# decorated, not nice but works
Get-RSpecObjectDecoratorPlugin
))
if ($PesterPreference.TestDrive.Enabled.Value) {
$plugins.Add((Get-TestDrivePlugin))
}
if ($PesterPreference.TestRegistry.Enabled.Value -and "Windows" -eq (GetPesterOs)) {
$plugins.Add((Get-TestRegistryPlugin))
}
$plugins.Add((Get-MockPlugin))
$plugins.Add((Get-SkipRemainingOnFailurePlugin))
if ($PesterPreference.CodeCoverage.Enabled.Value) {
$plugins.Add((Get-CoveragePlugin))
}
if ($PesterPreference.TestResult.Enabled.Value) {
$plugins.Add((Get-TestResultPlugin))
}
# this is here to support Pester test runner in VSCode. Don't use it unless you are prepared to get broken in the future. And if you decide to use it, let us know in https://github.com/pester/Pester/issues/2021 so we can warn you about removing this.
if (defined additionalPlugins) { $plugins.AddRange(@($script:additionalPlugins)) }
$filter = New-FilterObject `
-Tag $PesterPreference.Filter.Tag.Value `
-ExcludeTag $PesterPreference.Filter.ExcludeTag.Value `
-Line $PesterPreference.Filter.Line.Value `
-ExcludeLine $PesterPreference.Filter.ExcludeLine.Value `
-FullName $PesterPreference.Filter.FullName.Value
$containers = @()
if (any $PesterPreference.Run.ScriptBlock.Value) {
$containers += @( $PesterPreference.Run.ScriptBlock.Value | & $SafeCommands['ForEach-Object'] { New-BlockContainerObject -ScriptBlock $_ })
}
foreach ($c in $PesterPreference.Run.Container.Value) {
# Running through New-BlockContainerObject again to avoid modifying original container and it's Data during runtime
$containers += (New-BlockContainerObject -Container $c -Data $c.Data)
}
if ((any $PesterPreference.Run.Path.Value)) {
if (((none $PesterPreference.Run.ScriptBlock.Value) -and (none $PesterPreference.Run.Container.Value)) -or ('.' -ne $PesterPreference.Run.Path.Value[0])) {
#TODO: Skipping the invocation when scriptblock is provided and the default path, later keep path in the default parameter set and remove scriptblock from it, so get-help still shows . as the default value and we can still provide script blocks via an advanced settings parameter
# TODO: pass the startup options as context to Start instead of just paths
$exclusions = combineNonNull @($PesterPreference.Run.ExcludePath.Value, ($PesterPreference.Run.Container.Value | & $SafeCommands['Where-Object'] { "File" -eq $_.Type } | & $SafeCommands['ForEach-Object'] { $_.Item.FullName }))
$containers += @(Find-File -Path $PesterPreference.Run.Path.Value -ExcludePath $exclusions -Extension $PesterPreference.Run.TestExtension.Value | & $SafeCommands['ForEach-Object'] { New-BlockContainerObject -File $_ })
}
}
$steps = $Plugins.Start
if ($null -ne $steps -and 0 -lt @($steps).Count) {
Invoke-PluginStep -Plugins $Plugins -Step Start -Context @{
Containers = $containers
Configuration = $pluginConfiguration
GlobalPluginData = $pluginData
WriteDebugMessages = $PesterPreference.Debug.WriteDebugMessages.Value
Write_PesterDebugMessage = if ($PesterPreference.Debug.WriteDebugMessages.Value) { $script:SafeCommands['Write-PesterDebugMessage'] }
} -ThrowOnFailure
}
if ((none $containers)) {
throw "No test files were found and no scriptblocks were provided. Please ensure that you provided at least one path to a *$($PesterPreference.Run.TestExtension.Value) file, or a directory that contains such file.$(if ($null -ne $PesterPreference.Run.ExcludePath.Value -and 0 -lt @($PesterPreference.Run.ExcludePath.Value).Length) {" And that there is at least one file not excluded by ExcludeFile filter '$($PesterPreference.Run.ExcludePath.Value -join "', '")'."}) Or that you provided a ScriptBlock test container."
return
}
$r = Invoke-Test -BlockContainer $containers -Plugin $plugins -PluginConfiguration $pluginConfiguration -PluginData $pluginData -SessionState $sessionState -Filter $filter -Configuration $PesterPreference
foreach ($c in $r) {
Fold-Container -Container $c -OnTest { param($t) Add-RSpecTestObjectProperties $t }
}
$run = [Pester.Run]::Create()
$run.Executed = $true
$run.ExecutedAt = $start
$run.PSBoundParameters = $PSBoundParameters
$run.PluginConfiguration = $pluginConfiguration
$run.Plugins = $Plugins
$run.PluginData = $pluginData
$run.Configuration = $PesterPreference
$m = $ExecutionContext.SessionState.Module
$run.Version = if ($m.PrivateData -and $m.PrivateData.PSData -and $m.PrivateData.PSData.PreRelease) {
"$($m.Version)-$($m.PrivateData.PSData.PreRelease)"
}
else {
$m.Version
}
$run.PSVersion = $PSVersionTable.PSVersion
foreach ($i in @($r)) {
$run.Containers.Add($i)
}
PostProcess-RSpecTestRun -TestRun $run
$steps = $Plugins.End
if ($null -ne $steps -and 0 -lt @($steps).Count) {
Invoke-PluginStep -Plugins $Plugins -Step End -Context @{
TestRun = $run
Configuration = $pluginConfiguration
GlobalPluginData = $pluginData
} -ThrowOnFailure
}
if (-not $PesterPreference.Debug.ReturnRawResultObject.Value) {
Remove-RSPecNonPublicProperties $run
}
$failedCount = $run.FailedCount + $run.FailedBlocksCount + $run.FailedContainersCount
if ($PesterPreference.Run.PassThru.Value -and -not ($PesterPreference.Run.Exit.Value -and 0 -ne $failedCount)) {
$run
}
}
catch {
$formatErrorParams = @{
Err = $_
StackTraceVerbosity = $PesterPreference.Output.StackTraceVerbosity.Value
}
if ($PesterPreference.Output.CIFormat.Value -in 'AzureDevops', 'GithubActions') {
$errorMessage = (Format-ErrorMessage @formatErrorParams) -split [Environment]::NewLine
Write-CIErrorToScreen -CIFormat $PesterPreference.Output.CIFormat.Value -CILogLevel $PesterPreference.Output.CILogLevel.Value -Header $errorMessage[0] -Message $errorMessage[1..($errorMessage.Count - 1)]
}
else {
Write-ErrorToScreen @formatErrorParams -Throw:$PesterPreference.Run.Throw.Value
}
if ($PesterPreference.Run.Exit.Value) {
exit -1
}
}
# go back to original CWD
if ($null -ne $initialPWD) { & $SafeCommands['Set-Location'] -Path $initialPWD }
# always set exit code. This both to:
# - avoid inheriting a previous commands non-zero exit code
# - setting the exit code when there were some failed tests, blocks, or containers
$failedCount = $run.FailedCount + $run.FailedBlocksCount + $run.FailedContainersCount
$global:LASTEXITCODE = $failedCount
if ($PesterPreference.Run.Throw.Value -and 0 -ne $failedCount) {
$messages = combineNonNull @(
$(if (0 -lt $run.FailedCount) { "$($run.FailedCount) test$(if (1 -lt $run.FailedCount) { "s" }) failed" })
$(if (0 -lt $run.FailedBlocksCount) { "$($run.FailedBlocksCount) block$(if (1 -lt $run.FailedBlocksCount) { "s" }) failed" })
$(if (0 -lt $run.FailedContainersCount) { "$($run.FailedContainersCount) container$(if (1 -lt $run.FailedContainersCount) { "s" }) failed" })
)
throw "Pester run failed, because $(Join-And $messages)"
}
if ($PesterPreference.Run.Exit.Value -and 0 -ne $failedCount) {
# exit with the number of failed tests when there are any
# and the exit preference is set. This will fail the run in CI
# when any tests failed.
exit $failedCount
}
}
}
function Convert-PesterSimpleParameterSet ($BoundParameters) {
$Configuration = [PesterConfiguration]::Default
$migrations = @{
'Path' = {
if ($null -ne $Path) {
if (@($Path)[0] -is [System.Collections.IDictionary]) {
throw 'Passing hashtable configuration to -Path / -Script is currently not supported in Pester 5.0. Please provide just paths, as an array of strings.'
}
$Configuration.Run.Path = $Path
}
}
'ExcludePath' = {
if ($null -ne $ExcludePath) {
$Configuration.Run.ExcludePath = $ExcludePath
}
}
'TagFilter' = {
if ($null -ne $TagFilter -and 0 -lt @($TagFilter).Count) {
$Configuration.Filter.Tag = $TagFilter
}
}
'ExcludeTagFilter' = {
if ($null -ne $ExcludeTagFilter -and 0 -lt @($ExcludeTagFilter).Count) {
$Configuration.Filter.ExcludeTag = $ExcludeTagFilter
}
}
'FullNameFilter' = {
if ($null -ne $FullNameFilter -and 0 -lt @($FullNameFilter).Count) {
$Configuration.Filter.FullName = $FullNameFilter
}
}
'CI' = {
if ($CI) {
$Configuration.Run.Exit = $true
$Configuration.TestResult.Enabled = $true
}
}
'Output' = {
if ($null -ne $Output) {
$Configuration.Output.Verbosity = $Output
}
}
'PassThru' = {
if ($null -ne $PassThru) {
$Configuration.Run.PassThru = [bool] $PassThru
}
}
'Container' = {
if ($null -ne $Container) {
$Configuration.Run.Container = $Container
}
}
}
# Run all applicable migrations and remove variable to avoid leaking into child scopes
foreach ($key in $migrations.Keys) {
if ($BoundParameters.ContainsKey($key)) {
. $migrations[$key]
& $SafeCommands['Get-Variable'] -Name $key -Scope Local | Remove-Variable
}
}
return $Configuration
}
function Convert-PesterLegacyParameterSet ($BoundParameters) {
$Configuration = [PesterConfiguration]::Default
$migrations = @{
'Path' = {
if ($null -ne $Path) {
$Configuration.Run.Path = $Path
}
}
'FullNameFilter' = {
if ($null -ne $FullNameFilter -and 0 -lt @($FullNameFilter).Count) {
$Configuration.Filter.FullName = $FullNameFilter
}
}
'EnableExit' = {
if ($EnableExit) {
$Configuration.Run.Exit = $true
}
}
'TagFilter' = {
if ($null -ne $TagFilter -and 0 -lt @($TagFilter).Count) {
$Configuration.Filter.Tag = $TagFilter
}
}
'ExcludeTagFilter' = {
if ($null -ne $ExcludeTagFilter -and 0 -lt @($ExcludeTagFilter).Count) {
$Configuration.Filter.ExcludeTag = $ExcludeTagFilter
}
}
'PassThru' = {
if ($null -ne $PassThru) {
$Configuration.Run.PassThru = [bool] $PassThru
}
}