-
-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathExpecto.Impl.fs
More file actions
1085 lines (948 loc) · 40.8 KB
/
Expecto.Impl.fs
File metadata and controls
1085 lines (948 loc) · 40.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace Expecto
open System
open System.Collections.Generic
open System.Diagnostics
open System.Reflection
open System.Threading
open Expecto.Logging
open Expecto.Logging.Message
open Helpers
open Mono.Cecil
// TODO: make internal?
module Impl =
let mutable logger = Log.create "Expecto"
let setLogName name = logger <- Log.create name
let rec private exnWithInnerMsg (ex: exn) msg =
let currentMsg =
msg + (sprintf "%s%s" Environment.NewLine (ex.ToString()))
if isNull ex.InnerException then
currentMsg
else
exnWithInnerMsg ex.InnerException currentMsg
type JoinWith =
| Dot
| Slash
member x.asString =
match x with
| Dot -> "."
| _ -> "/"
member x.format (parts: string list) =
let by = x.asString
String.concat by parts
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: " + exnWithInnerMsg e ""
member x.tag =
match x with
| Passed -> 0
| Ignored _ -> 1
| Failed _ -> 2
| Error _ -> 3
member x.order =
match x with
| Ignored _ -> 0
| Passed -> 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 }
member x.duration = TimeSpan.FromMilliseconds x.meanDuration
static member single result duration =
{ result = result
count = 1
meanDuration = duration
maxDuration = duration }
static member (+) (s:TestSummary, (r,x): TestResult*float) =
{ result = TestResult.max s.result r
count = s.count + 1
meanDuration =
s.meanDuration + (x-s.meanDuration)/float(s.count + 1)
maxDuration = max s.maxDuration x }
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 joinWith (summary: TestRunSummary) =
let handleLineBreaks (elements:(FlatTest*TestSummary) seq) =
elements
|> Seq.map (fun (n,_) -> "\n\t" + n.fullName joinWith)
|> 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 joinWith (summary: TestRunSummary) =
createSummaryMessage joinWith summary Info
|> Formatting.defaultFormatter
let logSummary (joinWith: JoinWith) (summary: TestRunSummary) =
let split = joinWith.asString
createSummaryMessage split summary
|> logger.logWithAck Info
let logSummaryWithLocation (join: JoinWith) locate (summary: TestRunSummary) =
let handleLineBreaks (elements:(FlatTest*TestSummary) seq) =
let format (n:FlatTest,_) =
let location = locate n.test
let name = join.format n.name
sprintf "%s [%s:%d]" 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
[<ReferenceEquality>]
type TestPrinters =
{ /// Called before a test run (e.g. at the top of your main function)
beforeRun: Test -> Async<unit>
/// test name -> isTestSkipped -> unit. Called before a test is executed (when isTestSkipped = true) or skipped (when isTestSkipped = false)
beforeEach: string -> bool -> 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> }
// NOTE: with* methods provide a compatibility layer allowing us to change the TestPrinters signature
// without breaking YoloDev.Expecto.TestSdk and other dependent packages
static member withBeforeRun (beforeRun: (Test -> Async<unit>)) (printer: TestPrinters) = {printer with beforeRun = beforeRun}
static member withBeforeEach (beforeEach: (string -> Async<unit>)) (printer: TestPrinters) = {printer with beforeEach = (fun name _ -> beforeEach name)}
static member withBeforeEach_WithIsSkipped (beforeEach: (string -> bool -> Async<unit>)) (printer: TestPrinters) = {printer with beforeEach = beforeEach}
static member withInfo (info: (string -> Async<unit>)) (printer: TestPrinters) = {printer with info = info}
static member withPassed (passed: (string -> TimeSpan -> Async<unit>)) (printer: TestPrinters) = {printer with passed = passed}
static member withIgnored (ignored: (string -> string -> Async<unit>)) (printer: TestPrinters) = {printer with ignored = ignored}
static member withFailed (failed: (string -> string -> TimeSpan -> Async<unit>)) (printer: TestPrinters) = {printer with failed = failed}
static member withExn (exn: (string -> exn -> TimeSpan -> Async<unit>)) (printer: TestPrinters) = {printer with exn = exn}
static member withSummary (summary: (ExpectoConfig -> TestRunSummary -> Async<unit>)) (printer: TestPrinters) = {printer with summary = summary}
static member printResult config (test:FlatTest) (result:TestSummary) =
let name = config.joinWith.format test.name
match result.result with
| Passed -> config.printer.passed name result.duration
| Failed message -> config.printer.failed name message result.duration
| Ignored message -> config.printer.ignored name message
| Error e -> config.printer.exn 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 splitSign = _config.joinWith.asString
let spirit =
if summary.successful then "Success!" else String.Empty
let commonAncestor =
let rec loop (ancestor: string) (descendants : string list) =
match descendants with
| [] -> ancestor
| hd::tl when hd.StartsWith(ancestor)->
loop ancestor tl
| _ ->
if ancestor.Contains(splitSign) then
loop (ancestor.Substring(0, ancestor.LastIndexOf splitSign)) descendants
else
"miscellaneous"
let parentNames =
summary.results
|> List.map (fun (flatTest, _) ->
if flatTest.name.Length > 1 then
let size = flatTest.name.Length - 1
_config.joinWith.format flatTest.name.[0..size]
else
_config.joinWith.format 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) -> if r.result.isIgnored then 0 else 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 getName (name: string list) =
config.joinWith.format name
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 -> getName 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 -> getName 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 config.joinWith summary) }
static member summaryWithLocationPrinter innerPrinter =
{ innerPrinter with
summary = fun config summary ->
innerPrinter.summary config summary
|> Async.bind (fun () -> logSummaryWithLocation config.joinWith config.locate summary) }
static member teamCityPrinter innerPrinter =
let formatName (n:string) =
n.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 e -> async {
do! innerPrinter.beforeEach n e
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 true
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 e -> runTwoAsyncs (first.beforeEach n e) (second.beforeEach n e)
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.
runInParallel : 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
/// List tests of specified state
listStates : FocusState list
/// 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
/// Allows duplicate test names.
allowDuplicateNames: bool
/// Disable spinner progress update.
noSpinner: bool
/// Set the level of colours to use.
colour: ColourLevel
/// Split test names by `.` or `/`
joinWith: JoinWith
}
static member defaultConfig =
{ runInParallel = true
parallelWorkers = Environment.ProcessorCount
stress = None
stressTimeout = TimeSpan.FromMinutes 5.0
stressMemoryLimit = 100.0
filter = id
listStates = []
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
allowDuplicateNames = false
noSpinner = false
colour = Colour8
joinWith = JoinWith.Dot
}
member x.appendSummaryHandler handleSummary =
{ x with
printer =
{ x.printer with
summary = fun config summary -> async {
do! x.printer.summary config summary
handleSummary summary
}
}
}
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 <- config.joinWith.format 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 =
"\n" + e.Message + "\n" +
(e.StackTrace.Split('\n')
|> Seq.skipWhile (fun l -> l.StartsWith(" at Expecto.Expect."))
|> Seq.truncate 5
|> String.concat "\n")
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)
| :? AggregateException as e when e.InnerExceptions.Count = 1 ->
w.Stop()
if e.InnerException :? IgnoreException then
return TestSummary.single (Ignored e.InnerException.Message) (float w.ElapsedMilliseconds)
else
return TestSummary.single (Error e.InnerException) (float w.ElapsedMilliseconds)
| e ->
w.Stop()
return TestSummary.single (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 =
tests
|> Seq.where (fun t -> Option.isNone t.shouldSkipEvaluation)
|> Seq.length
let testsCompleted = ref 0
let evalTestAsync (test:FlatTest) =
let beforeEach (test:FlatTest) =
let name = config.joinWith.format test.name
config.printer.beforeEach name <| Option.isSome test.shouldSkipEvaluation
async {
let! beforeAsync = beforeEach test |> Async.StartChild
let! result = execTestAsync ct config test
do! beforeAsync
do! TestPrinters.printResult config test result
if progressStarted && Option.isNone test.shouldSkipEvaluation then
Fraction (Interlocked.Increment testsCompleted, testLength)
|> ProgressIndicator.update
return test,result
}
let inline cons xs x = x::xs
if not config.runInParallel ||
config.parallelWorkers = 1 ||
List.forall (fun t -> t.sequenced=Synchronous) tests then
return!
List.map evalTestAsync tests
|> Async.foldSequentiallyWithCancel ct cons []
else
let sequenced =
List.filter (fun t -> t.sequenced=Synchronous) tests
|> List.map evalTestAsync
let runInParallel =
List.filter (fun t -> t.sequenced<>Synchronous) tests
|> Seq.groupBy (fun t -> t.sequenced)
|> Seq.collect(fun (group,tests) ->
match group with
| InParallel ->
Seq.map (evalTestAsync >> List.singleton) tests
| _ ->
Seq.map evalTestAsync tests
|> Seq.toList
|> Seq.singleton
)
|> Seq.toList
|> List.sortBy (List.length >> (~-))
|> List.map (
function
| [test] -> Async.map List.singleton test
| l -> Async.foldSequentiallyWithCancel ct cons [] l
)
let! parallelResults =
let noWorkers = numberOfWorkers false config
Async.foldParallelWithCancel noWorkers ct (@) [] runInParallel
if List.isEmpty sequenced |> not && List.isEmpty runInParallel |> not then
do! config.printer.info "Starting sequenced tests..."
let! results = Async.foldSequentiallyWithCancel ct cons parallelResults sequenced
return List.sortBy (fun (t,_) ->
List.tryFindIndex (LanguagePrimitives.PhysicalEquality t) tests
) results
}
/// Evaluates tests.
let evalTests config test =
evalTestsWithCancel CancellationToken.None config test false
let evalTestsSilent test =
let config =
{ ExpectoConfig.defaultConfig with
runInParallel = false
verbosity = LogLevel.Fatal
printer = TestPrinters.silent
}
evalTests config test
/// Runs tests, returns error code
let runEvalWithCancel (ct:CancellationToken) config test =
async {
do! config.printer.beforeRun test
let progressStarted =
if config.noSpinner then false
else
ProgressIndicator.text "Expecto Running... "
ProgressIndicator.start()
let w = Stopwatch.StartNew()
let! results = evalTestsWithCancel ct config test progressStarted
w.Stop()
let testSummary = {
results = results
duration = w.Elapsed
maxMemory = 0L
memoryLimit = 0L
timedOut = []
}
do! config.printer.summary config testSummary
if progressStarted then
ProgressIndicator.stop ()
ANSIOutputWriter.close ()
return testSummary.errorCode
}
/// Runs tests, returns error code
let runEval config test =
runEvalWithCancel CancellationToken.None config test
let runStressWithCancel (ct: CancellationToken) config test =
async {
do! config.printer.beforeRun test
let progressStarted =
if config.noSpinner then false
else
ProgressIndicator.text "Expecto Running... "
ProgressIndicator.start()
let tests =
Test.toTestCodeList test
|> List.filter (fun t -> Option.isNone t.shouldSkipEvaluation)
let memoryLimit =
config.stressMemoryLimit * 1024.0 * 1024.0 |> int64
let evalTestAsync test =
execTestAsync ct config test |> Async.map (addFst test)
let rand = Random()
let randNext tests =
let next = List.length tests |> rand.Next
List.item next tests
let totalTicks =
config.stress.Value.TotalSeconds * float Stopwatch.Frequency
|> int64
let finishTime = lazy (totalTicks + Stopwatch.GetTimestamp())
let asyncRun foldRunner (runningTests: ResizeArray<_>,
results,
maxMemory) x =
let cancel = new CancellationTokenSource()
let folder (runningTests: ResizeArray<_>, results: ResizeMap<_,_>, maxMemory)
(test, result) =
runningTests.Remove test |> ignore
results.[test] <-
match results.TryGetValue test with
| true, existing ->
existing + (result.result, result.meanDuration)
| false, _ ->
result
let maxMemory = GC.GetTotalMemory false |> max maxMemory
if maxMemory > memoryLimit then
cancel.Cancel()
runningTests, results, maxMemory
Async.Start(async {
let finishMilliseconds =
max (finishTime.Value - Stopwatch.GetTimestamp()) 0L
* 1000L / Stopwatch.Frequency
let timeout =
int finishMilliseconds + int config.stressTimeout.TotalMilliseconds
do! Async.Sleep timeout
cancel.Cancel()
}, cancel.Token)
x
|> Seq.takeWhile (fun test ->
let now = Stopwatch.GetTimestamp()
if progressStarted then
100 - int((finishTime.Value - now) * 100L / totalTicks)
|> Percent
|> ProgressIndicator.update
if now < finishTime.Value
&& not ct.IsCancellationRequested then
runningTests.Add test
true
else
false )
|> Seq.map evalTestAsync
|> foldRunner cancel.Token folder (runningTests,results,maxMemory)
let initial = ResizeArray(), ResizeMap(), GC.GetTotalMemory false
let w = Stopwatch.StartNew()
let! runningTests,results,maxMemory =
let shouldRunSync =
not config.runInParallel
|| config.parallelWorkers = 1
|| List.forall (fun t -> t.sequenced=Synchronous) tests
if List.isEmpty tests then
async { return initial }
elif shouldRunSync then
Seq.initInfinite (fun _ -> randNext tests)
|> Seq.append tests
|> asyncRun Async.foldSequentiallyWithCancel initial
else
List.filter (fun t -> t.sequenced=Synchronous) tests
|> asyncRun Async.foldSequentiallyWithCancel initial
|> Async.bind (fun (runningTests,results,maxMemory) ->
if maxMemory > memoryLimit
|| Stopwatch.GetTimestamp() > finishTime.Value then
async.Return (runningTests,results,maxMemory)
else
let runInParallel =
List.filter (fun t -> t.sequenced<>Synchronous) tests
Seq.initInfinite (fun _ -> randNext runInParallel)
|> Seq.append runInParallel
|> Seq.filter (fun test ->
let s = test.sequenced
s=InParallel ||
not(Seq.exists (fun t -> t.sequenced=s) runningTests)
)
|> asyncRun
(Async.foldParallelWithCancel (numberOfWorkers true config))
(runningTests,results,maxMemory)
)
w.Stop()
let testSummary = { results = results
|> Seq.map (fun kv -> kv.Key,kv.Value)
|> List.ofSeq
duration = w.Elapsed
maxMemory = maxMemory
memoryLimit = memoryLimit
timedOut = List.ofSeq runningTests }
do! config.printer.summary config testSummary
if progressStarted then
ProgressIndicator.stop()
ANSIOutputWriter.close()
return testSummary.errorCode
}
let runStress config test =
runStressWithCancel CancellationToken.None config test
let testFromMember (mi: MemberInfo) : Test option =
let inline unboxTest v =
if isNull v then
"Test is null. Assembly may not be initialized. Consider adding an [<EntryPoint>] or making it a library/classlib."
|> NullTestDiscoveryException |> raise
else unbox v
let getTestFromMemberInfo focusedState =
match box mi with
| :? FieldInfo as m when m.FieldType = typeof<Test> ->
Some(focusedState, m.GetValue(null) |> unboxTest)
| :? MethodInfo as m when m.ReturnType = typeof<Test> ->
Some(focusedState, m.Invoke(null, null) |> unboxTest)
| :? PropertyInfo as m when m.PropertyType = typeof<Test> ->
Some(focusedState, m.GetValue(null, null) |> unboxTest)
| _ -> None
mi.MatchTestsAttributes ()
|> Option.bind getTestFromMemberInfo
|> Option.map ((<||) Test.translateFocusState)
let listToTestListOption =
function
| [] -> None
| x -> Some (TestList (x, Normal))
let testFromType =
let inline asMembers x = unbox<MemberInfo[]> x
let bindingFlags = BindingFlags.Public ||| BindingFlags.Static
fun (t: Type) ->
[ t.GetMethods bindingFlags |> asMembers
t.GetProperties bindingFlags |> asMembers
t.GetFields bindingFlags |> asMembers ]
|> Seq.collect id
|> Seq.choose testFromMember
|> Seq.toList
|> listToTestListOption
// If the test function we've found doesn't seem to be in the test assembly, it's
// possible we're looking at an FsCheck 'testProperty' style check. In that case,
// the function of interest (i.e., the one in the test assembly, and for which we
// might be able to find corresponding source code) is referred to in a field
// of the function object.
let isFsharpFuncType t =
let baseType =
let rec findBase (t:Type) =
if t.GetTypeInfo().BaseType |> isNull || t.GetTypeInfo().BaseType = typeof<obj> then
t
else
findBase (t.GetTypeInfo().BaseType)
findBase t
baseType.GetTypeInfo().IsGenericType && baseType.GetTypeInfo().GetGenericTypeDefinition() = typedefof<FSharpFunc<unit, unit>>
let getFuncTypeToUse (testFunc:unit->unit) (asm:Assembly) =
let t = testFunc.GetType()
if t.GetTypeInfo().Assembly.FullName = asm.FullName then
t
else
let nestedFunc =
t.GetTypeInfo().GetFields()
|> Array.tryFind (fun f -> isFsharpFuncType f.FieldType)
match nestedFunc with
| Some f -> f.GetValue(testFunc).GetType()
| None -> t
let getMethodName asm testCode =
match testCode with
| Sync test ->
let t = getFuncTypeToUse test asm
let m = t.GetTypeInfo().GetMethods () |> Array.find (fun m -> (m.Name = "Invoke") && (m.DeclaringType = t))
(t.FullName, m.Name)
| SyncWithCancel _ ->
("Unknown SyncWithCancel", "Unknown SyncWithCancel")
| Async _ | AsyncFsCheck _ ->
("Unknown Async", "Unknown Async")
// Load the list of types in the test assembly and cache the data
// Ref https://github.com/haf/expecto/issues/517 for comments on the performance
let private moduleDefinitionCache = System.Collections.Concurrent.ConcurrentDictionary<string, Map<string, TypeDefinition>>()
let private getTypesForAssembly (asm: Assembly) =