-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathruntests.jl
1781 lines (1582 loc) · 59.6 KB
/
runtests.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
using Test, Random
using Test: guardseed
using Serialization
using Distributed: RemoteException
import Logging: Debug, Info, Warn, with_logger
@testset "@test" begin
atol = 1
a = (; atol=2)
@test true
@test 1 == 1
@test 1 != 2
@test ==(1, 1)
@test ==((1, 1)...)
@test 1 ≈ 2 atol=1
@test strip("\t hi \n") == "hi"
@test strip("\t this should fail \n") != "hi"
@test isequal(1, 1)
@test isapprox(1, 1, atol=0.1)
@test isapprox(1, 1; atol=0.1)
@test isapprox(1, 1; [(:atol, 0)]...)
@test isapprox(1, 2; atol)
@test isapprox(1, 3; a.atol)
end
@testset "@test with skip/broken kwargs" begin
# Make sure the local variables can be used in conditions
a = 1
@test 2 + 2 == 4 broken=false
@test error() broken=true
@test !Sys.iswindows() broken=Sys.iswindows()
@test 1 ≈ 2 atol=1 broken=a==2
@test false skip=true
@test true skip=false
@test Grogu skip=isone(a)
@test 41 ≈ 42 rtol=1 skip=false
end
@testset "@test keyword precedence" begin
atol = 2
# post-semicolon keyword, suffix keyword, pre-semicolon keyword
@test isapprox(1, 2, atol=0) atol=1
@test isapprox(1, 3, atol=0; atol=2) atol=1
@test isapprox(1, 2, atol=0; atol)
@test isapprox(1, 3, atol=0; atol) atol=1
end
@testset "@test should only evaluate the arguments once" begin
g = Int[]
f = (x) -> (push!(g, x); x)
@test f(1) == 1
@test g == [1]
empty!(g)
@test isequal(f(2), 2)
@test g == [2]
end
@testset "@test_broken with fail" begin
@test_broken false
@test_broken 1 == 2
@test_broken 1 != 1
@test_broken strip("\t hi \n") != "hi"
@test_broken strip("\t this should fail \n") == "hi"
end
@testset "@test_broken with errors" begin
@test_broken error()
@test_broken absolute_nonsense
end
@testset "@test_skip" begin
@test_skip error()
@test_skip true
@test_skip false
@test_skip gobbeldygook
end
@testset "@test_warn" begin
@test 1234 === @test_nowarn(1234)
@test 5678 === @test_warn("WARNING: foo", begin println(stderr, "WARNING: foo"); 5678; end)
let a
@test_throws UndefVarError(:a, :local) a
@test_nowarn a = 1
@test a === 1
end
end
@testset "@test and elements of an array" begin
a = Array{Float64, 5}(undef, 2, 2, 2, 2, 2)
a[1, 1, 1, 1, 1] = 10
@test a[1, 1, 1, 1, 1] == 10
@test a[1, 1, 1, 1, 1] != 2
end
@test rand() != rand()
@testset "Pass - exception" begin
@test endswith(sprint(show, @test_throws ErrorException error()),
"Thrown: ErrorException")
@test endswith(sprint(show, @test_throws ErrorException("test") error("test")),
"Thrown: ErrorException")
@test endswith(sprint(show, @test_throws "a test" error("a test")),
"Message: \"a test\"")
@test occursin("Message: \"DomainError",
sprint(show, @test_throws r"sqrt\([Cc]omplex" sqrt(-1)))
@test endswith(sprint(show, @test_throws str->occursin("a t", str) error("a test")),
"Message: \"a test\"")
@test endswith(sprint(show, @test_throws ["BoundsError", "access", "1-element", "at index [2]"] [1][2]),
"Message: \"BoundsError: attempt to access 1-element Vector{$Int} at index [2]\"")
@test_throws "\"" throw("\"")
@test_throws Returns(false) throw(Returns(false))
end
# Test printing of Fail results
include("nothrow_testset.jl")
let fails = @testset NoThrowTestSet begin
# 1 - Fail - wrong exception
@test_throws OverflowError error()
# 2 - Fail - no exception
@test_throws OverflowError 1 + 1
# 3 - Fail - comparison
@test 1+1 == 2+2
# 4 - Fail - approximate comparison
@test 1/1 ≈ 2/1
# 5 - Fail - chained comparison
@test 1+0 == 2+0 == 3+0
# 6 - Fail - comparison call
@test ==(1 - 2, 2 - 1)
# 7 - Fail - splatting
@test ==(1:2...)
# 8 - Fail - isequal
@test isequal(0 / 0, 1 / 0)
# 9 - Fail - function splatting
@test isequal(1:2...)
# 10 - Fail - isapprox
@test isapprox(0 / 1, -1 / 0)
# 11 & 12 - Fail - function with keyword
@test isapprox(1 / 2, 2 / 1, atol=1 / 1)
@test isapprox(1 - 2, 2 - 1; atol=1 - 1)
# 13 - Fail - function keyword splatting
k = [(:atol, 0), (:nans, true)]
@test isapprox(1, 2; k...)
# 14 - Fail - call negation
@test !isequal(1, 2 - 1)
# 15 - Fail - comparison negation
@test !(2 + 3 == 1 + 4)
# 16 - Fail - chained negation
@test !(2 + 3 == 1 + 4 == 5)
# 17 - Fail - isempty
nonempty = [1, 2, 3]
@test isempty(nonempty)
str1 = "Hello"
str2 = "World"
# 18 - Fail - occursin
@test occursin(str1, str2)
# 19 - Fail - startswith
@test startswith(str1, str2)
# 20 - Fail - endswith
@test endswith(str1, str2)
# 21 - Fail - contains
@test contains(str1, str2)
# 22 - Fail - Type Comparison
@test typeof(1) <: typeof("julia")
# 23 - 26 - Fail - wrong message
@test_throws "A test" error("a test")
@test_throws r"sqrt\([Cc]omplx" sqrt(-1)
@test_throws str->occursin("a T", str) error("a test")
@test_throws ["BoundsError", "acquire", "1-element", "at index [2]"] [1][2]
# 27 - Fail - issetequal
a = [1, 2]
b = [1, 3]
@test issetequal(a, b)
end
for fail in fails
@test fail isa Test.Fail
end
let str = sprint(show, fails[1])
@test occursin("Expression: error()", str)
@test occursin("Thrown: ErrorException", str)
end
let str = sprint(show, fails[2])
@test occursin("Expression: 1 + 1", str)
@test occursin("No exception thrown", str)
end
let str = sprint(show, fails[3])
@test occursin("Expression: 1 + 1 == 2 + 2", str)
@test occursin("Evaluated: 2 == 4", str)
end
let str = sprint(show, fails[4])
@test occursin("Expression: 1 / 1 ≈ 2 / 1", str)
@test occursin("Evaluated: 1.0 ≈ 2.0", str)
end
let str = sprint(show, fails[5])
@test occursin("Expression: 1 + 0 == 2 + 0 == 3 + 0", str)
@test occursin("Evaluated: 1 == 2 == 3", str)
end
let str = sprint(show, fails[6])
@test occursin("Expression: 1 - 2 == 2 - 1", str)
@test occursin("Evaluated: -1 == 1", str)
end
let str = sprint(show, fails[7])
@test occursin("Expression: (==)(1:2...)", str)
@test !occursin("Evaluated", str)
end
let str = sprint(show, fails[8])
@test occursin("Expression: isequal(0 / 0, 1 / 0)", str)
@test occursin("Evaluated: isequal(NaN, Inf)", str)
end
let str = sprint(show, fails[9])
@test occursin("Expression: isequal(1:2...)", str)
@test occursin("Evaluated: isequal(1, 2)", str)
end
let str = sprint(show, fails[10])
@test occursin("Expression: isapprox(0 / 1, -1 / 0)", str)
@test occursin("Evaluated: isapprox(0.0, -Inf)", str)
end
let str = sprint(show, fails[11])
@test occursin("Expression: isapprox(1 / 2, 2 / 1, atol = 1 / 1)", str)
@test occursin("Evaluated: isapprox(0.5, 2.0; atol = 1.0)", str)
end
let str = sprint(show, fails[12])
@test occursin("Expression: isapprox(1 - 2, 2 - 1; atol = 1 - 1)", str)
@test occursin("Evaluated: isapprox(-1, 1; atol = 0)", str)
end
let str = sprint(show, fails[13])
@test occursin("Expression: isapprox(1, 2; k...)", str)
@test occursin("Evaluated: isapprox(1, 2; atol = 0, nans = true)", str)
end
let str = sprint(show, fails[14])
@test occursin("Expression: !(isequal(1, 2 - 1))", str)
@test occursin("Evaluated: !(isequal(1, 1))", str)
end
let str = sprint(show, fails[15])
@test occursin("Expression: !(2 + 3 == 1 + 4)", str)
@test occursin("Evaluated: !(5 == 5)", str)
end
let str = sprint(show, fails[16])
@test occursin("Expression: !(2 + 3 == 1 + 4 == 5)", str)
@test occursin("Evaluated: !(5 == 5 == 5)", str)
end
let str = sprint(show, fails[17])
@test occursin("Expression: isempty(nonempty)", str)
@test occursin("Evaluated: isempty([1, 2, 3])", str)
end
let str = sprint(show, fails[18])
@test occursin("Expression: occursin(str1, str2)", str)
@test occursin("Evaluated: occursin(\"Hello\", \"World\")", str)
end
let str = sprint(show, fails[19])
@test occursin("Expression: startswith(str1, str2)", str)
@test occursin("Evaluated: startswith(\"Hello\", \"World\")", str)
end
let str = sprint(show, fails[20])
@test occursin("Expression: endswith(str1, str2)", str)
@test occursin("Evaluated: endswith(\"Hello\", \"World\")", str)
end
let str = sprint(show, fails[21])
@test occursin("Expression: contains(str1, str2)", str)
@test occursin("Evaluated: contains(\"Hello\", \"World\")", str)
end
let str = sprint(show, fails[22])
@test occursin("Expression: typeof(1) <: typeof(\"julia\")", str)
@test occursin("Evaluated: $(typeof(1)) <: $(typeof("julia"))", str)
end
let str = sprint(show, fails[23])
@test occursin("Expected: \"A test\"", str)
@test occursin("Message: \"a test\"", str)
end
let str = sprint(show, fails[24])
@test occursin("Expected: r\"sqrt\\([Cc]omplx\"", str)
@test occursin(r"Message: .*Try sqrt\(Complex", str)
end
let str = sprint(show, fails[25])
@test occursin("Expected: < match function >", str)
@test occursin("Message: \"a test\"", str)
end
let str = sprint(show, fails[26])
@test occursin("Expected: [\"BoundsError\", \"acquire\", \"1-element\", \"at index [2]\"]", str)
@test occursin(r"Message: \"BoundsError.* 1-element.*at index \[2\]", str)
end
let str = sprint(show, fails[27])
@test occursin("Expression: issetequal(a, b)", str)
@test occursin("Evaluated: issetequal([1, 2], [1, 3])", str)
end
end
struct BadError <: Exception end
Base.show(io::IO, ::BadError) = throw("I am a bad error")
let errors = @testset NoThrowTestSet begin
# 1 - Error - unexpected pass
@test_broken true
# 2 - Error - converting a call into a comparison
@test ==(1, 1:2...)
# 3 - Error - objects with broken show
@test throw(BadError())
@test BadError()
throw(BadError())
end
for err in errors
@test err isa Test.Error
end
let str = sprint(show, errors[1])
@test occursin("Unexpected Pass", str)
@test occursin("Expression: true", str)
end
let str = sprint(show, errors[2])
@test occursin("Expression: ==(1, 1:2...)", str)
@test occursin("MethodError: no method matching ==(::$Int, ::$Int, ::$Int)", str)
end
let str = sprint(show, errors[3])
@test occursin("Expression: throw(BadError())\n #=ERROR showing exception stack=# \"I am a bad error\"\n Stacktrace:\n", str)
end
let str = sprint(show, errors[4])
@test occursin("Expression: BadError()\n Value: #=ERROR showing error of type $BadError=# \"I am a bad error\"\nStacktrace:\n", str)
end
let str = sprint(show, errors[5])
@test occursin("Got exception outside of a @test\n #=ERROR showing exception stack=# \"I am a bad error\"\n Stacktrace:\n", str)
end
end
let retval_tests = @testset NoThrowTestSet begin
ts = Test.DefaultTestSet("Mock for testing retval of record(::DefaultTestSet, ::T <: Result) methods")
pass_mock = Test.Pass(:test, 1, 2, 3, LineNumberNode(0, "A Pass Mock"))
@test Test.record(ts, pass_mock) isa Test.Pass
error_mock = Test.Error(:test, 1, 2, 3, LineNumberNode(0, "An Error Mock"))
@test Test.record(ts, error_mock) isa Test.Error
fail_mock = Test.Fail(:test, 1, 2, 3, nothing, LineNumberNode(0, "A Fail Mock"), false)
@test Test.record(ts, fail_mock) isa Test.Fail
broken_mock = Test.Broken(:test, LineNumberNode(0, "A Broken Mock"))
@test Test.record(ts, broken_mock) isa Test.Broken
end
for retval_test in retval_tests
@test retval_test isa Test.Pass
end
end
@testset "printing of a TestSetException" begin
tse_str = sprint(show, Test.TestSetException(1, 2, 3, 4, Vector{Union{Test.Error, Test.Fail}}()))
@test occursin("1 passed", tse_str)
@test occursin("2 failed", tse_str)
@test occursin("3 errored", tse_str)
@test occursin("4 broken", tse_str)
end
@test Test.finish(Test.FallbackTestSet()) !== nothing
OLD_STDOUT = stdout
OLD_STDERR = stderr
catch_out = IOStream("")
catch_err = IOStream("")
rde, wre = redirect_stderr()
rdo, wro = redirect_stdout()
# test that FallbackTestSet will throw immediately
cmd = `$(Base.julia_cmd()) --startup-file=no --depwarn=error test_exec.jl`
@test !success(pipeline(cmd))
@testset "no errors" begin
@test true
@test 1 == 1
end
# Test entirely empty test set
@testset "outer" begin
@testset "inner" begin
end
end
@testset "testset types" begin
ts = @testset "@testset should return the testset" begin
@test true
end
@test typeof(ts) == Test.DefaultTestSet
@test ts.n_passed == 1
tss = @testset "@testset/for should return an array of testsets: $i" for i in 1:3
@test true
end
@test length(tss) == 3
@test typeof(tss[1]) == Test.DefaultTestSet
@test tss[1].n_passed == 1
end
@testset "accounting" begin
local ts, fails
try
ts = @testset "outer" begin
@testset "inner1" begin
@test true
@test false
@test 1 == 1
@test 2 === :foo
@test 3 == 3
@testset "d" begin
@test 4 == 4
end
@testset begin
@test :blank !== :notblank
end
end
@testset "inner1" begin
@test 1 == 1
@test 2 == 2
@test 3 === :bar
@test 4 == 4
@test_throws ErrorException 1+1
@test_throws ErrorException error()
@test_throws RemoteException error()
@testset "errrrr" begin
@test "not bool"
@test error()
end
error("exceptions in testsets should be caught")
@test 1 == 1 # this test will not be run
end
@testset "loop with desc" begin
@testset "loop1 $T" for T in (Float32, Float64)
@test 1 == T(1)
end
end
@testset "loops without desc" begin
@testset for T in (Float32, Float64)
@test 1 == T(1)
end
@testset for T in (Float32, Float64), S in (Int32,Int64)
@test S(1) == T(1)
end
end
@testset "some loops fail" begin
@testset for i in 1:5
@test i <= 4
end
# should add 3 errors and 3 passing tests
@testset for i in 1:6
iseven(i) || error("error outside of test")
@test true # only gets run if the above passed
end
end
end
# These lines shouldn't be called
error("No exception was thrown!")
catch ex
redirect_stdout(OLD_STDOUT)
redirect_stderr(OLD_STDERR)
ex
end
@testset "ts results" begin
@test isa(ts, Test.DefaultTestSet)
tc = Test.get_test_counts(ts)
total_pass = tc.passes + tc.cumulative_passes
total_fail = tc.fails + tc.cumulative_fails
total_error = tc.errors + tc.cumulative_errors
total_broken = tc.broken + tc.cumulative_broken
@test total_pass == 24
@test total_fail == 6
@test total_error == 6
@test total_broken == 0
end
ts.anynonpass = false
deleteat!(Test.get_testset().results, 1)
end
@test .1+.1+.1 ≈ .3
@test .1+.1+.1 ≉ .4
ts = @testset "@testset should return the testset" begin
@test true
end
@test typeof(ts) == Test.DefaultTestSet
@test ts.n_passed == 1
tss = @testset "@testset/for should return an array of testsets: $i" for i in 1:3
@test true
end
@test length(tss) == 3
@test typeof(tss[1]) == Test.DefaultTestSet
@test tss[1].n_passed == 1
# Issue #17908 (return)
testset_depth17908 = Test.get_testset_depth()
@testset for i in 1:3
i > 1 && return
@test i == 1
end
# The return aborts the control flow so the expression above doesn't return a
# value. The only thing we can test is whether the testset is properly popped.
# Do not use `@test` since the issue this is testing will swallow the error.
@assert testset_depth17908 == Test.get_testset_depth()
# Issue #17462 and Issue #17908 (break, continue)
testset_depth17462 = Test.get_testset_depth()
counter_17462_pre = 0
counter_17462_post = 0
tss17462 = @testset for x in [1,2,3,4]
global counter_17462_pre, counter_17462_post
counter_17462_pre += 1
if x == 1
@test counter_17462_pre == x
continue
@test false
elseif x == 3
@test counter_17462_pre == x
break
@test false
elseif x == 4
@test false
else
@test counter_17462_pre == x
@test x == 2
@test counter_17462_post == 0
end
counter_17462_post += 1
end
# Do not use `@test` since the issue this is testing will swallow the error.
# Same for the `@assert` in the for loop below
@assert testset_depth17462 == Test.get_testset_depth()
@assert length(tss17462) == 3
for ts17462 in tss17462
@assert isa(ts17462, Test.DefaultTestSet)
end
@test counter_17462_pre == 3
@test counter_17462_post == 1
# Issue #21008
ts = try
@testset "@test_broken and @test_skip should not give an exception" begin
@test_broken false
@test_skip true
@test_skip false
end
catch
nothing # Shouldn't get here
end
@test ts isa Test.DefaultTestSet
# now we're done running tests with DefaultTestSet so we can go back to stdout
redirect_stdout(OLD_STDOUT)
redirect_stderr(OLD_STDERR)
# import the methods needed for defining our own testset type
import Test: record, finish
using Test: get_testset_depth, get_testset
using Test: AbstractTestSet, Result, Pass, Fail, Error
struct CustomTestSet <: Test.AbstractTestSet
description::String
foo::Int
results::Vector
# constructor takes a description string and options keyword arguments
CustomTestSet(desc; foo=1) = new(desc, foo, [])
end
record(ts::CustomTestSet, child::AbstractTestSet) = push!(ts.results, child)
record(ts::CustomTestSet, res::Result) = push!(ts.results, res)
function finish(ts::CustomTestSet)
# just record if we're not the top-level parent
if get_testset_depth() > 0
record(get_testset(), ts)
end
ts
end
ts = @testset CustomTestSet "Testing custom testsets" begin
# this testset should inherit the parent testset type
@testset "custom testset inner 1" begin
@test true
@test false
@test error("this error will be reported as an error")
@test_throws ErrorException nothing
@test_throws ErrorException error("this error is a success")
end
# this testset has its own testset type
@testset CustomTestSet foo=4 "custom testset inner 2" begin
# this testset should inherit the type, but not the argument. If a particular
# testset type wants inheritance behavior they should implement it themselves
# using get_testset() in the constructor
@testset "custom testset inner 2 inner 1" begin
@test true
end
# make sure the RHS can use computed values, also tests options without
# specifying the testset type
@testset foo=(1+2) "custom testset inner 2 inner 2" begin
@test true
end
end
end
@test typeof(ts) == CustomTestSet
@test ts.foo == 1
@test ts.description == "Testing custom testsets"
@test typeof(ts.results[1]) == CustomTestSet
@test ts.results[1].description == "custom testset inner 1"
@test ts.results[1].foo == 1
@test typeof(ts.results[1].results[1]) == Pass
@test typeof(ts.results[1].results[2]) == Fail
@test typeof(ts.results[1].results[3]) == Error
@test typeof(ts.results[1].results[4]) == Fail
@test typeof(ts.results[1].results[5]) == Pass
@test typeof(ts.results[2]) == CustomTestSet
@test ts.results[2].description == "custom testset inner 2"
@test ts.results[2].foo == 4
@test typeof(ts.results[2].results[1]) == CustomTestSet
@test ts.results[2].results[1].foo == 1
@test typeof(ts.results[2].results[1].results[1]) == Pass
@test typeof(ts.results[2].results[2]) == CustomTestSet
@test ts.results[2].results[2].foo == 3
# test custom testset types on testset/for
tss = @testset CustomTestSet foo=3 "custom testset $i" for i in 1:6
@testset "inner testset $i-$j" for j in 1:3
@test iseven(i + j)
end
# make sure a testset within a testset/for works
@testset "inner testset $i" begin
@test iseven(i)
end
end
for i in 1:6
@test typeof(tss[i]) == CustomTestSet
@test tss[i].foo == 3
for j in 1:3
@test typeof(tss[i].results[j]) == CustomTestSet
@test tss[i].results[j].foo == 1
@test typeof(tss[i].results[j].results[1]) == (iseven(i+j) ? Pass : Fail)
end
@test typeof(tss[i].results[4]) == CustomTestSet
@test typeof(tss[i].results[4].results[1]) == (iseven(i) ? Pass : Fail)
end
# test that second argument is escaped correctly
foo = 3
tss = @testset CustomTestSet foo=foo "custom testset - escaping" begin
@test true
end
@test tss.foo == 3
# test @inferred
uninferable_function(i) = (1, "1")[i]
uninferable_small_union(i) = (1, nothing)[i]
@test_throws ErrorException @inferred(uninferable_function(1))
@test @inferred(identity(1)) == 1
@test @inferred(Nothing, uninferable_small_union(1)) === 1
@test @inferred(Nothing, uninferable_small_union(2)) === nothing
@test_throws ErrorException @inferred(Missing, uninferable_small_union(1))
@test_throws ErrorException @inferred(Missing, uninferable_small_union(2))
@test_throws ArgumentError @inferred(nothing, uninferable_small_union(1))
# Ensure @inferred only evaluates the arguments once
inferred_test_global = 0
function inferred_test_function()
global inferred_test_global
inferred_test_global += 1
true
end
@test @inferred inferred_test_function()
@test inferred_test_global == 1
struct SillyArray <: AbstractArray{Float64,1} end
Base.getindex(a::SillyArray, i) = rand() > 0.5 ? 0 : false
@testset "@inferred works with A[i] expressions" begin
@test (@inferred (1:3)[2]) == 2
test_result = @test_throws ErrorException (@inferred SillyArray()[2])
@test occursin("Bool", test_result.value.msg)
end
# Issue #14928
# Make sure abstract error type works.
@test_throws Exception error("")
# Issue #17105
# @inferred with kwargs
inferable_kwtest(x; y=1) = 2x
uninferable_kwtest(x; y=1) = 2x+y
@test (@inferred inferable_kwtest(1)) == 2
@test (@inferred inferable_kwtest(1; y=1)) == 2
@test (@inferred uninferable_kwtest(1)) == 3
@test (@inferred uninferable_kwtest(1; y=2)) == 4
@test_throws ErrorException @testset "$(error())" for i in 1:10
end
@test_throws ErrorException @testset "$(error())" begin
end
@testset "backtraces in test errors" begin
local f = tempname()
write(f,
"""
using Test
@testset begin
@test 1==2
@test_throws MethodError 1
end
""")
local msg = read(pipeline(ignorestatus(`$(Base.julia_cmd()) --startup-file=no --color=no $f`), stderr=devnull), String)
@test !occursin("do_test(", msg)
@test !occursin("include(", msg)
@test occursin("at " * f * ":3", msg)
@test occursin("at " * f * ":4", msg)
rm(f; force=true)
end
@testset "provide informative location in backtrace for test failures" begin
win2unix(filename) = replace(filename, "\\" => '/')
utils = win2unix(tempname())
write(utils,
"""
function test_properties2(value)
@test isodd(value)
end
""")
included = win2unix(tempname())
write(included,
"""
@testset "Other tests" begin
@test 1 + 1 == 3
test_properties2(2)
end
test_properties2(8)
# Test calls to `@test` and `@testset` with no file/lineno information (__source__ == nothing).
eval(Expr(:macrocall, Symbol("@test"), nothing, :false))
eval(Expr(:macrocall, Symbol("@testset"), nothing, "Testset without source", quote
@test false
@test error("failed")
end))
""")
runtests = win2unix(tempname())
write(runtests,
"""
using Test
include("$utils")
function test_properties(value)
@test isodd(value)
end
@testset "Tests" begin
test_properties(8)
@noinline test_properties(8)
test_properties2(8)
include("$included")
end
""")
msg = read(pipeline(ignorestatus(`$(Base.julia_cmd()) --startup-file=no --color=no $runtests`), stderr=devnull), String)
msg = win2unix(msg)
regex = r"((?:Tests|Other tests|Testset without source): Test Failed (?:.|\n)*?)\n\nStacktrace:(?:.|\n)*?(?=\n(?:Tests|Other tests))"
failures = map(eachmatch(regex, msg)) do m
m = match(r"(Tests|Other tests|Testset without source): .*? at (.*?)\n Expression: (.*)(?:.|\n)*\n+Stacktrace:\n((?:.|\n)*)", m.match)
(; testset = m[1], source = m[2], ex = m[3], stacktrace = m[4])
end
@test length(failures) == 8 # 8 failed tests
@test count(contains("Error During Test"), split(msg, '\n')) == 1 # 1 error
test_properties_macro_source = runtests * ":6"
test_properties2_macro_source = utils * ":2"
fail = failures[1]; lines = split(fail.stacktrace, '\n')
@test length(lines)/2 ≤ 6
@test fail.testset == "Tests" && fail.source == test_properties_macro_source && fail.ex == "isodd(value)"
@test count(contains(runtests * ":10"), lines) == 2 # @testset + test
fail = failures[2]; lines = split(fail.stacktrace, '\n')
@test length(lines)/2 ≤ 6
@test fail.testset == "Tests" && fail.source == test_properties_macro_source && fail.ex == "isodd(value)"
@test count(contains(runtests * ":10"), lines) == 1 # @testset
@test count(contains(runtests * ":11"), lines) == 1 # test
fail = failures[3]; lines = split(fail.stacktrace, '\n')
@test length(lines)/2 ≤ 6
@test fail.testset == "Tests" && fail.source == test_properties2_macro_source && fail.ex == "isodd(value)"
@test count(contains(runtests * ":10"), lines) == 1 # @testset
@test count(contains(runtests * ":12"), lines) == 1 # test
fail = failures[4]; lines = split(fail.stacktrace, '\n')
@test length(lines)/2 ≤ 5
@test fail.testset == "Other tests" && fail.source == included * ":2" && fail.ex == "1 + 1 == 3"
@test count(contains(included * ":2"), lines) == 2 # @testset + test
@test count(contains(runtests * ":10"), lines) == 0 # @testset (stop at the innermost testset)
fail = failures[5]; lines = split(fail.stacktrace, '\n')
@test length(lines)/2 ≤ 6
@test fail.testset == "Other tests" && fail.source == test_properties2_macro_source && fail.ex == "isodd(value)"
@test count(contains(included * ":2"), lines) == 1 # @testset
@test count(contains(included * ":3"), lines) == 1 # test
@test count(contains(runtests * ":10"), lines) == 0 # @testset (stop at the innermost testset)
fail = failures[6]; lines = split(fail.stacktrace, '\n')
@test length(lines)/2 ≤ 8
@test fail.testset == "Tests" && fail.source == test_properties2_macro_source && fail.ex == "isodd(value)"
@test count(contains(runtests * ":10"), lines) == 1 # @testset
@test count(contains(runtests * ":14"), lines) == 1 # include
@test count(contains(included * ":5"), lines) == 1 # test
fail = failures[7]; lines = split(fail.stacktrace, '\n')
@test length(lines)/2 ≤ 9
@test fail.testset == "Tests" && fail.source == "none:0" && fail.ex == "false"
@test count(contains(runtests * ":10"), lines) == 1 # @testset
@test count(contains(runtests * ":14"), lines) == 1 # include
@test count(contains(included * ":8"), lines) == 1 # test
fail = failures[8]; lines = split(fail.stacktrace, '\n')
@test length(lines)/2 ≤ 5
@test fail.testset == "Testset without source" && fail.source == included * ":10" && fail.ex == "false"
@test count(contains(included * ":10"), lines) == 2 # @testset + test
@test count(contains(runtests * ":10"), lines) == 0 # @testset (stop at the innermost testset)
end
let io = IOBuffer()
exc = Test.TestSetException(1,2,3,4,Vector{Union{Test.Error, Test.Fail}}())
Base.showerror(io, exc, backtrace())
@test !occursin("backtrace()", String(take!(io)))
end
@testset "#19750" begin
io = IOBuffer()
exc = Test.TestSetException(1,2,3,4,Vector{Union{Test.Error, Test.Fail}}())
Base.showerror(io, exc, backtrace())
@test !occursin("backtrace()", String(take!(io)))
exc = Test.FallbackTestSetException("msg")
Base.showerror(io, exc, backtrace())
str = String(take!(io))
@test occursin("msg", str)
@test !occursin("backtrace()", str)
end
let msg = read(pipeline(ignorestatus(`$(Base.julia_cmd()) --startup-file=no --color=no -e '
using Test
foo(x) = length(x)^2
@testset "Foo Tests" begin
@testset "Animals" begin
@testset "Felines" begin
@test foo("cat") == 9
end
@testset "Canines" begin
@test foo("dog") == 11
end
end
@testset "Arrays" begin
@test foo(zeros(2)) == 4
@test foo(fill(1., 4)) == 15
end
end'`), stderr=devnull), String)
@test occursin(r"""
Test Summary: \| Pass Fail Total +Time
Foo Tests \| 2 2 4 \s*\d*\.\ds
Animals \| 1 1 2 \s*\d*\.\ds
Felines \| 1 1 \s*\d*\.\ds
Canines \| 1 1 \s*\d*\.\ds
Arrays \| 1 1 2 \s*\d*\.\ds
""", msg)
end
# 20489
let msg = split(read(pipeline(ignorestatus(`$(Base.julia_cmd()) --startup-file=no --color=no -e '
Test.print_test_results(Test.DefaultTestSet(""))'`), stderr=devnull), String), "\n")[1]
@test msg == rstrip(msg)
end
@testset "test guarded Random.seed!" begin
seed = rand(UInt)
orig = copy(Random.default_rng())
@test guardseed(()->rand(), seed) == guardseed(()->rand(), seed)
@test guardseed(()->rand(Int), seed) == guardseed(()->rand(Int), seed)
r1, r2 = MersenneTwister(0), MersenneTwister(0)
a, b = guardseed(r1) do
Random.seed!(r1, 0)
rand(r1), rand(r1, Int)
end::Tuple{Float64,Int}
c, d = guardseed(r2) do
Random.seed!(r2, 0)
rand(r2), rand(r2, Int)
end::Tuple{Float64,Int}
@test a == c == rand(r1) == rand(r2)
@test b == d == rand(r1, Int) == rand(r2, Int)
@test orig == Random.default_rng()
@test rand(orig) == rand()
end
@testset "file info in test errors" begin
local f = tempname()
write(f,
"""
using Test
@testset begin
@test 1==2
@test_throws UndefVarError 1
@test_broken 1 == 1
end
""")
local msg = read(pipeline(ignorestatus(`$(Base.julia_cmd()) --startup-file=no --color=no $f`), stderr=devnull), String)
@test occursin("at " * f * ":" * "3", msg)
@test occursin("at " * f * ":" * "4", msg)
@test occursin("at " * f * ":" * "5", msg)
rm(f; force=true)
end
# issue #24919
@testset "≈ with atol" begin
local cmd = `$(Base.julia_cmd()) --startup-file=no --color=no`
f(src) = read(pipeline(ignorestatus(`$cmd -e $src`), stderr=devnull), String)
msg = f("""
using Test
x, y = 0.9, 0.1
@test x ≈ y atol=0.01
""")
@test occursin("Evaluated: 0.9 ≈ 0.1 (atol=0.01)", msg)
msg = f("""
using Test
x, y = 0.9, 0.1
@test x ≈ y nans=true atol=0.01
""")
@test occursin("Evaluated: 0.9 ≈ 0.1 (nans=true, atol=0.01)", msg)
end
erronce() = @error "an error" maxlog=1
@testset "@test_logs" begin
function foo(n)
@info "Doing foo with n=$n"
for i=1:n
@debug "Iteration $i"
end
end
@test_logs (Info,"Doing foo with n=2") foo(2)
# Log pattern matching
# Regex
@test_logs (Info,r"^Doing foo with n=[0-9]+$") foo(10)
@test_logs (Info,r"^Doing foo with n=[0-9]+$") foo(1)
# Level symbols
@test_logs (:debug,) min_level=Debug @debug "foo"
@test_logs (:info,) @info "foo"
@test_logs (:warn,) @warn "foo"
@test_logs (:error,) @error "foo"
# Pass through so the value of the expression can also be tested
@test (@test_logs (Info,"blah") (@info "blah"; 42)) == 42
# Debug level log collection
@test_logs (Info,"Doing foo with n=2") (Debug,"Iteration 1") (Debug,"Iteration 2") min_level=Debug foo(2)
@test_logs (Debug,"Iteration 5") min_level=Debug match_mode=:any foo(10)
# Respect `maxlog` (#41625). We check we only find one logging message.
@test_logs (:error, "an error") (erronce(); erronce())
# Test `respect_maxlog=false`:
test_logger = Test.TestLogger(; respect_maxlog=false)
with_logger(test_logger) do
erronce()
erronce()
end
@test length(test_logger.logs) == 2
# Test failures
fails = @testset NoThrowTestSet "check that @test_logs detects bad input" begin