-
Notifications
You must be signed in to change notification settings - Fork 5
/
PSate.psm1
1259 lines (1031 loc) · 33.3 KB
/
PSate.psm1
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
<#
PSate - copyright(c) 2013 - Jon Wagner
See https://github.com/jonwagner/PSate for licensing and other information.
Version: $version$
Changeset: $changeset$
#>
# maintain a current test context so that setup works properly
$testContext = $null
$testFilter = $null
$testOutput = 'Log'
# automatically enable mocking
if (Get-Command Enable-Mock -ErrorAction SilentlyContinue) {
Enable-Mock | iex
}
# see if mocking is enabled, if not, then mock mocking (oh my)
if (!(Get-Command MockContext -ErrorAction SilentlyContinue)) {
function MockContext {
param ([scriptblock] $MockBlock)
# NOTE: if you name this $ScriptBlock, then you modify the module variable ScriptBlock
# and end up with a stack overflow.
& $MockBlock
}
}
<#
.Synopsis
Invokes all of the .Tests.ps1 test scripts in a given path.
.Description
Invokes all of the .Tests.ps1 test scripts in a given path. The tests are run as one test run,
and the results are output.
.Parameter Path
The path to use to look for the test scripts. The default is the current working directory.
.Parameter Recurse
Tells Invoke-Tests to look in child directories.
.Parameter Filter
Tells Invoke-Tests to only invoke the tests matching the description filters.
The filter is an array of match strings that are applied as the test cases are run.
The first string matches the top-level test descriptions, the second string matches second-level
descriptions, etc.
For example, if you have the following test hierarchy:
Describing "FileWatcher" {
Given "one file" { It "watches it" {...}
Given "two files" { It "watches them" { ... }
}
Describing "FileScrubber" { Given "a file" { It "scrubs them" { ... } }
-Filter "Watcher"
Matches all of the FileWatcher tests.
-Filter "Watcher","one"
-Filter *,"one"
Both of these matches only the "one file" tests.
-Filter *,*,"them"
Matches both the "watches them" and "scrubs them" tests.
.Parameter Output
Tells Invoke-Tests how to output the results. The default is Log.
* Quiet - no output is given
* Log - a text representation of the test results is output
* Results - the test results object is output
* Flat - a flat array or test results is output
* NUnit - an NUnit-compatible test result XML structure is output
.Parameter NUnit
Outputs an NUnit-compatible test result XML structure to the given file,
in addition to the data that is output to the stream.
.Parameter ExitCode
Instructs Invoke-Tests to exit the process with the number of failed tests.
This is a good way to indicate failure to an automated build process.
.Parameter ResultsVariable
If specified, the name of a variable to assign the results of the operation.
.Example
Invoke-Tests
Invokes all of the tests in the current path.
.Example
Invoke-Tests .\Tests -Recurse
Invokes all of the tests in the Tests folder and below.
.Example
Invoke-Tests -Recurse -NUnit TestResults.xml -ExitCode
Invokes all of the tests in the current directory and below, and
outputs TestResults.xml to a file, then exits with the number of failed tests.
This is a good example of integrating with a automated build process.
.Example
Invoke-Tests -Output Log -ResultsVariable Results
Invokes the test cases, outputting the log to the stream and assigning the results
to the global variable $Results.
.Link
Test-Case
#>
# Invoke all of the tests in a given path
function Invoke-Tests {
param (
[Alias('p')]
[string] $Path = '.',
[Alias('f')]
[string[]] $Filter,
[ValidateSet('Quiet', 'Log', 'Results', 'NUnit', 'Flat')]
[Alias('o')]
[string] $Output = 'Log',
[Alias('n')]
[string] $NUnit,
[Alias('x')]
[switch] $ExitCode,
[Alias('r')]
[switch] $Recurse,
[string] $ResultsVariable
)
try {
# initialize the global variables
$testFilter = @("*","*")
if ($Filter -ne $null) { $testFilter = $testFilter + @($Filter) }
$testOutput = $Output
# invoke the tests
$results = Test-Case "Invoking" (Resolve-Path $Path) -Group -OutputResults {
# find all of the child-items that match
Get-ChildItem $Path -Filter "*.Tests.ps1" -Recurse:$Recurse |% {
Test-Case "Invoking" $_.FullName -Group {
. $_.FullName
}
}
}
# write the final results
if ($results.Failed -gt 0) {
$color = 'Red'
}
else {
$color = 'Green'
}
Write-TestLog "$($results.Count) tests. $($results.Passed) passed, $($results.Failed) failed." $color
# output the results if requested
if ($Output -eq 'Results') { $Results }
elseif ($Output -eq 'NUnit') { $Results | Format-AsNUnit }
elseif ($Output -eq 'Flat') { $Results | Format-AsFlatTests }
# if they want to write nunit to a file, we can do that too
if ($NUnit) {
$Results | Format-AsNUnit | Set-Content $NUnit
}
# if they want the results in a variable, do that
if ($ResultsVariable) {
"`$global:$ResultsVariable = `$Results" | iex
}
# set the exit code if requested
if ($ExitCode) {
$host.SetShouldExit($results.Failed)
}
}
finally {
$testFilter = $null
$testOutput = 'Log'
}
}
<#
.Synopsis
Runs a set of test cases.
.Description
Runs a set of test cases. In general, you will not call this directly, but you would use one of the following:
TestFixture, TestCase, TestScope, Describing, Given, It.
.Parameter Call
The name of the method used to call the case. This is used for display purposes only.
.Parameter Name
The name of the test group or case. This is used for display, and for filtering when used with Invoke-Tests.
.Parameter ScriptBlock
The test script block to execute. This can contain and Setup, TearDown blocks, as well as test code to execute.
.Parameter Group
This switch controls whether the ScriptBlock is executed to setup the case or to run the test case.
For grouping constructs like TestScope, TestFixture, Describing, Given, the Group switch should be set,
and the ScriptBlock is executed immediately.
For test constructs like TestCase and It, the Group switch should not be set, and the ScriptBlock
is deferred until the outer group Setup blocks are executed.
This is all handled for you if you use one of the other functions.
.Parameter DataDriven
This switch tells PSate to turn off its normal way of calling the setup and teardown blocks once per test,
and instead call the entire block once only. This is intended to allow nesting of test cases in loops.
At small numbers of cases (under a few hundred) then this switch is not too important, but at large numbers
of test cases, this switch can decrease test times by several orders of magnitude.
.Example
Test-Case "Math" -Group {
Test-Case "Add" {
1 + 1 | Should Be 2
}
Test-Case "Subtract" {
1 - 1 | Should Be 0
}
}
Defines a group of Math test cases, with an Add and a Subtract case.
.Example
Test-Case "Math Tables" -Group -DataDriven {
1..12 | % {
Test-Case "Three-times tables" {
$_ * 3 | Should Be $_ + $_ + $_
}
}
}
Defines a group of Math Tables test cases, with twelve multiplication cases.
.Link
TestFixture
.Link
TestCase
.Link
TestScope
.Link
Describing
.Link
Given
.Link
It
#>
function Test-Case {
param (
[Parameter(Mandatory=$true)] [string] $Call,
[Parameter(Mandatory=$true)] [string] $Name,
[Parameter(Mandatory=$true)] [scriptblock] $ScriptBlock,
[switch] $Group,
[switch] $DataDriven,
[switch] $OutputResults
)
# save the test context to restore later
$local:oldTestContext = $global:testContext
$local:oldTestScriptPath = $global:TestScriptPath
try {
# create a new test context for this
$testContext = New-TestContext $Call $Name $testContext -Group:$Group -DataDriven:$DataDriven
# save the script path on the context
# find the closest point in the stack not in our modules
$invocation = (Get-PSCallStack | Where { $_.Location -notmatch '^((PSate)|(PSMock)).psm1:' } | Select -First 1)
if ($invocation -and $invocation.ScriptName) {
$global:TestScriptPath = Split-Path -Parent $invocation.ScriptName
}
$testContext.ScriptPath = $global:TestScriptPath
# if this is the root item or the user wants to run all tests once (data driven) or it is our turn to execute, then run the test
if (($testContext.Parent -eq $null) -or $testContext.Parent.DataDriven -or ($testContext.Parent.TestIndex -eq $testContext.Parent.TestPass)) {
if (($testContext.Depth -lt $testFilter.length) -and ($testFilter[$testContext.Depth] -ne '*') -and ($testFilter[$testContext.Depth] -ne $testContext.Name)) {
# don't run tests that are filtered out
}
elseif ($Group) {
Run-Group $testContext $ScriptBlock
}
else {
Execute-Test $testContext $ScriptBlock
}
# append the results to the parent
if ($testContext.Parent) {
$testContext.Parent.Cases += $testContext
}
}
# go to the next test
if ($testContext.Parent) {
$testContext.Parent.TestIndex++
}
# output the results if they asked for it
if ($OutputResults) {
return $testContext
}
}
finally {
$global:testContext = $local:oldTestContext
$global:TestScriptPath = $local:oldTestScriptPath
}
}
# Run a group of tests
function Run-Group {
param (
$Context,
[scriptblock] $ScriptBlock
)
try {
# this is a container, so run the sub-tests
Write-TestLog "$($Context.Call) $($Context.Name)" White
if ($Context.DataDriven) {
# Run the test once, since the user is handling the looping.
$Context.TestIndex = 0
Execute-ScriptBlock $Context $ScriptBlock
$Context.TestIndex = 1
$Context.TestPass = 1
} else {
# run the script until all of the inner cases have run
# the script block will execute at least once, even if there are no tests
$Context.TestPass = 0
$Context.TestIndex = 1
while ($Context.TestPass -lt $Context.TestIndex) {
$Context.TestIndex = 0
Execute-ScriptBlock $Context $ScriptBlock
$Context.TestPass++
}
}
}
finally {
Cleanup-Test $Context
# accumulate the results
$Context.Time = $Context.Cases |% { $_.Time } | Measure-Object -Sum |% { $_.Sum }
$Context.Count = $Context.Cases |% { $_.Count } | Measure-Object -Sum |% { $_.Sum }
$Context.Passed = $Context.Cases |% { $_.Passed } | Measure-Object -Sum |% { $_.Sum }
$Context.Failed = $Context.Cases |% { $_.Failed } | Measure-Object -Sum |% { $_.Sum }
$Context.Success = ($Context.Failed -eq 0)
if ($Context.Success) {
$Context.Result = 'Success'
}
else {
$Context.Result = 'Failure'
}
}
}
# Execute a single test.
function Execute-Test {
param (
$Context,
[scriptblock] $ScriptBlock
)
# execute the case with measurement and capture the error
$time = Measure-Command {
try {
Execute-ScriptBlock $Context $ScriptBlock
# hooray
$Context.Success = $true
$Context.Result = 'Success'
$Context.Passed = $Context.Passed + 1
}
catch {
# boo
$Context.Exception = $_
$Context.StackTrace = (Get-FilteredStackTrace $_)
$Context.Result = 'Failure'
$Context.Success = $false
$Context.Failed = $Context.Failed + 1
}
finally {
Cleanup-Test $Context
}
}
$Context.Time = $time.TotalSeconds
# output the results
$Context.Count = $Context.Count + 1
if ($Context.Success) {
Write-TestLog "[+] $($Context.Call) $($Context.Name) [$(Format-Time $Context.Time)]" Green
}
else {
Write-TestLog "[-] $($Context.Call) $($Context.Name) [$(Format-Time $Context.Time)]" Red
Write-TestLog " $($Context.Exception)" Red
$Context.StackTrace |% { Write-TestLog " $_" Red }
}
}
function Execute-ScriptBlock {
param (
$Context,
[scriptblock] $ScriptBlock
)
# create a mock context, test context, and variable scope
MockContext {
try {
$testContext = $Context
& $ScriptBlock | Write-TestLog
}
finally {
$testContext = $Context.Parent
}
}
}
function Cleanup-Test {
param (
$Context
)
# auto-teardown - clean up any folders and files
[Array]::Reverse($Context.Items)
$Context.Items | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
$Context.Items = @()
}
################################################
# Setup and TearDown
################################################
<#
.Synopsis
Defines a Setup block that is executed before each inner test.
.Description
Defines a Setup block that is executed before each inner test.
A Setup block can be added at any level, and is executed once for each inner test block.
.Parameter ScriptBlock
The setup block that is used to initialize each test case.
.Example
Describing "Math" {
Given "1 and 1" {
TestSetup {
$x = 1
$y = 1
}
It "adds them" {
$x + $y | Should Be 2
}
It "subtracts them" {
$x - $y | Should Be 0
}
}
}
Creates a test case with a TestSetup block. The TestSetup block is run once for each It block.
.Link
TestFixture
.Link
TestCase
.Link
TestScope
.Link
Describing
.Link
Given
.Link
It
.Link
TestTearDown
#>
function TestSetup {
param (
[Parameter(Mandatory=$true)] [scriptblock] $ScriptBlock
)
if (!$testContext) {
throw "Test Setup can only be called from within a test context"
}
if (!$testContext.Group) {
throw "Test Setup can only be called from within a grouping test context"
}
. $ScriptBlock
}
<#
.Synopsis
Defines a TearDown block that is executed after each inner test.
.Description
Defines a TearDown block that is executed after each inner test.
A TearDown block can be added at any level, and is executed once for each inner test block.
The TearDown block is guaranteed to execute regardless of the outcome of the test.
.Parameter ScriptBlock
The teardown block that is used to initialize each test case.
.Example
Describing "FileStuff" {
Given "a temp file" {
TestSetup {
$file = New-Item -Name "temp.file" -Path $env:temp -Type File -Force
}
It "does something with the file" {
# something
}
TestTearDown {
$file | Remove-Item -Force
}
}
}
Creates a test case with a TestTearDown block. The TestTearDown block is run once after each It block.
.Link
TestFixture
.Link
TestCase
.Link
TestScope
.Link
Describing
.Link
Given
.Link
It
.Link
TestSetup
#>
function TestTearDown {
param (
[Parameter(Mandatory=$true)] [scriptblock] $ScriptBlock
)
if (!$testContext) {
throw "Test TearDown can only be called from within a test context"
}
if (!$testContext.Group) {
throw "Test TearDown can only be called from within a grouping test context"
}
. $ScriptBlock
}
################################################
# Resource helper functions
################################################
<#
.Synopsis
Creates and returns a temp folder that is automatically deleted at the end of the test.
.Description
Creates and returns a temp folder that is automatically deleted at the end of the test.
Any files created in the folder are also deleted at the end of the test.
.Example
Describing "FileStuff" {
Given "nothing" {
It "can create a test folder" {
# create a folder
$folder = New-TestFolder
# do something with it
}
}
}
Creates a test case where a temporary folder is created. The folder and its contents are
automatically deleted in the TearDown phase of the test case.
.Link
New-TestFile
.Link
Register-TestCleanup
#>
function New-TestFolder {
if (!$testContext) { throw "Cannot create a TestFolder outside of a test context." }
# create a new folder name
$guid = [Guid]::NewGuid().ToString()
# create the folder and register it for cleanup
New-Item -Name $guid -Path $env:Temp -Type Container -Force | Register-TestCleanup -PassThru
}
<#
.Synopsis
Creates and returns a temp file that is automatically deleted at the end of the test.
.Description
Creates and returns a temp file that is automatically deleted at the end of the test.
.Parameter Name
The name of the file to create. If not specified, a guid is used as the filename.
.Parameter Path
The name of the directory to create the file in. If not specified, the current temp folder is used.
.Example
Describing "FileStuff" {
Given "nothing" {
It "can create a test file" {
# create a file
$file = New-TestFile
# do something with it
}
}
}
Creates a test case where a temporary file is created. The file and its contents are
automatically deleted in the TearDown phase of the test case.
.Link
New-TestFolder
.Link
Register-TestCleanup
#>
function New-TestFile {
param (
[string] $Name,
[string] $Path
)
if (!$testContext) { throw "Cannot create a TestFile outside of a test context." }
# if no name, then use a guid
if (!$Name) {
$Name = [Guid]::NewGuid().ToString()
}
# if no path, then use the temp folder
if (!$Path) {
$Path = $env:Temp
}
# create a file with the given name and register it for cleanup
New-Item -Name $Name -Path $Path -Type File -Force | Register-TestCleanup -PassThru
}
<#
.Synopsis
Registers the given object to automatically get deleted at the end of the test.
.Description
Registers the given object to automatically get deleted at the end of the test.
The object and all of its contents are automatically deleted.
.Parameter Object
The object to register for cleanup.
.Parameter PassThru
If this switch is set, the object is automatically output to the stream.
.Example
Describing "RegistryStuff" {
Given "nothing" {
It "can create a test registry key" {
# create a file
$reg = new-item -path hkcu:\Environment\TestNew | Register-TestCleanup -PassThru
# do something with it
}
}
}
Creates a test case where a temporary registry key is created. The key and its contents are
automatically deleted in the TearDown phase of the test case.
.Link
New-TestFolder
.Link
New-TestFile
#>
function Register-TestCleanup {
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)] [object[]] $Object,
[switch] $PassThru
)
process {
if (!$testContext) { throw "Cannot register for test cleanup outside of a test context." }
$testContext.Items += $Object
# if working in passthru mode, output the object
if ($PassThru) {
$Object
}
}
}
################################################
# Test Context functions
################################################
# Creates a new testcontext and initializes its members properly
function New-TestContext {
param (
[string] $Call,
[string] $Name,
$Parent,
[switch] $Group,
[switch] $DataDriven
)
$context = @{
"Call" = $Call
"Name" = $Name
"Parent" = $Parent
"Group" = $Group
"DataDriven" = $DataDriven
"Cases" = @()
# cleanup items
"Items" = @()
# results
"Success" = $null
"Time" = $null
"Exception" = $null
"Count" = 0
"Passed" = 0
"Failed" = 0
}
if ($Parent) {
$context.Depth = $Parent.Depth + 1
}
else {
$context.Depth = 0
}
return $context
}
################################################
# Logging and output functions
################################################
# properly formats a string for output into the test log
function Write-TestLog {
param (
[Parameter(ValueFromPipeline=$true)][string[]] $Object,
[consolecolor] $Color = 'Yellow'
)
process {
if ($testOutput -eq 'Log') {
"$(" " * $testContext.Depth * 2)$Object" | Write-Host -ForegroundColor $Color
}
}
}
# formats a result object as an NUnit output
function Format-AsFlatTests {
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)] $TestResults
)
if ($TestResults.Group) {
$TestResults.Cases |% { $_ | Format-AsFlatTests }
} else {
$TestResults
}
}
################################################
# NUnit Output functions
################################################
# invokes a string template with replacements
function Invoke-Template {
param (
$Data,
[string] $template
)
$Data |% { $template -replace '"','`"' -replace '^`"','"' -replace '`"$','"' | iex }
}
# formats a result object as an NUnit output
function Format-AsNUnit {
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)] $TestResults
)
Invoke-Template $TestResults $testResultsTemplate
}
$testResultsTemplate = @'
"
<test-results name="PSate" total="$($_.Count)" errors="0" failures="$($_.Failed)" not-run="0" inconclusive="0" ignored="0" skipped="0" invalid="0" date="$(Get-Date -format "yyyy-MM-dd")" time="$(Get-Date -format "HH:mm:ss")">
$(Invoke-Template (Get-WmiObject Win32_OperatingSystem) $environmentTemplate)
<culture-info
current-culture="$(([System.Threading.Thread]::CurrentThread.CurrentCulture).Name)"
current-uiculture="$(([System.Threading.Thread]::CurrentThread.CurrentCulture).Name)"
/>
$(Invoke-Template $_ $testSuiteTemplate)
</test-results>
"
'@
$environmentTemplate = @'
"
<environment
nunit-version="2.5.8.0"
clr-version="$([System.Environment]::Version)"
os-version="$($_.Version)"
platform="$($_.Name)"
cwd="$((Get-Location).Path)"
machine-name="$($env:ComputerName)"
user="$($env:UserName)"
user-domain="$($env:UserDomain)"
/>
"
'@
$testSuiteTemplate = @'
"
<test-suite type="Powershell" name="$($_.Name)" executed="True" result="$($_.Result)" success="$($_.Success)" time="$($_.Time)" asserts="$($_.Failed)">
<results>
$($_.Cases |? { $_.Cases.Length -gt 0 } |% { Invoke-Template $_ $testSuiteTemplate })
$($_.Cases |? { $_.Cases.Length -eq 0 } |% { Invoke-Template $_ $testCaseTemplate })
</results>
</test-suite>
"
'@
$testCaseTemplate = @'
"
<test-case name="$($_.Name)" executed="True" result="$($_.Result)" success="$($_.Success)" time="$($_.Time)" asserts="$($_.Failed)">
$($_ |? { $_.Failed -gt 0 } |% { Invoke-Template $_ $testCaseFailureTemplate })
$($_.Cases |% { Invoke-Template $_ $testCaseTemplate })
</test-case>
"
'@
$testCaseFailureTemplate = @'
"
<failure>
<message><![CDATA[$($_.Exception.ToString())]]></message>
<stack-trace><![CDATA[$_.StackTrace]]></stack-trace>
</failure>
"
'@
################################################
# Internal Utility functions
################################################
# Make the number of milliseconds readable
function Format-Time {
param (
$Seconds
)
if ($Seconds -gt 0.99) {
$time = [math]::Round($Seconds, 2)
$unit = "s"
}
else {
$time = [math]::Floor($Seconds * 1000)
$unit = "ms"
}
return "$time $unit"
}
# Filter a stacktrace and rip out the PSST lines to make it more readable
function Get-FilteredStackTrace {
param (
$Exception
)
if ($PSVersionTable.PSVersion.Major -lt 3) {
$Exception
}
else {
$Exception.ScriptStackTrace.Split("`n") |
? { $_ -notmatch 'PSate.psm1:' } |
? { $_ -notmatch 'PShould.psm1:' } |
? { $_ -notmatch 'PSMock.psm1:' } |
? { $_ -notmatch 'psake.psm1:' }
}
}
################################################
# TDD-style functions
################################################
<#
.Synopsis
Groups a set of Test Cases
.Description
Groups a set of TestCases under a given name.
.Example
TestFixture "TheScriptToTest" {
TestCase "The Test" {
Do-Something | Should Be "Work"
}
}
Defines a test fixture and a case in the fixture.
.Example
TestFixture "TheScriptToTest" {
TestFixture "SubGroup" {
TestCase "The Test" {
Do-Something | Should Be "Work"
}
}
}
Defines a test fixture, a sub-group and a case in the fixture.
#>
function TestFixture {
param (
[Parameter(Mandatory=$true)] [string] $Name,
[Parameter(Mandatory=$true)] [scriptblock] $ScriptBlock,
[switch] $OutputResults
)
Test-Case "Fixture" @args @PSBoundParameters -Group
}
function EachTestFixture {
param (
[Parameter(Mandatory=$true)] [string] $Name,
[Parameter(Mandatory=$true)] [scriptblock] $ScriptBlock,
[switch] $OutputResults
)
Test-Case "Fixture" @args @PSBoundParameters -Group -DataDriven
}
<#
.Synopsis
Defines a Test Case to execute.
.Description
Defines a Test Case to execute.
.Example
TestFixture "TheScriptToTest" {
TestCase "The Test" {
Do-Something | Should Be "Work"
}
}
Defines a test fixture and a case in the fixture.
#>
function TestCase {
param (
[Parameter(Mandatory=$true)] [string] $Name,
[Parameter(Mandatory=$true)] [scriptblock] $ScriptBlock,
[switch] $OutputResults
)
Test-Case "Case" @args @PSBoundParameters
}
################################################
# BDD-style functions
################################################
<#
.Synopsis
Groups a set of Test Cases
.Description