-
-
Notifications
You must be signed in to change notification settings - Fork 96
/
Expecto.fs
1915 lines (1683 loc) · 73.8 KB
/
Expecto.fs
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
namespace Expecto
#nowarn "46"
open System
open System.Linq
open System.Runtime.CompilerServices
open System.Reflection
open System.Diagnostics
open System.Threading
open System.Threading.Tasks
// When exposing Extension Methods, you should declare an assembly-level attribute (in addition to class and method)
[<assembly:Extension>]
do
()
// TODO: move to internal
type SourceLocation =
{ sourcePath : string
lineNumber : int }
with
static member empty =
{ sourcePath = ""
lineNumber = 0 }
type FsCheckConfig =
/// The maximum number of tests that are run.
{ maxTest: int
/// The size to use for the first test.
startSize: int
/// The size to use for the last test, when all the tests are passing. The size increases linearly between Start- and EndSize.
endSize: int
/// If set, the seed to use to start testing. Allows reproduction of previous runs.
replay: (int * int) option
/// The Arbitrary instances on this class will be merged in back to front order, i.e. instances for the same generated type at the front
/// of the list will override those at the back. The instances on Arb.Default are always known, and are at the back (so they can always be
/// overridden)
arbitrary: Type list
/// Callback when the test case had input parameters generated.
receivedArgs: FsCheckConfig
-> (* test name *) string
-> (* test number *) int
-> (* generated arguments *) obj list
-> Async<unit>
/// Callback when the test case was successfully shrunk
successfulShrink: FsCheckConfig
-> (* test name *) string
-> (* shrunk new arguments *) obj list
-> Async<unit>
/// Callback when the test case has finished
finishedTest: FsCheckConfig
-> (* test name *) string
-> Async<unit>
}
static member defaultConfig =
{ maxTest = 200
startSize = 1
endSize = 100
replay = None
arbitrary = []
receivedArgs = fun _ _ _ _ -> async.Return ()
successfulShrink = fun _ _ _ -> async.Return ()
finishedTest = fun _ _ -> async.Return ()
}
/// Actual test function; either an async one, or a synchronous one.
type TestCode =
| Sync of stest: (unit -> unit)
| SyncWithCancel of stest: (CancellationToken -> unit)
| Async of atest: Async<unit>
| AsyncFsCheck of testConfig: FsCheckConfig option *
stressConfig: FsCheckConfig option *
test: (FsCheckConfig -> Async<unit>)
/// The parent state (watching the tests as a tree structure) will influence
/// the child tests state. By following rules, if parent test state is:
/// - Focused will elevate all Normal child tests to Focused.
/// Focused and Pending child tests will not change state(behavior)
/// - Normal will not influence the child tests states(behavior).
/// - Pending will elevate all Normal and Focused child tests to Pending.
/// Pending child test will not change state(behavior)
type FocusState =
/// The default state of a test that will be evaluated
| Normal
/// The state of a test that will be ignored by Expecto
| Pending
/// The state of a test that will be evaluated
/// All other test marked with Normal or Pending will be ignored
| Focused
type SequenceMethod =
| Synchronous
| SynchronousGroup of string
| InParallel
/// Test tree – this is how you compose your tests as values. Since
/// any of these can act as a test, you can pass any of these DU cases
/// into a function that takes a Test.
type Test =
/// A test case is a function from unit to unit, that can be executed
/// by Expecto to run the test code.
| TestCase of code:TestCode * state:FocusState
/// A collection/list of tests.
| TestList of tests:Test list * state:FocusState
/// A labelling of a Test (list or test code).
| TestLabel of label:string * test:Test * state:FocusState
/// Require sequenced for a Test (list or test code).
| Sequenced of SequenceMethod * Test
// TODO: move to internal namespace
type ExpectoException(msg) = inherit Exception(msg)
// TODO: move to internal namespace
type AssertException(msg) = inherit ExpectoException(msg)
// TODO: move to internal namespace
type FailedException(msg) = inherit ExpectoException(msg)
// TODO: move to internal namespace
type IgnoreException(msg) = inherit ExpectoException(msg)
/// Represents an error during test discovery.
type TestDiscoveryException(msg) = inherit ExpectoException(msg)
/// Represents a null test value during test discovery.
type NullTestDiscoveryException(msg) = inherit TestDiscoveryException(msg)
/// Marks a top-level test for scanning
/// The test will run even if PTest is also present.
[<AttributeUsage(AttributeTargets.Method ||| AttributeTargets.Property ||| AttributeTargets.Field)>]
type TestsAttribute() = inherit Attribute()
/// Allows to mark a test as Pending (will be skipped/ignored if no other TestAttribute is present)
/// Is a fast way to exclude some tests from running.
/// If FTest or Test is also present then this attribute will be ignored.
[<AttributeUsage(AttributeTargets.Method ||| AttributeTargets.Property ||| AttributeTargets.Field)>]
type PTestsAttribute() = inherit Attribute()
/// Allows to mark a test as FocusState.Focused (will be run and will change the behavior for
/// all other tests marked as FocusState.Normal to be ignored)
/// Is a fast way to exclude some tests from running.
/// The test will run even if PTest is also present. Have priority over TestAttribute.
[<AttributeUsage(AttributeTargets.Method ||| AttributeTargets.Property ||| AttributeTargets.Field)>]
type FTestsAttribute() = inherit Attribute()
type private TestNameHolder() =
[<ThreadStatic;DefaultValue>]
static val mutable private name : string
static member Name
with get () = TestNameHolder.name
and set name = TestNameHolder.name <- name
[<AutoOpen>]
module internal Helpers =
let inline dispose (d:IDisposable) = d.Dispose()
let inline addFst a b = a,b
let inline addSnd b a = a,b
let inline commaString (i:int) = i.ToString("#,##0")
open System.Text.RegularExpressions
let rx = lazy Regex(" at (.*) in (.*):line (\d+)", RegexOptions.Compiled ||| RegexOptions.Multiline)
let stackTraceToString s = rx.Value.Replace(s, "$2($3,1): $1")
let exnToString (e: Exception) = stackTraceToString (e.ToString())
module Seq =
let cons x xs = seq { yield x; yield! xs }
module List =
let inline singleton x = [x]
module Option =
let orFun fn =
function | Some a -> a | None -> fn()
let orDefault def =
function | Some a -> a | None -> def
type Type with
static member TryGetType t =
try
Type.GetType(t, true) |> Some
with _ ->
None
type ResizeMap<'k,'v> = Collections.Generic.Dictionary<'k,'v>
let matchFocusAttributes = function
| "Expecto.FTestsAttribute" -> Some (1, Focused)
| "Expecto.TestsAttribute" -> Some (2, Normal)
| "Expecto.PTestsAttribute" -> Some (3, Pending)
| _ -> None
let allTestAttributes = Set.ofList [ (typeof<FTestsAttribute>).FullName
(typeof<TestsAttribute>).FullName
(typeof<PTestsAttribute>).FullName]
type MemberInfo with
member m.HasAttributePred (pred: Type -> bool) =
m.GetCustomAttributes true
|> Seq.filter (fun a -> pred(a.GetType()))
|> Seq.length |> (<) 0
member m.HasAttributeType (attr: Type) =
m.HasAttributePred ((=) attr)
member m.HasAttribute (attr: string) =
m.HasAttributePred (fun (t: Type) -> t.FullName = attr)
member m.GetAttributes (attr: string) : Attribute seq =
m.GetCustomAttributes true
|> Seq.filter (fun a -> a.GetType().FullName = attr)
|> Seq.cast
member m.MatchTestsAttributes () =
m.GetCustomAttributes true
|> Seq.map (fun t -> t.GetType().FullName)
|> Set.ofSeq
|> Set.intersect allTestAttributes
|> Set.toList
|> List.choose matchFocusAttributes
|> List.sortBy fst
|> List.map snd
|> List.tryFind (fun _ -> true)
module internal Async =
let map fn a =
async {
let! v = a
return fn v
}
let bind fn a =
async.Bind(a, fn)
let foldSequentiallyWithCancel (ct:CancellationToken) folder state (s:_ seq) =
async {
let mutable state = state
let tcs = TaskCompletionSource()
use _ = Action tcs.SetResult |> ct.Register
let tasks : Task[] = [| null; tcs.Task |]
use e = s.GetEnumerator()
while not ct.IsCancellationRequested && e.MoveNext() do
let task = Async.StartAsTask e.Current
tasks.[0] <- task :> Task
if Task.WaitAny tasks = 0 then
state <- folder state task.Result
return state
}
let foldSequentially folder state (s:_ seq) =
foldSequentiallyWithCancel CancellationToken.None folder state s
let foldParallelWithCancel maxParallelism (ct:CancellationToken) folder state (s:_ seq) =
async {
let mutable state = state
use e = s.GetEnumerator()
if e.MoveNext() then
let mutable tasks = [Async.StartAsTask e.Current]
while not(ct.IsCancellationRequested || List.isEmpty tasks) do
if List.length tasks = maxParallelism || not(e.MoveNext()) then
while not( tasks |> List.exists (fun t -> t.IsCompleted)
|| ct.IsCancellationRequested) do
do! Async.Sleep 10
tasks |> List.tryFindIndex (fun t -> t.IsCompleted)
|> Option.iter (fun i ->
let a,b = List.splitAt i tasks
state <- (List.head b).Result |> folder state
tasks <- a @ List.tail b
)
else tasks <- Async.StartAsTask e.Current :: tasks
return state
}
// TODO: move to internal
[<ReferenceEquality>]
type FlatTest =
{ name : string
test : TestCode
state : FocusState
focusOn : bool
sequenced : SequenceMethod }
member x.shouldSkipEvaluation =
match x.focusOn, x.state with
| _, Pending -> Some "The test or one of its parents is marked as Pending"
| true, Normal -> Some "The test is skipped because other tests are Focused"
| _ -> None
[<CompilationRepresentationAttribute(CompilationRepresentationFlags.ModuleSuffix)>]
module Test =
/// Compute the child test state based on parent test state
let computeChildFocusState parentState childState =
match parentState, childState with
| Focused, Pending -> Pending
| Pending, _ -> Pending
| Focused, _ -> Focused
| Normal, _ -> childState
/// Is focused set on at least one test
let rec isFocused test =
match test with
| TestLabel (_,_,Focused)
| TestCase (_,Focused)
| TestList (_,Focused) -> true
| TestLabel (_,_,Pending)
| TestList (_,Pending)
| TestCase _ -> false
| TestLabel (_,test,Normal)
| Sequenced (_,test) -> isFocused test
| TestList (tests,Normal) -> List.exists isFocused tests
/// Flattens a tree of tests
let toTestCodeList test =
let isFocused = isFocused test
let rec loop parentName testList parentState sequenced =
function
| TestLabel (name, test, state) ->
let fullName =
if String.IsNullOrEmpty parentName
then name
else parentName + "/" + name
loop fullName testList (computeChildFocusState parentState state) sequenced test
| TestCase (test, state) ->
{ name=parentName
test=test
state=computeChildFocusState parentState state
focusOn = isFocused
sequenced=sequenced } :: testList
| TestList (tests, state) -> List.collect (loop parentName testList (computeChildFocusState parentState state) sequenced) tests
| Sequenced (sequenced,test) -> loop parentName testList parentState sequenced test
loop null [] Normal InParallel test
/// Change the FocusState by appling the old state to a new state
/// Note: this is not state replacement!!!
/// Used in replaceTestCode and the order is intended for scenario:
/// 1. User wants to automate some tests and his intent is not to change
/// the test state (use Normal), so this way the current state will be preserved
/// Don't see the use case: the user wants to automate some tests and wishes
/// to change the test states
let rec translateFocusState newFocusState =
function
| TestCase (test, oldFocusState) -> TestCase(test, computeChildFocusState oldFocusState newFocusState)
| TestList (testList, oldFocusState) -> TestList(testList, computeChildFocusState oldFocusState newFocusState)
| TestLabel (label, test, oldFocusState) -> TestLabel(label, test, computeChildFocusState oldFocusState newFocusState)
| Sequenced (sequenced,test) -> Sequenced (sequenced,translateFocusState newFocusState test)
/// Recursively replaces TestCodes in a Test.
/// Check translateFocusState for focus state behaviour description.
let rec replaceTestCode (f:string -> TestCode -> Test) =
function
| TestLabel (label, TestCase (test, childState), parentState) ->
f label test
|> translateFocusState (computeChildFocusState parentState childState)
| TestCase (test, state) ->
f null test
|> translateFocusState state
| TestList (testList, state) -> TestList (List.map (replaceTestCode f) testList, state)
| TestLabel (label, test, state) -> TestLabel (label, replaceTestCode f test, state)
| Sequenced (sequenced,test) -> Sequenced (sequenced,replaceTestCode f test)
/// Filter tests by name.
let filter pred =
toTestCodeList
>> List.filter (fun t -> pred t.name)
>> List.map (fun t ->
let test = TestLabel (t.name, TestCase (t.test, t.state), t.state)
match t.sequenced with
| InParallel ->
test
| s ->
Sequenced (s,test)
)
>> (fun x -> TestList (x,Normal))
/// Applies a timeout to a test.
let timeout timeout (test: TestCode) : TestCode =
let timeoutAsync testAsync =
async {
try
let! async = Async.StartChild(testAsync, timeout)
do! async
with :? TimeoutException ->
let ts = TimeSpan.FromMilliseconds (float timeout)
raise <| AssertException(sprintf "Timeout (%A)" ts)
}
match test with
| Sync test -> async { test() } |> timeoutAsync |> Async
| SyncWithCancel test ->
SyncWithCancel (fun ct ->
Async.StartImmediate(async { test ct } |> timeoutAsync)
)
| Async test -> timeoutAsync test |> Async
| AsyncFsCheck (testConfig, stressConfig, test) ->
AsyncFsCheck (testConfig, stressConfig, test >> timeoutAsync)
// TODO: make internal?
module Impl =
open Expecto.Logging
open Expecto.Logging.Message
open Helpers
open Mono.Cecil
let mutable logger = Log.create "Expecto"
let setLogName name = logger <- Log.create name
type TestResult =
| Passed
| Ignored of string
| Failed of string
| Error of exn
override x.ToString() =
match x with
| Passed -> "Passed"
| Ignored reason -> "Ignored: " + reason
| Failed error -> "Failed: " + error
| Error e -> "Exception: " + exnToString e
member x.tag =
match x with
| Passed -> 0
| Ignored _ -> 1
| Failed _ -> 2
| Error _ -> 3
member x.isPassed =
match x with
| Passed -> true
| _ -> false
member x.isIgnored =
match x with
| Ignored _ -> true
| _ -> false
member x.isFailed =
match x with
| Failed _ -> true
| _ -> false
member x.isException =
match x with
| Error _ -> true
| _ -> false
static member max (a:TestResult) (b:TestResult) =
if a.tag>=b.tag then a else b
type TestSummary =
{ result : TestResult
count : int
meanDuration : float
maxDuration : float
totalVariance : float }
member x.duration = TimeSpan.FromMilliseconds x.meanDuration
static member single result duration =
{ result = result
count = 1
meanDuration = duration
maxDuration = duration
totalVariance = 0.0 }
static member (+)(s:TestSummary,(r,d):TestResult*float) =
let n,m,v = Statistics.updateIntermediateStatistics
(s.count,s.meanDuration,s.totalVariance) d
{ result = TestResult.max s.result r
count = n
meanDuration = m
maxDuration = max s.maxDuration d
totalVariance = v }
type TestRunSummary =
{ results : (FlatTest*TestSummary) list
duration : TimeSpan
maxMemory : int64
memoryLimit : int64
timedOut : FlatTest list
}
static member fromResults results =
{ results = results
duration =
results
|> List.sumBy (fun (_,r:TestSummary) -> r.meanDuration)
|> TimeSpan.FromMilliseconds
maxMemory = 0L
memoryLimit = 0L
timedOut = [] }
member x.passed = List.filter (fun (_,r) -> r.result.isPassed) x.results
member x.ignored = List.filter (fun (_,r) -> r.result.isIgnored) x.results
member x.failed = List.filter (fun (_,r) -> r.result.isFailed) x.results
member x.errored = List.filter (fun (_,r) -> r.result.isException) x.results
member x.errorCode =
(if List.isEmpty x.failed then 0 else 1) |||
(if List.isEmpty x.errored then 0 else 2) |||
(if x.maxMemory <= x.memoryLimit then 0 else 4) |||
(if List.isEmpty x.timedOut then 0 else 8)
member x.successful = x.errorCode = 0
let createSummaryMessage (summary: TestRunSummary) =
let handleLineBreaks (elements:(FlatTest*TestSummary) seq) =
elements
|> Seq.map (fun (n,_) -> "\n\t" + n.name)
|> String.Concat
let passed = summary.passed |> handleLineBreaks
let passedCount = List.sumBy (fun (_,r) -> r.count) summary.passed |> commaString
let ignored = summary.ignored |> handleLineBreaks
let ignoredCount = List.sumBy (fun (_,r) -> r.count) summary.ignored |> commaString
let failed = summary.failed |> handleLineBreaks
let failedCount = List.sumBy (fun (_,r) -> r.count) summary.failed |> commaString
let errored = summary.errored |> handleLineBreaks
let erroredCount = List.sumBy (fun (_,r) -> r.count) summary.errored |> commaString
let digits =
[passedCount; ignoredCount; failedCount; erroredCount ]
|> List.map (fun x -> x.ToString().Length)
|> List.max
let align (s:string) offset = s.PadLeft(offset + digits)
eventX "EXPECTO?! Summary...\nPassed: {passedCount}{passed}\nIgnored: {ignoredCount}{ignored}\nFailed: {failedCount}{failed}\nErrored: {erroredCount}{errored}"
>> setField "passed" passed
>> setField "passedCount" (align passedCount 1)
>> setField "ignored" ignored
>> setField "ignoredCount" (align ignoredCount 0)
>> setField "failed" failed
>> setField "failedCount" (align failedCount 1)
>> setField "errored" errored
>> setField "erroredCount" (align erroredCount 0)
let createSummaryText (summary: TestRunSummary) =
createSummaryMessage summary Info
|> Expecto.Logging.Formatting.defaultFormatter
let logSummary (summary: TestRunSummary) =
createSummaryMessage summary
|> logger.logWithAck Info
let logSummaryWithLocation locate (summary: TestRunSummary) =
let handleLineBreaks (elements:(FlatTest*TestSummary) seq) =
let format (n:FlatTest,_) =
let location = locate n.test
sprintf "%s [%s:%d]" n.name location.sourcePath location.lineNumber
let text = elements |> Seq.map format |> String.concat "\n\t"
if text = "" then text else text + "\n"
let passed = summary.passed |> handleLineBreaks
let passedCount = List.sumBy (fun (_,r) -> r.count) summary.passed |> commaString
let ignored = summary.ignored |> handleLineBreaks
let ignoredCount = List.sumBy (fun (_,r) -> r.count) summary.ignored |> commaString
let failed = summary.failed |> handleLineBreaks
let failedCount = List.sumBy (fun (_,r) -> r.count) summary.failed |> commaString
let errored = summary.errored |> handleLineBreaks
let erroredCount = List.sumBy (fun (_,r) -> r.count) summary.errored |> commaString
let digits =
[passedCount; ignoredCount; failedCount; erroredCount ]
|> List.map (fun x -> x.ToString().Length)
|> List.max
let align (s:string) offset = s.PadLeft(offset + digits)
logger.logWithAck Info (
eventX "EXPECTO?! Summary...\nPassed: {passedCount}\n\t{passed}Ignored: {ignoredCount}\n\t{ignored}Failed: {failedCount}\n\t{failed}Errored: {erroredCount}\n\t{errored}"
>> setField "passed" passed
>> setField "passedCount" (align passedCount 1)
>> setField "ignored" ignored
>> setField "ignoredCount" (align ignoredCount 0)
>> setField "failed" failed
>> setField "failedCount" (align failedCount 1)
>> setField "errored" errored
>> setField "erroredCount" (align erroredCount 0))
/// Hooks to print report through test run
type TestPrinters =
{ /// Called before a test run (e.g. at the top of your main function)
beforeRun: Test -> Async<unit>
/// Called before atomic test (TestCode) is executed.
beforeEach: string -> Async<unit>
/// info
info: string -> Async<unit>
/// test name -> time taken -> unit
passed: string -> TimeSpan -> Async<unit>
/// test name -> ignore message -> unit
ignored: string -> string -> Async<unit>
/// test name -> other message -> time taken -> unit
failed: string -> string -> TimeSpan -> Async<unit>
/// test name -> exception -> time taken -> unit
exn: string -> exn -> TimeSpan -> Async<unit>
/// Prints a summary given the test result counts
summary : ExpectoConfig -> TestRunSummary -> Async<unit> }
static member printResult config (test:FlatTest) (result:TestSummary) =
match result.result with
| Passed -> config.printer.passed test.name result.duration
| Failed message -> config.printer.failed test.name message result.duration
| Ignored message -> config.printer.ignored test.name message
| Error e -> config.printer.exn test.name e result.duration
static member silent =
{ beforeRun = fun _ -> async.Zero()
beforeEach = fun _ -> async.Zero()
info = fun _ -> async.Zero()
passed = fun _ _ -> async.Zero()
ignored = fun _ _ -> async.Zero()
failed = fun _ _ _ -> async.Zero()
exn = fun _ _ _ -> async.Zero()
summary = fun _ _ -> async.Zero() }
static member defaultPrinter =
{ beforeRun = fun _tests ->
logger.logWithAck Info (eventX "EXPECTO? Running tests...")
beforeEach = fun n ->
logger.logWithAck Debug (
eventX "{testName} starting..."
>> setField "testName" n)
info = fun s ->
logger.logWithAck Info (eventX s)
passed = fun n d ->
logger.logWithAck Debug (
eventX "{testName} passed in {duration}."
>> setField "testName" n
>> setField "duration" d)
ignored = fun n m ->
logger.logWithAck Debug (
eventX "{testName} was ignored. {reason}"
>> setField "testName" n
>> setField "reason" m)
failed = fun n m d ->
async {
do! logger.logWithAck LogLevel.Error (
eventX "{testName} failed in {duration}. {message}"
>> setField "testName" n
>> setField "duration" d
>> setField "message" m)
ANSIOutputWriter.Flush()
}
exn = fun n e d ->
async {
do! logger.logWithAck LogLevel.Error (
eventX "{testName} errored in {duration}"
>> setField "testName" n
>> setField "duration" d
>> addExn e)
ANSIOutputWriter.Flush()
}
summary = fun _config summary ->
let spirit =
if summary.successful then "Success!" else String.Empty
let commonAncestor =
let rec loop ancestor (descendants : string list) =
match descendants with
| [] -> ancestor
| hd::tl when hd.StartsWith(ancestor)->
loop ancestor tl
| _ ->
if ancestor.Contains("/") then
loop (ancestor.Substring(0, ancestor.LastIndexOf "/")) descendants
else
"miscellaneous"
let parentNames =
summary.results
|> List.map (fun (flatTest, _) ->
if flatTest.name.Contains("/") then
flatTest.name.Substring(0, flatTest.name.LastIndexOf "/")
else
flatTest.name )
match parentNames with
| [x] -> x
| hd::tl ->
loop hd tl
| _ -> "miscellaneous" //we can't get here
logger.logWithAck Info (
eventX "EXPECTO! {total} tests run in {duration} for {name} – {passes} passed, {ignores} ignored, {failures} failed, {errors} errored. {spirit}"
>> setField "total" (List.sumBy (fun (_,r) -> r.count) summary.results |> commaString)
>> setField "name" commonAncestor
>> setField "duration" summary.duration
>> setField "passes" (List.sumBy (fun (_,r) -> r.count) summary.passed |> commaString)
>> setField "ignores" (List.sumBy (fun (_,r) -> r.count) summary.ignored |> commaString)
>> setField "failures" (List.sumBy (fun (_,r) -> r.count) summary.failed |> commaString)
>> setField "errors" (List.sumBy (fun (_,r) -> r.count) summary.errored |> commaString)
>> setField "spirit" spirit)
}
static member stressPrinter =
{ TestPrinters.defaultPrinter with
beforeRun = fun _tests ->
logger.logWithAck Info (
eventX "EXPECTO? Running stress testing...")
summary = fun config summary ->
let printResults =
List.map (fun (t,r) -> TestPrinters.printResult config t r) summary.results
|> Async.foldSequentially (fun _ _ -> ()) ()
let result =
if summary.maxMemory > summary.memoryLimit then
logger.logWithAck LogLevel.Error (
eventX "Maximum memory usage was {memory} KB and exceeded the limit set at {limit} KB.\nRunning tests:\n\t{timeout}"
>> setField "memory" (summary.maxMemory / 1024L |> int |> commaString)
>> setField "limit" (summary.memoryLimit / 1024L |> int |> commaString)
>> setField "timeout" (summary.timedOut |> Seq.map (fun t -> t.name) |> String.concat "\n\t"))
elif List.isEmpty summary.timedOut then
logger.logWithAck Info (
eventX "Maximum memory usage was {memory} KB (limit set at {limit} KB)."
>> setField "memory" (summary.maxMemory / 1024L |> int |> commaString)
>> setField "limit" (summary.memoryLimit / 1024L |> int |> commaString))
else
logger.logWithAck LogLevel.Error (
eventX "Deadlock timeout running tests:\n\t{timeout}"
>> setField "timeout" (summary.timedOut |> Seq.map (fun t -> t.name) |> String.concat "\n\t"))
async {
do! printResults
do! result
do! TestPrinters.defaultPrinter.summary config summary
}
}
static member summaryPrinter innerPrinter =
{ innerPrinter with
summary = fun config summary ->
innerPrinter.summary config summary
|> Async.bind (fun () -> logSummary summary) }
static member summaryWithLocationPrinter innerPrinter =
{ innerPrinter with
summary = fun config summary ->
innerPrinter.summary config summary
|> Async.bind (fun () -> logSummaryWithLocation config.locate summary) }
static member teamCityPrinter innerPrinter =
let formatName (n:string) =
n.Replace( "/", "." ).Replace( " ", "_" )
// https://confluence.jetbrains.com/display/TCD10/Build+Script+Interaction+with+TeamCity#BuildScriptInteractionwithTeamCity-Escapedvalues
let escape (msg: string) =
let replaced =
msg.Replace("|", "||")
.Replace("'", "|'")
.Replace("\r", "|r")
.Replace("\n", "|n")
.Replace("]", "|]")
.Replace("[", "|[")
let reg = Text.RegularExpressions.Regex(@"[^\u0020-\u007F]")
reg.Replace(replaced, fun m -> "|0x" + ((int m.Value.[0]).ToString("X4")))
let tcLog msgName props =
let tcMsg =
props
|> List.map (fun (k,v) -> sprintf "%s='%s'" k (escape v))
|> String.concat " "
|> sprintf "##teamcity[%s %s]" msgName
Global.lockSem (fun _ -> Console.WriteLine tcMsg)
{ beforeRun = fun _tests -> async {
do! innerPrinter.beforeRun _tests
tcLog "testSuiteStarted" [
"name", "ExpectoTestSuite" ] }
beforeEach = fun n -> async {
do! innerPrinter.beforeEach n
tcLog "testStarted" [
"flowId", formatName n
"name", formatName n ] }
passed = fun n d -> async {
do! innerPrinter.passed n d
tcLog "testFinished" [
"flowId", formatName n
"name", formatName n
"duration", d.TotalMilliseconds |> int |> string ] }
info = fun s ->
innerPrinter.info s
ignored = fun n m -> async {
do! innerPrinter.ignored n m
tcLog "testIgnored" [
"flowId", formatName n
"name", formatName n
"message", m ] }
failed = fun n m d -> async {
do! innerPrinter.failed n m d
tcLog "testFailed" [
"flowId", formatName n
"name", formatName n
"message", m ]
tcLog "testFinished" [
"flowId", formatName n
"name", formatName n
"duration", d.TotalMilliseconds |> int |> string ] }
exn = fun n e d -> async {
do! innerPrinter.beforeEach n
tcLog "testFailed" [
"flowId", formatName n
"name", formatName n
"message", e.Message
"details", e.StackTrace ]
tcLog "testFinished" [
"flowId", formatName n
"name", formatName n
"duration", d.TotalMilliseconds |> int |> string ] }
summary = fun c s -> async {
do! innerPrinter.summary c s
tcLog "testSuiteFinished" [
"name", "ExpectoTestSuite" ] } }
static member internal mergePrinters (first:TestPrinters, second:TestPrinters) =
let runTwoAsyncs a b = async {
do! a
do! b
}
{ beforeRun = fun _tests -> runTwoAsyncs (first.beforeRun _tests) (second.beforeRun _tests)
beforeEach = fun n -> runTwoAsyncs (first.beforeEach n) (second.beforeEach n)
info = fun s -> runTwoAsyncs (first.info s) (second.info s)
passed = fun n d -> runTwoAsyncs (first.passed n d) (second.passed n d)
ignored = fun n m -> runTwoAsyncs (first.ignored n m) (second.ignored n m)
failed = fun n m d -> runTwoAsyncs (first.failed n m d) (second.failed n m d)
exn = fun n e d -> runTwoAsyncs (first.exn n e d) (second.exn n e d)
summary = fun config summary -> runTwoAsyncs (first.summary config summary) (second.summary config summary)
}
// Runner options
and ExpectoConfig =
{ /// Whether to run the tests in parallel. Defaults to
/// true, because your code should not mutate global
/// state by default.
parallel : bool
/// Number of parallel workers. Defaults to the number of
/// logical processors.
parallelWorkers : int
/// Stress test by running tests randomly for the given TimeSpan.
/// Can be sequenced or parallel depending on the config.
stress : TimeSpan option
/// Stress test deadlock timeout TimeSpan to wait after stress TimeSpan
/// before stopping and reporting as a deadlock (default 5 mins).
stressTimeout : TimeSpan
/// Stress test memory limit in MB to stop the test and report as
/// a memory leak (default 100 MB).
stressMemoryLimit : float
/// Whether to make the test runner fail if focused tests exist.
/// This can be used from CI servers to ensure no focused tests are
/// commited and therefor all tests are run.
failOnFocusedTests : bool
/// An optional filter function. Useful if you only would
/// like to run a subset of all the tests defined in your assembly.
filter : Test -> Test
/// Allows the test printer to be parametised to your liking.
printer : TestPrinters
/// Verbosity level (default: Info).
verbosity : LogLevel
/// Process name to log under (default: "Expecto")
logName : string option
/// Optional function used for finding source code location of test
/// Defaults to empty source code.
locate : TestCode -> SourceLocation
/// FsCheck maximum number of tests (default: 100).
fsCheckMaxTests: int
/// FsCheck start size (default: 1).
fsCheckStartSize: int
/// FsCheck end size (default: 100 for testing and 10,000 for
/// stress testing).
fsCheckEndSize: int option
/// Depricated. Will be removed on next major release.
mySpiritIsWeak: bool
/// Allows duplicate test names.
allowDuplicateNames: bool
}
static member defaultConfig =
{ parallel = true
parallelWorkers = Environment.ProcessorCount
stress = None
stressTimeout = TimeSpan.FromMinutes 5.0
stressMemoryLimit = 100.0
filter = id
failOnFocusedTests = false
printer =
let tc = Environment.GetEnvironmentVariable "TEAMCITY_PROJECT_NAME"
if isNull tc then
TestPrinters.defaultPrinter
else
TestPrinters.teamCityPrinter TestPrinters.defaultPrinter
verbosity = Info
logName = None
locate = fun _ -> SourceLocation.empty
fsCheckMaxTests = 100
fsCheckStartSize = 1
fsCheckEndSize = None
mySpiritIsWeak = false
allowDuplicateNames = false
}
let execTestAsync (ct:CancellationToken) config (test:FlatTest) : Async<TestSummary> =
async {
let w = Stopwatch.StartNew()
try
match test.shouldSkipEvaluation with
| Some ignoredMessage ->
return TestSummary.single (Ignored ignoredMessage) 0.0
| None ->
TestNameHolder.Name <- test.name
match test.test with
| Sync test ->
test()
| SyncWithCancel test ->
test ct
| Async test ->
do! test
| AsyncFsCheck (testConfig, stressConfig, test) ->
let fsConfig =
match config.stress with
| None -> testConfig
| Some _ -> stressConfig
|> Option.orFun (fun () ->
{ FsCheckConfig.defaultConfig with
maxTest = config.fsCheckMaxTests
startSize = config.fsCheckStartSize
endSize =
match config.fsCheckEndSize, config.stress with
| Some i, _ -> i
| None, None -> 100
| None, Some _ -> 10000
}
)
do! test fsConfig
w.Stop()
return TestSummary.single Passed (float w.ElapsedMilliseconds)
with
| :? AssertException as e ->
w.Stop()
let msg =
(stackTraceToString e.StackTrace).Split('\n')
|> Seq.tryFind (fun q -> q.Contains ",1): ")
|> Option.defaultWith (fun () -> e.StackTrace.Split('\n')
|> Seq.truncate 10
|> String.concat "\n")
|> sprintf "\n%s\n%s\n" e.Message
return
TestSummary.single (Failed msg) (float w.ElapsedMilliseconds)
| :? FailedException as e ->
w.Stop()
return
TestSummary.single (Failed ("\n"+e.Message)) (float w.ElapsedMilliseconds)
| :? IgnoreException as e ->
w.Stop()
return
TestSummary.single (Ignored e.Message) (float w.ElapsedMilliseconds)
| e ->
w.Stop()
return
TestSummary.single (TestResult.Error e) (float w.ElapsedMilliseconds)
}
let private numberOfWorkers limit config =
if config.parallelWorkers < 0 then
-config.parallelWorkers * Environment.ProcessorCount
elif config.parallelWorkers = 0 then
if limit then
Environment.ProcessorCount
else
Int32.MaxValue
else
config.parallelWorkers
/// Evaluates tests.
let evalTestsWithCancel (ct:CancellationToken) config test progressStarted =
async {
let tests = Test.toTestCodeList test
let testLength = List.length tests
let testsCompleted = ref 0
let evalTestAsync (test:FlatTest) =
let beforeEach (test:FlatTest) =
config.printer.beforeEach test.name
async {
let! beforeAsync = beforeEach test |> Async.StartChild
let! result = execTestAsync ct config test
do! beforeAsync
do! TestPrinters.printResult config test result
if progressStarted then
Fraction (Interlocked.Increment testsCompleted, testLength)
|> ProgressIndicator.update
return test,result
}
let inline cons xs x = x::xs