DAY 22
0

## Julia裡頭本身就提供了一套很方便的unit test工具 - `Test`

``````@test ex
@test f(args...) key=val ...
``````

``````using Test
julia> x = "b"
"b"
julia> @test typeof(x) == String
Test Passed
julia> @test 5.0/3 ≈ 1.67 atol=0.01
Test Passed
``````

``````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> foo(x) = length(x)^2
julia> @test_throws MethodError foo(:cat)
Test Passed
Thrown: MethodError
``````

``````julia> @testset "Foo()測試" begin
@test foo("a") == 1
@test foo("ab") == 4
@test foo("abc") == 9
end
Test Summary: | Pass  Total
Foo()測試      |    3      3
Test.DefaultTestSet("Foo()測試", Any[], 3, false)

julia> @testset "三角函數測試" begin
θ = 2/3 * π
@test sin(-θ) ≈ -sin(θ)
@test cos(-θ) ≈ cos(θ)
@test sin(2θ) ≈ 2*sin(θ)*cos(θ)
@test cos(2θ) ≈ cos(θ)^2 - sin(θ)^2
end
Test Summary: | Pass  Total

Test.DefaultTestSet("三角函數測試", Any[], 4, false)
``````

``````julia> @testset "foo函數詳細測試" begin
@testset "Animals" begin
@test foo("cat") == 9
@test foo("dog") == foo("cat")
end
@testset "Arrays \$i" for i in 1:3
@test foo(zeros(i)) == i^2
@test foo(fill(1.0, i)) == i^2
end
end
Test Summary: | Pass  Total
foo函數詳細測試 |    8      8
Test.DefaultTestSet("foo函數詳細測試", Any[DefaultTestSet("Animals", Any[], 2, false), DefaultTestSet("Arrays 1", Any[], 2, false), DefaultTestSet("Arrays 2", Any[], 2, false), DefaultTestSet("Arrays 3", Any[], 2, false)], 0, false)
``````

``````julia> f(a, b, c) = b > 1 ? 1 : 1.0
f (generic function with 1 method)

julia> typeof(f(1, 2, 3))
Int64

julia> @code_warntype f(1, 2, 3)
Body::Union{Float64, Int64}
1 1 ─ %1 = (Base.slt_int)(1, b)::Bool
└──      goto #3 if not %1
2 ─      return 1
3 ─      return 1.0
julia> @inferred f(1,2,3)
ERROR: return type Int64 does not match inferred return type Union{Float64, Int64}
Stacktrace:
[1] error(::String) at ./error.jl:33
[2] top-level scope at none:0
julia> @inferred max(1, 2)
2
``````

``````julia> function foo(n)
@info "Doing foo with n=\$n"
for i=1:n
@debug "Iteration \$i"
end
42
end
foo (generic function with 1 method)

julia> @test_logs (:info,"Doing foo with n=2") foo(2)
42

julia> @test_logs (:info,"Doing foo with n=2") (:debug,"Iteration 1") (:debug,"Iteration 2") min_level=Debug foo(2)
Error During Test at REPL[45]:1
Test threw exception
Expression: foo(2)
UndefVarError: Debug not defined
Stacktrace:
[1] top-level scope at none:0
[2] eval(::Module, ::Any) at ./boot.jl:319
[3] eval_user_input(::Any, ::REPL.REPLBackend) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.0/REPL/src/REPL.jl:85
[4] macro expansion at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.0/REPL/src/REPL.jl:117 [inlined]
ERROR: There was an error during testing
``````

### 1 則留言

0

iT邦新手 5 級 ‧ 2018-10-23 22:09:27

https://discourse.julialang.org/t/recommendation-for-logging/4560

@杜岳華，研究一下再跟你說 XD