diff --git a/Project.toml b/Project.toml index f54f715..946ba2a 100644 --- a/Project.toml +++ b/Project.toml @@ -4,7 +4,7 @@ keywords = ["testing", "mocking"] license = "MIT" desc = "Allows Julia function calls to be temporarily overloaded for purpose of testing" author = ["Curtis Vogt"] -version = "0.7.5" +version = "0.7.6" [deps] Compat = "34da2185-b29b-5c13-b0c7-acf172513d20" diff --git a/src/Mocking.jl b/src/Mocking.jl index d29c179..1598264 100644 --- a/src/Mocking.jl +++ b/src/Mocking.jl @@ -15,7 +15,7 @@ include("deprecated.jl") activated() = false """ - Mocking.activate() + Mocking.activate([func]) Enable `@mock` call sites to allow for calling patches instead of the original function. """ @@ -25,6 +25,18 @@ function activate() return nothing end +function activate(f) + old = activated() + try + activate() + Base.invokelatest(f) + finally + if (Base.invokelatest(activated) != old) + @eval activated() = $old + end + end +end + """ Mocking.deactivate() diff --git a/test/activate.jl b/test/activate.jl new file mode 100644 index 0000000..4e76fd3 --- /dev/null +++ b/test/activate.jl @@ -0,0 +1,29 @@ +@testset "activate(func)" begin + add1(x) = x + 1 + patch = @patch add1(x) = x + 42 + + # Starting with Mocking enabled. + Mocking.activate() + @assert Mocking.activated() + Mocking.activate() do + apply(patch) do + @test (@mock add1(2)) == 44 + end + end + @test Mocking.activated() + + # Starting with Mocking disabled. + # Make sure to leave it enabled for the rest of the tests. + try + Mocking.deactivate() + @assert !Mocking.activated() + Mocking.activate() do + apply(patch) do + @test (@mock add1(2)) == 44 + end + end + @test !Mocking.activated() + finally + Mocking.activate() + end +end diff --git a/test/runtests.jl b/test/runtests.jl index feb600e..4341531 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -30,4 +30,5 @@ using Mocking: anon_morespecific, anonymous_signature, dispatch, type_morespecif include("nested_apply.jl") include("async.jl") include("issues.jl") + include("activate.jl") end