|
| 1 | +module InlineTest |
| 2 | + |
| 3 | +export @addtest, runtests, @testset, @test, @test_throws |
| 4 | + |
| 5 | +using Test: @test, @test_throws, @testset |
| 6 | +import Test |
| 7 | + |
| 8 | +function tests(m) |
| 9 | + if !isdefined(m, :__INLINE_TESTS__) |
| 10 | + @eval m __INLINE_TESTS__ = Dict{AbstractString, Expr}() |
| 11 | + end |
| 12 | + m.__INLINE_TESTS__ |
| 13 | +end |
| 14 | + |
| 15 | +function addtest(args::Tuple, m::Module) |
| 16 | + n = findfirst(a -> a isa String, args) |
| 17 | + desc = n == nothing ? nothing : args[n] |
| 18 | + desc != nothing && haskey(tests(m), desc) && @warn("Test $desc already defined for module $(string(m)), overwriting") |
| 19 | + if desc == nothing |
| 20 | + i = 1 |
| 21 | + while haskey(tests(m), "anonymous test $i") |
| 22 | + i += 1 |
| 23 | + end |
| 24 | + desc = "anonymous test $i" |
| 25 | + end |
| 26 | + tests(m)[desc] = :(@testset($(args...))) |
| 27 | + nothing |
| 28 | +end |
| 29 | + |
| 30 | +macro addtest(args...) |
| 31 | + Expr(:call, :addtest, args, __module__) |
| 32 | +end |
| 33 | + |
| 34 | +function runtests(m::Module) |
| 35 | + tss = collect(values(tests(m))) |
| 36 | + tsm = :(@testset $("Tests for module $m") begin |
| 37 | + $(tss...) |
| 38 | + end) |
| 39 | + Core.eval(m, tsm) |
| 40 | + nothing |
| 41 | +end |
| 42 | + |
| 43 | +function runtests() |
| 44 | + foreach(values(Base.loaded_modules)) do m |
| 45 | + if isdefined(m, :__INLINE_TESTS__) && m != InlineTest && m != InlineTest.InlineTestTest |
| 46 | + ts = runtests(m) |
| 47 | + end |
| 48 | + end |
| 49 | +end |
| 50 | + |
| 51 | + |
| 52 | +module InlineTestTest |
| 53 | + |
| 54 | +using ..InlineTest |
| 55 | +@addtest "test Test in sub-module" begin |
| 56 | + @test 1 == 1 |
| 57 | +end |
| 58 | + |
| 59 | +end # module InlineTestTest |
| 60 | + |
| 61 | +@addtest "self test" begin |
| 62 | + @assert typeof(@__MODULE__) == Module |
| 63 | + @test 1 != 2 |
| 64 | + runtests(InlineTestTest) |
| 65 | +end |
| 66 | + |
| 67 | +end # module InlineTest |
0 commit comments