-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Test.jl
1773 lines (1567 loc) · 60.3 KB
/
Test.jl
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
# This file is a part of Julia. License is MIT: https://julialang.org/license
"""
Simple unit testing functionality:
* `@test`
* `@test_throws`
All tests belong to a *test set*. There is a default, task-level
test set that throws on the first failure. Users can choose to wrap
their tests in (possibly nested) test sets that will store results
and summarize them at the end of the test set with `@testset`.
"""
module Test
export @test, @test_throws, @test_broken, @test_skip,
@test_warn, @test_nowarn,
@test_logs, @test_deprecated
export @testset
export @inferred
export detect_ambiguities, detect_unbound_args
export GenericString, GenericSet, GenericDict, GenericArray, GenericOrder
export TestSetException
using Random
using Random: AbstractRNG, default_rng
using InteractiveUtils: gen_call_with_extracted_types
using Base: typesplit
using Serialization: Serialization
const DISPLAY_FAILED = (
:isequal,
:isapprox,
:≈,
:occursin,
:startswith,
:endswith,
:isempty,
)
#-----------------------------------------------------------------------
# Backtrace utility functions
function ip_has_file_and_func(ip, file, funcs)
return any(fr -> (string(fr.file) == file && fr.func in funcs), StackTraces.lookup(ip))
end
function scrub_backtrace(bt)
do_test_ind = findfirst(ip -> ip_has_file_and_func(ip, @__FILE__, (:do_test, :do_test_throws)), bt)
if do_test_ind !== nothing && length(bt) > do_test_ind
bt = bt[do_test_ind + 1:end]
end
name_ind = findfirst(ip -> ip_has_file_and_func(ip, @__FILE__, (Symbol("macro expansion"),)), bt)
if name_ind !== nothing && length(bt) != 0
bt = bt[1:name_ind]
end
return bt
end
function scrub_exc_stack(stack)
return Any[ (x[1], scrub_backtrace(x[2])) for x in stack ]
end
# define most of the test infrastructure without type specialization
@nospecialize
"""
Result
All tests produce a result object. This object may or may not be
stored, depending on whether the test is part of a test set.
"""
abstract type Result end
"""
Pass
The test condition was true, i.e. the expression evaluated to true or
the correct exception was thrown.
"""
struct Pass <: Result
test_type::Symbol
orig_expr
data
value
function Pass(test_type::Symbol, orig_expr, data, thrown)
return new(test_type, orig_expr, data, thrown isa String ? "String" : thrown)
end
end
function Base.show(io::IO, t::Pass)
printstyled(io, "Test Passed"; bold = true, color=:green)
if !(t.orig_expr === nothing)
print(io, "\n Expression: ", t.orig_expr)
end
if t.test_type === :test_throws
# The correct type of exception was thrown
print(io, "\n Thrown: ", t.value isa String ? t.value : typeof(t.value))
elseif t.test_type === :test && t.data !== nothing
# The test was an expression, so display the term-by-term
# evaluated version as well
print(io, "\n Evaluated: ", t.data)
end
end
"""
Fail
The test condition was false, i.e. the expression evaluated to false or
the correct exception was not thrown.
"""
struct Fail <: Result
test_type::Symbol
orig_expr::String
data::Union{Nothing, String}
value::String
source::LineNumberNode
function Fail(test_type::Symbol, orig_expr, data, value, source::LineNumberNode)
return new(test_type,
string(orig_expr),
data === nothing ? nothing : string(data),
string(isa(data, Type) ? typeof(value) : value),
source)
end
end
function Base.show(io::IO, t::Fail)
printstyled(io, "Test Failed"; bold=true, color=Base.error_color())
print(io, " at ")
printstyled(io, something(t.source.file, :none), ":", t.source.line, "\n"; bold=true, color=:default)
print(io, " Expression: ", t.orig_expr)
if t.test_type === :test_throws_wrong
# An exception was thrown, but it was of the wrong type
print(io, "\n Expected: ", t.data)
print(io, "\n Thrown: ", t.value)
elseif t.test_type === :test_throws_nothing
# An exception was expected, but no exception was thrown
print(io, "\n Expected: ", t.data)
print(io, "\n No exception thrown")
elseif t.test_type === :test && t.data !== nothing
# The test was an expression, so display the term-by-term
# evaluated version as well
print(io, "\n Evaluated: ", t.data)
end
end
"""
Error
The test condition couldn't be evaluated due to an exception, or
it evaluated to something other than a [`Bool`](@ref).
In the case of `@test_broken` it is used to indicate that an
unexpected `Pass` `Result` occurred.
"""
struct Error <: Result
test_type::Symbol
orig_expr::String
value::String
backtrace::String
source::LineNumberNode
function Error(test_type, orig_expr, value, bt, source)
if test_type === :test_error
bt = scrub_exc_stack(bt)
end
if test_type === :test_error || test_type === :nontest_error
bt_str = sprint(Base.show_exception_stack, bt; context=stdout)
else
bt_str = ""
end
return new(test_type,
string(orig_expr),
sprint(show, value, context = :limit => true),
bt_str,
source)
end
end
function Base.show(io::IO, t::Error)
if t.test_type === :test_interrupted
printstyled(io, "Interrupted", color=Base.error_color())
return
end
printstyled(io, "Error During Test"; bold=true, color=Base.error_color())
print(io, " at ")
printstyled(io, something(t.source.file, :none), ":", t.source.line, "\n"; bold=true, color=:default)
if t.test_type === :test_nonbool
println(io, " Expression evaluated to non-Boolean")
println(io, " Expression: ", t.orig_expr)
print( io, " Value: ", t.value)
elseif t.test_type === :test_error
println(io, " Test threw exception")
println(io, " Expression: ", t.orig_expr)
# Capture error message and indent to match
join(io, (" " * line for line in split(t.backtrace, "\n")), "\n")
elseif t.test_type === :test_unbroken
# A test that was expected to fail did not
println(io, " Unexpected Pass")
println(io, " Expression: ", t.orig_expr)
println(io, " Got correct result, please change to @test if no longer broken.")
elseif t.test_type === :nontest_error
# we had an error outside of a @test
println(io, " Got exception outside of a @test")
# Capture error message and indent to match
join(io, (" " * line for line in split(t.backtrace, "\n")), "\n")
end
end
"""
Broken
The test condition is the expected (failed) result of a broken test,
or was explicitly skipped with `@test_skip`.
"""
struct Broken <: Result
test_type::Symbol
orig_expr
end
function Base.show(io::IO, t::Broken)
printstyled(io, "Test Broken\n"; bold=true, color=Base.warn_color())
if t.test_type === :skipped && !(t.orig_expr === nothing)
print(io, " Skipped: ", t.orig_expr)
elseif !(t.orig_expr === nothing)
print(io, " Expression: ", t.orig_expr)
end
end
# Types that appear in TestSetException.errors_and_fails we convert eagerly into strings
# other types we convert lazily
function Serialization.serialize(s::Serialization.AbstractSerializer, t::Pass)
Serialization.serialize_type(s, typeof(t))
Serialization.serialize(s, t.test_type)
Serialization.serialize(s, t.orig_expr === nothing ? nothing : string(t.orig_expr))
Serialization.serialize(s, t.data === nothing ? nothing : string(t.data))
Serialization.serialize(s, string(t.value))
nothing
end
function Serialization.serialize(s::Serialization.AbstractSerializer, t::Broken)
Serialization.serialize_type(s, typeof(t))
Serialization.serialize(s, t.test_type)
Serialization.serialize(s, t.orig_expr === nothing ? nothing : string(t.orig_expr))
nothing
end
#-----------------------------------------------------------------------
abstract type ExecutionResult end
struct Returned <: ExecutionResult
value
data
source::LineNumberNode
end
struct Threw <: ExecutionResult
exception
backtrace
source::LineNumberNode
end
function eval_test(evaluated::Expr, quoted::Expr, source::LineNumberNode, negate::Bool=false)
res = true
i = 1
evaled_args = evaluated.args
quoted_args = quoted.args
n = length(evaled_args)
kw_suffix = ""
if evaluated.head === :comparison
args = evaled_args
while i < n
a, op, b = args[i], args[i+1], args[i+2]
if res
res = op(a, b) === true # Keep `res` type stable
end
quoted_args[i] = a
quoted_args[i+2] = b
i += 2
end
elseif evaluated.head === :call
op = evaled_args[1]
kwargs = evaled_args[2].args # Keyword arguments from `Expr(:parameters, ...)`
args = evaled_args[3:n]
res = op(args...; kwargs...) === true
# Create "Evaluated" expression which looks like the original call but has all of
# the arguments evaluated
func_sym = quoted_args[1]
if isempty(kwargs)
quoted = Expr(:call, func_sym, args...)
elseif func_sym === :≈ && !res
quoted = Expr(:call, func_sym, args...)
kw_suffix = " ($(join(["$k=$v" for (k, v) in kwargs], ", ")))"
else
kwargs_expr = Expr(:parameters, [Expr(:kw, k, v) for (k, v) in kwargs]...)
quoted = Expr(:call, func_sym, kwargs_expr, args...)
end
else
throw(ArgumentError("Unhandled expression type: $(evaluated.head)"))
end
if negate
res = !res
quoted = Expr(:call, :!, quoted)
end
Returned(res,
# stringify arguments in case of failure, for easy remote printing
res ? quoted : sprint(io->print(IOContext(io, :limit => true), quoted))*kw_suffix,
source)
end
const comparison_prec = Base.operator_precedence(:(==))
"""
test_expr!(ex, kws...)
Preprocess test expressions of function calls with trailing keyword arguments
so that e.g. `@test a ≈ b atol=ε` means `@test ≈(a, b, atol=ε)`.
"""
test_expr!(m, ex) = ex
function test_expr!(m, ex, kws...)
ex isa Expr && ex.head === :call || @goto fail
for kw in kws
kw isa Expr && kw.head === :(=) || @goto fail
kw.head = :kw
push!(ex.args, kw)
end
return ex
@label fail
error("invalid test macro call: $m $ex $(join(kws," "))")
end
# @test - check if the expression evaluates to true
"""
@test ex
@test f(args...) key=val ...
Tests that the expression `ex` evaluates to `true`.
Returns a `Pass` `Result` if it does, a `Fail` `Result` if it is
`false`, and an `Error` `Result` if it could not be evaluated.
# Examples
```jldoctest
julia> @test true
Test Passed
julia> @test [1, 2] + [2, 1] == [3, 3]
Test Passed
```
The `@test f(args...) key=val...` form is equivalent to writing
`@test f(args..., key=val...)` which can be useful when the expression
is a call using infix syntax such as approximate comparisons:
```jldoctest
julia> @test π ≈ 3.14 atol=0.01
Test Passed
```
This is equivalent to the uglier test `@test ≈(π, 3.14, atol=0.01)`.
It is an error to supply more than one expression unless the first
is a call expression and the rest are assignments (`k=v`).
"""
macro test(ex, kws...)
test_expr!("@test", ex, kws...)
orig_ex = Expr(:inert, ex)
result = get_test_result(ex, __source__)
:(do_test($result, $orig_ex))
end
"""
@test_broken ex
@test_broken f(args...) key=val ...
Indicates a test that should pass but currently consistently fails.
Tests that the expression `ex` evaluates to `false` or causes an
exception. Returns a `Broken` `Result` if it does, or an `Error` `Result`
if the expression evaluates to `true`.
The `@test_broken f(args...) key=val...` form works as for the `@test` macro.
# Examples
```jldoctest
julia> @test_broken 1 == 2
Test Broken
Expression: 1 == 2
julia> @test_broken 1 == 2 atol=0.1
Test Broken
Expression: ==(1, 2, atol = 0.1)
```
"""
macro test_broken(ex, kws...)
test_expr!("@test_broken", ex, kws...)
orig_ex = Expr(:inert, ex)
result = get_test_result(ex, __source__)
# code to call do_test with execution result and original expr
:(do_broken_test($result, $orig_ex))
end
"""
@test_skip ex
@test_skip f(args...) key=val ...
Marks a test that should not be executed but should be included in test
summary reporting as `Broken`. This can be useful for tests that intermittently
fail, or tests of not-yet-implemented functionality.
The `@test_skip f(args...) key=val...` form works as for the `@test` macro.
# Examples
```jldoctest
julia> @test_skip 1 == 2
Test Broken
Skipped: 1 == 2
julia> @test_skip 1 == 2 atol=0.1
Test Broken
Skipped: ==(1, 2, atol = 0.1)
```
"""
macro test_skip(ex, kws...)
test_expr!("@test_skip", ex, kws...)
orig_ex = Expr(:inert, ex)
testres = :(Broken(:skipped, $orig_ex))
:(record(get_testset(), $testres))
end
# An internal function, called by the code generated by the @test
# macro to get results of the test expression.
# In the special case of a comparison, e.g. x == 5, generate code to
# evaluate each term in the comparison individually so the results
# can be displayed nicely.
function get_test_result(ex, source)
negate = QuoteNode(false)
orig_ex = ex
# Evaluate `not` wrapped functions separately for pretty-printing failures
if isa(ex, Expr) && ex.head === :call && length(ex.args) == 2 && ex.args[1] === :!
negate = QuoteNode(true)
ex = ex.args[2]
end
# Normalize non-dot comparison operator calls to :comparison expressions
is_splat = x -> isa(x, Expr) && x.head === :...
if isa(ex, Expr) && ex.head === :call && length(ex.args) == 3 &&
first(string(ex.args[1])) != '.' && !is_splat(ex.args[2]) && !is_splat(ex.args[3]) &&
(ex.args[1] === :(==) || Base.operator_precedence(ex.args[1]) == comparison_prec)
ex = Expr(:comparison, ex.args[2], ex.args[1], ex.args[3])
end
if isa(ex, Expr) && ex.head === :comparison
# pass all terms of the comparison to `eval_comparison`, as an Expr
escaped_terms = [esc(arg) for arg in ex.args]
quoted_terms = [QuoteNode(arg) for arg in ex.args]
testret = :(eval_test(
Expr(:comparison, $(escaped_terms...)),
Expr(:comparison, $(quoted_terms...)),
$(QuoteNode(source)),
$negate,
))
elseif isa(ex, Expr) && ex.head === :call && ex.args[1] in DISPLAY_FAILED
escaped_func = esc(ex.args[1])
quoted_func = QuoteNode(ex.args[1])
escaped_args = []
escaped_kwargs = []
# Keywords that occur before `;`. Note that the keywords are being revised into
# a form we can splat.
for a in ex.args[2:end]
if isa(a, Expr) && a.head === :kw
push!(escaped_kwargs, Expr(:call, :(=>), QuoteNode(a.args[1]), esc(a.args[2])))
end
end
# Keywords that occur after ';'
parameters_expr = ex.args[2]
if isa(parameters_expr, Expr) && parameters_expr.head === :parameters
for a in parameters_expr.args
if isa(a, Expr) && a.head === :kw
push!(escaped_kwargs, Expr(:call, :(=>), QuoteNode(a.args[1]), esc(a.args[2])))
elseif isa(a, Expr) && a.head === :...
push!(escaped_kwargs, Expr(:..., esc(a.args[1])))
elseif isa(a, Expr) && a.head === :.
push!(escaped_kwargs, Expr(:call, :(=>), QuoteNode(a.args[2].value), esc(Expr(:., a.args[1], QuoteNode(a.args[2].value)))))
elseif isa(a, Symbol)
push!(escaped_kwargs, Expr(:call, :(=>), QuoteNode(a), esc(a)))
end
end
end
# Positional arguments
for a in ex.args[2:end]
isa(a, Expr) && a.head in (:kw, :parameters) && continue
if isa(a, Expr) && a.head === :...
push!(escaped_args, Expr(:..., esc(a.args[1])))
else
push!(escaped_args, esc(a))
end
end
testret = :(eval_test(
Expr(:call, $escaped_func, Expr(:parameters, $(escaped_kwargs...)), $(escaped_args...)),
Expr(:call, $quoted_func),
$(QuoteNode(source)),
$negate,
))
else
testret = :(Returned($(esc(orig_ex)), nothing, $(QuoteNode(source))))
end
result = quote
try
$testret
catch _e
_e isa InterruptException && rethrow()
Threw(_e, Base.catch_stack(), $(QuoteNode(source)))
end
end
Base.remove_linenums!(result)
result
end
# An internal function, called by the code generated by the @test
# macro to actually perform the evaluation and manage the result.
function do_test(result::ExecutionResult, orig_expr)
# get_testset() returns the most recently added test set
# We then call record() with this test set and the test result
if isa(result, Returned)
# expr, in the case of a comparison, will contain the
# comparison with evaluated values of each term spliced in.
# For anything else, just contains the test expression.
# value is the evaluated value of the whole test expression.
# Ideally it is true, but it may be false or non-Boolean.
value = result.value
testres = if isa(value, Bool)
# a true value Passes
value ? Pass(:test, nothing, nothing, value) :
Fail(:test, orig_expr, result.data, value, result.source)
else
# If the result is non-Boolean, this counts as an Error
Error(:test_nonbool, orig_expr, value, nothing, result.source)
end
else
# The predicate couldn't be evaluated without throwing an
# exception, so that is an Error and not a Fail
@assert isa(result, Threw)
testres = Error(:test_error, orig_expr, result.exception, result.backtrace, result.source)
end
record(get_testset(), testres)
end
function do_broken_test(result::ExecutionResult, orig_expr)
testres = Broken(:test, orig_expr)
# Assume the test is broken and only change if the result is true
if isa(result, Returned)
value = result.value
if isa(value, Bool) && value
testres = Error(:test_unbroken, orig_expr, value, nothing, result.source)
end
end
record(get_testset(), testres)
end
#-----------------------------------------------------------------------
"""
@test_throws exception expr
Tests that the expression `expr` throws `exception`.
The exception may specify either a type,
or a value (which will be tested for equality by comparing fields).
Note that `@test_throws` does not support a trailing keyword form.
# Examples
```jldoctest
julia> @test_throws BoundsError [1, 2, 3][4]
Test Passed
Thrown: BoundsError
julia> @test_throws DimensionMismatch [1, 2, 3] + [1, 2]
Test Passed
Thrown: DimensionMismatch
```
"""
macro test_throws(extype, ex)
orig_ex = Expr(:inert, ex)
result = quote
try
Returned($(esc(ex)), nothing, $(QuoteNode(__source__)))
catch _e
if $(esc(extype)) != InterruptException && _e isa InterruptException
rethrow()
end
Threw(_e, nothing, $(QuoteNode(__source__)))
end
end
Base.remove_linenums!(result)
:(do_test_throws($result, $orig_ex, $(esc(extype))))
end
# An internal function, called by the code generated by @test_throws
# to evaluate and catch the thrown exception - if it exists
function do_test_throws(result::ExecutionResult, orig_expr, extype)
if isa(result, Threw)
# Check that the right type of exception was thrown
success = false
exc = result.exception
if isa(extype, Type)
success = isa(exc, extype)
else
if isa(exc, typeof(extype))
success = true
for fld in 1:nfields(extype)
if !isequal(getfield(extype, fld), getfield(exc, fld))
success = false
break
end
end
end
end
if success
testres = Pass(:test_throws, nothing, nothing, exc)
else
testres = Fail(:test_throws_wrong, orig_expr, extype, exc, result.source)
end
else
testres = Fail(:test_throws_nothing, orig_expr, extype, nothing, result.source)
end
record(get_testset(), testres)
end
#-----------------------------------------------------------------------
# Test for log messages
# Test for warning messages (deprecated)
contains_warn(output, s::AbstractString) = occursin(s, output)
contains_warn(output, s::Regex) = occursin(s, output)
contains_warn(output, s::Function) = s(output)
contains_warn(output, S::Union{AbstractArray,Tuple}) = all(s -> contains_warn(output, s), S)
"""
@test_warn msg expr
Test whether evaluating `expr` results in [`stderr`](@ref) output that contains
the `msg` string or matches the `msg` regular expression. If `msg` is
a boolean function, tests whether `msg(output)` returns `true`. If `msg` is a
tuple or array, checks that the error output contains/matches each item in `msg`.
Returns the result of evaluating `expr`.
See also [`@test_nowarn`](@ref) to check for the absence of error output.
Note: Warnings generated by `@warn` cannot be tested with this macro. Use
[`@test_logs`](@ref) instead.
"""
macro test_warn(msg, expr)
quote
let fname = tempname()
try
ret = open(fname, "w") do f
redirect_stderr(f) do
$(esc(expr))
end
end
@test contains_warn(read(fname, String), $(esc(msg)))
ret
finally
rm(fname, force=true)
end
end
end
end
"""
@test_nowarn expr
Test whether evaluating `expr` results in empty [`stderr`](@ref) output
(no warnings or other messages). Returns the result of evaluating `expr`.
Note: The absence of warnings generated by `@warn` cannot be tested
with this macro. Use [`@test_logs`](@ref) instead.
"""
macro test_nowarn(expr)
quote
@test_warn r"^(?!.)"s $(esc(expr))
end
end
#-----------------------------------------------------------------------
# The AbstractTestSet interface is defined by two methods:
# record(AbstractTestSet, Result)
# Called by do_test after a test is evaluated
# finish(AbstractTestSet)
# Called after the test set has been popped from the test set stack
abstract type AbstractTestSet end
"""
record(ts::AbstractTestSet, res::Result)
Record a result to a testset. This function is called by the `@testset`
infrastructure each time a contained `@test` macro completes, and is given the
test result (which could be an `Error`). This will also be called with an `Error`
if an exception is thrown inside the test block but outside of a `@test` context.
"""
function record end
"""
finish(ts::AbstractTestSet)
Do any final processing necessary for the given testset. This is called by the
`@testset` infrastructure after a test block executes. One common use for this
function is to record the testset to the parent's results list, using
`get_testset`.
"""
function finish end
"""
TestSetException
Thrown when a test set finishes and not all tests passed.
"""
struct TestSetException <: Exception
pass::Int
fail::Int
error::Int
broken::Int
errors_and_fails::Vector{Union{Fail, Error}}
end
function Base.show(io::IO, ex::TestSetException)
print(io, "Some tests did not pass: ")
print(io, ex.pass, " passed, ")
print(io, ex.fail, " failed, ")
print(io, ex.error, " errored, ")
print(io, ex.broken, " broken.")
end
function Base.showerror(io::IO, ex::TestSetException, bt; backtrace=true)
printstyled(io, string(ex), color=Base.error_color())
end
#-----------------------------------------------------------------------
"""
FallbackTestSet
A simple fallback test set that throws immediately on a failure.
"""
struct FallbackTestSet <: AbstractTestSet end
fallback_testset = FallbackTestSet()
struct FallbackTestSetException <: Exception
msg::AbstractString
end
function Base.showerror(io::IO, ex::FallbackTestSetException, bt; backtrace=true)
printstyled(io, ex.msg, color=Base.error_color())
end
# Records nothing, and throws an error immediately whenever a Fail or
# Error occurs. Takes no action in the event of a Pass or Broken result
record(ts::FallbackTestSet, t::Union{Pass, Broken}) = t
function record(ts::FallbackTestSet, t::Union{Fail, Error})
println(t)
throw(FallbackTestSetException("There was an error during testing"))
end
# We don't need to do anything as we don't record anything
finish(ts::FallbackTestSet) = ts
#-----------------------------------------------------------------------
"""
DefaultTestSet
If using the DefaultTestSet, the test results will be recorded. If there
are any `Fail`s or `Error`s, an exception will be thrown only at the end,
along with a summary of the test results.
"""
mutable struct DefaultTestSet <: AbstractTestSet
description::AbstractString
results::Vector
n_passed::Int
anynonpass::Bool
verbose::Bool
end
DefaultTestSet(desc; verbose = false) = DefaultTestSet(desc, [], 0, false, verbose)
# For a broken result, simply store the result
record(ts::DefaultTestSet, t::Broken) = (push!(ts.results, t); t)
# For a passed result, do not store the result since it uses a lot of memory
record(ts::DefaultTestSet, t::Pass) = (ts.n_passed += 1; t)
# For the other result types, immediately print the error message
# but do not terminate. Print a backtrace.
function record(ts::DefaultTestSet, t::Union{Fail, Error})
if TESTSET_PRINT_ENABLE[]
printstyled(ts.description, ": ", color=:white)
# don't print for interrupted tests
if !(t isa Error) || t.test_type !== :test_interrupted
print(t)
if !isa(t, Error) # if not gets printed in the show method
Base.show_backtrace(stdout, scrub_backtrace(backtrace()))
end
println()
end
end
push!(ts.results, t)
return t
end
# When a DefaultTestSet finishes, it records itself to its parent
# testset, if there is one. This allows for recursive printing of
# the results at the end of the tests
record(ts::DefaultTestSet, t::AbstractTestSet) = push!(ts.results, t)
@specialize
function print_test_errors(ts::DefaultTestSet)
for t in ts.results
if isa(t, Error) || isa(t, Fail)
println("Error in testset $(ts.description):")
show(t)
println()
elseif isa(t, DefaultTestSet)
print_test_errors(t)
end
end
end
function print_test_results(ts::DefaultTestSet, depth_pad=0)
# Calculate the overall number for each type so each of
# the test result types are aligned
passes, fails, errors, broken, c_passes, c_fails, c_errors, c_broken = get_test_counts(ts)
total_pass = passes + c_passes
total_fail = fails + c_fails
total_error = errors + c_errors
total_broken = broken + c_broken
dig_pass = total_pass > 0 ? ndigits(total_pass) : 0
dig_fail = total_fail > 0 ? ndigits(total_fail) : 0
dig_error = total_error > 0 ? ndigits(total_error) : 0
dig_broken = total_broken > 0 ? ndigits(total_broken) : 0
total = total_pass + total_fail + total_error + total_broken
dig_total = total > 0 ? ndigits(total) : 0
# For each category, take max of digits and header width if there are
# tests of that type
pass_width = dig_pass > 0 ? max(length("Pass"), dig_pass) : 0
fail_width = dig_fail > 0 ? max(length("Fail"), dig_fail) : 0
error_width = dig_error > 0 ? max(length("Error"), dig_error) : 0
broken_width = dig_broken > 0 ? max(length("Broken"), dig_broken) : 0
total_width = dig_total > 0 ? max(length("Total"), dig_total) : 0
# Calculate the alignment of the test result counts by
# recursively walking the tree of test sets
align = max(get_alignment(ts, 0), length("Test Summary:"))
# Print the outer test set header once
pad = total == 0 ? "" : " "
printstyled(rpad("Test Summary:", align, " "), " |", pad; bold=true, color=:white)
if pass_width > 0
printstyled(lpad("Pass", pass_width, " "), " "; bold=true, color=:green)
end
if fail_width > 0
printstyled(lpad("Fail", fail_width, " "), " "; bold=true, color=Base.error_color())
end
if error_width > 0
printstyled(lpad("Error", error_width, " "), " "; bold=true, color=Base.error_color())
end
if broken_width > 0
printstyled(lpad("Broken", broken_width, " "), " "; bold=true, color=Base.warn_color())
end
if total_width > 0
printstyled(lpad("Total", total_width, " "); bold=true, color=Base.info_color())
end
println()
# Recursively print a summary at every level
print_counts(ts, depth_pad, align, pass_width, fail_width, error_width, broken_width, total_width)
end
const TESTSET_PRINT_ENABLE = Ref(true)
# Called at the end of a @testset, behaviour depends on whether
# this is a child of another testset, or the "root" testset
function finish(ts::DefaultTestSet)
# If we are a nested test set, do not print a full summary
# now - let the parent test set do the printing
if get_testset_depth() != 0
# Attach this test set to the parent test set
parent_ts = get_testset()
record(parent_ts, ts)
return ts
end
passes, fails, errors, broken, c_passes, c_fails, c_errors, c_broken = get_test_counts(ts)
total_pass = passes + c_passes
total_fail = fails + c_fails
total_error = errors + c_errors
total_broken = broken + c_broken
total = total_pass + total_fail + total_error + total_broken
if TESTSET_PRINT_ENABLE[]
print_test_results(ts)
end
# Finally throw an error as we are the outermost test set
if total != total_pass + total_broken
# Get all the error/failures and bring them along for the ride
efs = filter_errors(ts)
throw(TestSetException(total_pass, total_fail, total_error, total_broken, efs))
end
# return the testset so it is returned from the @testset macro
ts
end
# Recursive function that finds the column that the result counts
# can begin at by taking into account the width of the descriptions
# and the amount of indentation. If a test set had no failures, and
# no failures in child test sets, there is no need to include those
# in calculating the alignment
function get_alignment(ts::DefaultTestSet, depth::Int)
# The minimum width at this depth is
ts_width = 2*depth + length(ts.description)
# If all passing, no need to look at children
!ts.anynonpass && return ts_width
# Return the maximum of this width and the minimum width
# for all children (if they exist)
isempty(ts.results) && return ts_width
child_widths = map(t->get_alignment(t, depth+1), ts.results)
return max(ts_width, maximum(child_widths))
end
get_alignment(ts, depth::Int) = 0
# Recursive function that fetches backtraces for any and all errors
# or failures the testset and its children encountered
function filter_errors(ts::DefaultTestSet)
efs = []
for t in ts.results
if isa(t, DefaultTestSet)
append!(efs, filter_errors(t))
elseif isa(t, Union{Fail, Error})
append!(efs, [t])
end
end
efs
end
# Recursive function that counts the number of test results of each
# type directly in the testset, and totals across the child testsets
function get_test_counts(ts::DefaultTestSet)
passes, fails, errors, broken = ts.n_passed, 0, 0, 0
c_passes, c_fails, c_errors, c_broken = 0, 0, 0, 0
for t in ts.results
isa(t, Fail) && (fails += 1)
isa(t, Error) && (errors += 1)
isa(t, Broken) && (broken += 1)
if isa(t, DefaultTestSet)
np, nf, ne, nb, ncp, ncf, nce , ncb = get_test_counts(t)
c_passes += np + ncp
c_fails += nf + ncf
c_errors += ne + nce
c_broken += nb + ncb
end
end
ts.anynonpass = (fails + errors + c_fails + c_errors > 0)
return passes, fails, errors, broken, c_passes, c_fails, c_errors, c_broken
end
# Recursive function that prints out the results at each level of
# the tree of test sets
function print_counts(ts::DefaultTestSet, depth, align,
pass_width, fail_width, error_width, broken_width, total_width)
# Count results by each type at this level, and recursively
# through any child test sets
passes, fails, errors, broken, c_passes, c_fails, c_errors, c_broken = get_test_counts(ts)
subtotal = passes + fails + errors + broken + c_passes + c_fails + c_errors + c_broken
# Print test set header, with an alignment that ensures all
# the test results appear above each other
print(rpad(string(" "^depth, ts.description), align, " "), " | ")
np = passes + c_passes
if np > 0
printstyled(lpad(string(np), pass_width, " "), " ", color=:green)
elseif pass_width > 0
# No passes at this level, but some at another level
print(lpad(" ", pass_width), " ")
end
nf = fails + c_fails
if nf > 0
printstyled(lpad(string(nf), fail_width, " "), " ", color=Base.error_color())
elseif fail_width > 0
# No fails at this level, but some at another level
print(lpad(" ", fail_width), " ")
end