For languages without classes tests are in my opinion a great way to document functions. For example, when I have the function
function str2int(letter::String) letter = uppercase(letter) @assert occursin(r"[A-Z]+", letter) ch = letter i = Int(ch) - 64 end
then the goal is immediately clear when I read
@test str2int("C") == 3
Unfortunately, all languages I know of tend to put these test in a file far away from the definition of the actual function. When we define these tests right below these functions then any time we load the module all tests will be run, which is not useful in practice either. To solve this I wrote a little macro (thanks to the Julia language for allowing that).
module DTest # `Delayed test`, or `define test`, whatever you like all_dtests = Expr export all_dtests macro dtests(ex) push!(all_dtests, ex) # Returning last evaluated expression to get "Test Passed". esc(:(dtest() = eval.(all_dtests)[end])) end export @dtests end # module
Then to use it I write
using Test include("dtest.jl") using .DTest function str2int(letter::String) letter = uppercase(letter) @assert occursin(r"[A-Z]+", letter) ch = letter i = Int(ch) - 64 end export str2int @dtests begin @test str2int("C") == 3 end
Now I can still load the module
Helpers and its functions without running the tests. To run the tests I call
So far the small macro has been very convenient for me. I am wondering whether it is something I should make a Julia package, or even whether it is a nice addition to the standard library?