-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathTest.jl
2135 lines (1886 loc) · 74.6 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
export TestLogger, LogRecord
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,
:contains
)
const FAIL_FAST = Ref{Bool}(false)
#-----------------------------------------------------------------------
# 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]::Vector{Union{Ptr{Nothing},Base.InterpreterIP}})) 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
source::Union{Nothing,LineNumberNode}
message_only::Bool
function Pass(test_type::Symbol, orig_expr, data, thrown, source::Union{Nothing,LineNumberNode}=nothing, message_only::Bool=false)
return new(test_type, orig_expr, data, thrown, source, message_only)
end
end
function Base.show(io::IO, t::Pass)
printstyled(io, "Test Passed"; bold = true, color=:green)
if t.test_type === :test_throws
# The correct type of exception was thrown
if t.message_only
print(io, "\n Message: ", t.value)
else
print(io, "\n Thrown: ", typeof(t.value))
end
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
context::Union{Nothing, String}
source::LineNumberNode
message_only::Bool
function Fail(test_type::Symbol, orig_expr, data, value, context, source::LineNumberNode, message_only::Bool)
return new(test_type,
string(orig_expr),
data === nothing ? nothing : string(data),
string(isa(data, Type) ? typeof(value) : value),
context,
source,
message_only)
end
end
# Deprecated fallback constructor without `context` argument (added in Julia 1.9). Remove in Julia 2.0.
Fail(test_type::Symbol, orig_expr, data, value, source::LineNumberNode, message_only::Bool=false) =
Fail(test_type, orig_expr, data, value, nothing, source, message_only)
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)
value, data = t.value, t.data
if t.test_type === :test_throws_wrong
# An exception was thrown, but it was of the wrong type
if t.message_only
print(io, "\n Expected: ", data)
print(io, "\n Message: ", value)
else
print(io, "\n Expected: ", data)
print(io, "\n Thrown: ", value)
end
elseif t.test_type === :test_throws_nothing
# An exception was expected, but no exception was thrown
print(io, "\n Expected: ", data)
print(io, "\n No exception thrown")
elseif t.test_type === :test
if data !== nothing
# The test was an expression, so display the term-by-term
# evaluated version as well
print(io, "\n Evaluated: ", data)
end
if t.context !== nothing
print(io, "\n Context: ", t.context)
end
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::Symbol, orig_expr, value, bt, source::LineNumberNode)
if test_type === :test_error
bt = scrub_exc_stack(bt)
end
if test_type === :test_error || test_type === :nontest_error
bt_str = try # try the latest world for this, since we might have eval'd new code for show
Base.invokelatest(sprint, Base.show_exception_stack, bt; context=stdout)
catch ex
"#=ERROR showing exception stack=# " *
try
sprint(Base.showerror, ex, catch_backtrace(); context=stdout)
catch
"of type " * string(typeof(ex))
end
end
else
bt_str = ""
end
value = try # try the latest world for this, since we might have eval'd new code for show
Base.invokelatest(sprint, show, value, context = :limit => true)
catch ex
"#=ERROR showing error of type " * string(typeof(value)) * "=# " *
try
sprint(Base.showerror, ex, catch_backtrace(); context=stdout)
catch
"of type " * string(typeof(ex))
end
end
return new(test_type,
string(orig_expr),
value,
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))
Serialization.serialize(s, t.source === nothing ? nothing : t.source)
Serialization.serialize(s, t.message_only)
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::Union{Nothing,Vector{Any}}
source::LineNumberNode
end
function eval_test(evaluated::Expr, quoted::Expr, source::LineNumberNode, negate::Bool=false)
evaled_args = evaluated.args
quoted_args = quoted.args
n = length(evaled_args)
kw_suffix = ""
if evaluated.head === :comparison
args = evaled_args
res = true
i = 1
while i < n
a, op, b = args[i], args[i+1], args[i+2]
if res
res = op(a, b)
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]::Expr).args # Keyword arguments from `Expr(:parameters, ...)`
args = evaled_args[3:n]
res = op(args...; kwargs...)
# Create "Evaluated" expression which looks like the original call but has all of
# the arguments evaluated
func_sym = quoted_args[1]::Union{Symbol,Expr}
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 === true ? quoted : sprint(print, quoted, context=(:limit => true)) * 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 ...
@test ex broken=true
@test ex skip=true
Test that the expression `ex` evaluates to `true`.
If executed inside a `@testset`, return a `Pass` `Result` if it does, a `Fail` `Result` if it is
`false`, and an `Error` `Result` if it could not be evaluated.
If executed outside a `@testset`, throw an exception instead of returning `Fail` or `Error`.
# 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`).
You can use any key for the `key=val` arguments, except for `broken` and `skip`,
which have special meanings in the context of `@test`:
* `broken=cond` indicates a test that should pass but currently consistently
fails when `cond==true`. 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`. Regular `@test ex` is
evaluated when `cond==false`.
* `skip=cond` marks a test that should not be executed but should be included in
test summary reporting as `Broken`, when `cond==true`. This can be useful for
tests that intermittently fail, or tests of not-yet-implemented functionality.
Regular `@test ex` is evaluated when `cond==false`.
# Examples
```jldoctest
julia> @test 2 + 2 ≈ 6 atol=1 broken=true
Test Broken
Expression: ≈(2 + 2, 6, atol = 1)
julia> @test 2 + 2 ≈ 5 atol=1 broken=false
Test Passed
julia> @test 2 + 2 == 5 skip=true
Test Broken
Skipped: 2 + 2 == 5
julia> @test 2 + 2 == 4 skip=false
Test Passed
```
!!! compat "Julia 1.7"
The `broken` and `skip` keyword arguments require at least Julia 1.7.
"""
macro test(ex, kws...)
# Collect the broken/skip keywords and remove them from the rest of keywords
broken = [kw.args[2] for kw in kws if kw.args[1] === :broken]
skip = [kw.args[2] for kw in kws if kw.args[1] === :skip]
kws = filter(kw -> kw.args[1] ∉ (:skip, :broken), kws)
# Validation of broken/skip keywords
for (kw, name) in ((broken, :broken), (skip, :skip))
if length(kw) > 1
error("invalid test macro call: cannot set $(name) keyword multiple times")
end
end
if length(skip) > 0 && length(broken) > 0
error("invalid test macro call: cannot set both skip and broken keywords")
end
# Build the test expression
test_expr!("@test", ex, kws...)
orig_ex = Expr(:inert, ex)
result = get_test_result(ex, __source__)
return quote
if $(length(skip) > 0 && esc(skip[1]))
record(get_testset(), Broken(:skipped, $orig_ex))
else
let _do = $(length(broken) > 0 && esc(broken[1])) ? do_broken_test : do_test
_do($result, $orig_ex)
end
end
end
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`. This is equivalent to
[`@test ex broken=true`](@ref @test).
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. This is equivalent to
[`@test ex skip=true`](@ref @test).
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])
# Mark <: and >: as :comparison expressions
elseif isa(ex, Expr) && length(ex.args) == 2 &&
!is_splat(ex.args[1]) && !is_splat(ex.args[2]) &&
Base.operator_precedence(ex.head) == comparison_prec
ex = Expr(:comparison, ex.args[1], ex.head, ex.args[2])
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.current_exceptions(), $(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, orig_expr, result.data, value, result.source) :
Fail(:test, orig_expr, result.data, value, nothing, result.source, false)
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::Vector{Any}, result.source)
end
isa(testres, Pass) || trigger_test_failure_break(result)
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,
a string, regular expression, or list of strings occurring in the displayed error message,
a matching function,
or a value (which will be tested for equality by comparing fields).
Note that `@test_throws` does not support a trailing keyword form.
!!! compat "Julia 1.8"
The ability to specify anything other than a type or a value as `exception` requires Julia v1.8 or later.
# 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
julia> @test_throws "Try sqrt(Complex" sqrt(-1)
Test Passed
Message: "DomainError with -1.0:\\nsqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x))."
```
In the final example, instead of matching a single string it could alternatively have been performed with:
- `["Try", "Complex"]` (a list of strings)
- `r"Try sqrt\\([Cc]omplex"` (a regular expression)
- `str -> occursin("complex", str)` (a matching function)
"""
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
const MACROEXPAND_LIKE = Symbol.(("@macroexpand", "@macroexpand1", "macroexpand"))
# 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
message_only = false
exc = result.exception
# NB: Throwing LoadError from macroexpands is deprecated, but in order to limit
# the breakage in package tests we add extra logic here.
from_macroexpand =
orig_expr isa Expr &&
orig_expr.head in (:call, :macrocall) &&
orig_expr.args[1] in MACROEXPAND_LIKE
if isa(extype, Type)
success =
if from_macroexpand && extype == LoadError && exc isa Exception
Base.depwarn("macroexpand no longer throws a LoadError so `@test_throws LoadError ...` is deprecated and passed without checking the error type!", :do_test_throws)
true
else
isa(exc, extype)
end
elseif isa(extype, Exception) || !isa(exc, Exception)
if extype isa LoadError && !(exc isa LoadError) && typeof(extype.error) == typeof(exc)
extype = extype.error # deprecated
end
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
else
message_only = true
exc = sprint(showerror, exc)
success = contains_warn(exc, extype)
exc = repr(exc)
if isa(extype, AbstractString)
extype = repr(extype)
elseif isa(extype, Function)
extype = "< match function >"
end
end
if success
testres = Pass(:test_throws, orig_expr, extype, exc, result.source, message_only)
else
testres = Fail(:test_throws_wrong, orig_expr, extype, exc, nothing, result.source, message_only)
end
else
testres = Fail(:test_throws_nothing, orig_expr, extype, nothing, nothing, result.source, false)
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
# Duplicate some code from `@test_warn` to allow printing the content of
# `stderr` again to `stderr` here while suppressing it for `@test_warn`.
# If that shouldn't be used, it would be possible to just use
# @test_warn isempty $(esc(expr))
# here.
let fname = tempname()
try
ret = open(fname, "w") do f
redirect_stderr(f) do
$(esc(expr))
end
end
stderr_content = read(fname, String)
print(stderr, stderr_content) # this is helpful for debugging
@test isempty(stderr_content)
ret
finally
rm(fname, force=true)
end
end
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.
Custom `AbstractTestSet` subtypes should call `record` on their parent (if there
is one) to add themselves to the tree of test results. This might be implemented
as:
```julia
if get_testset_depth() != 0
# Attach this test set to the parent test set
parent_ts = get_testset()
record(parent_ts, self)
return self
end
```
"""
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::String
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
#-----------------------------------------------------------------------
"""
ContextTestSet
Passes test failures through to the parent test set, while adding information
about a context object that is being tested.
"""
struct ContextTestSet <: AbstractTestSet
parent_ts::AbstractTestSet
context_name::Union{Symbol, Expr}
context::Any
end
function ContextTestSet(name::Union{Symbol, Expr}, @nospecialize(context))
if (name isa Expr) && (name.head != :tuple)
error("Invalid syntax: $(name)")
end
return ContextTestSet(get_testset(), name, context)
end
record(c::ContextTestSet, t) = record(c.parent_ts, t)
function record(c::ContextTestSet, t::Fail)
context = string(c.context_name, " = ", c.context)
context = t.context === nothing ? context : string(t.context, "\n ", context)
record(c.parent_ts, Fail(t.test_type, t.orig_expr, t.data, t.value, context, t.source, t.message_only))
end
#-----------------------------------------------------------------------
"""
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