Skip to content

Commit

Permalink
Added support for kwargs in @mock calls. (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
rofinn authored and omus committed Feb 6, 2018
1 parent db52245 commit 49dff5f
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
9 changes: 5 additions & 4 deletions src/Mocking.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ __precompile__(true)

module Mocking

import Compat: uninitialized, @info, @warn
import Compat: uninitialized, @info, @warn, invokelatest

if VERSION < v"0.7.0-DEV.3455"
hasmethod(f, t) = Base.method_exists(f, t)
Expand Down Expand Up @@ -217,7 +217,8 @@ macro mock(expr)

func = expr.args[1]
func_name = QuoteNode(func)
args = expr.args[2:end]
args = filter(x -> !Mocking.iskwarg(x), expr.args[2:end])
kwargs = extract_kwargs(expr)

env_var = gensym("env")
args_var = gensym("args")
Expand All @@ -231,9 +232,9 @@ macro mock(expr)
local $env_var = Mocking.get_active_env()
local $args_var = tuple($(args...))
if Mocking.ismocked($env_var, $func_name, $args_var)
Base.invokelatest($env_var.mod.$func, $args_var...)
Mocking.invokelatest($env_var.mod.$func, $args_var...; $(kwargs...))
else
$func($args_var...)
$func($args_var...; $(kwargs...))
end
end

Expand Down
24 changes: 24 additions & 0 deletions src/expr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,27 @@ function rewrite_do(expr::Expr)
call, body = expr.args
Expr(:call, call.args[1], body, call.args[2:end]...)
end

iskwarg(x::Any) = isa(x, Expr) && (x.head === :parameters || x.head === :kw)

"""
extract_kwargs(expr::Expr) -> Vector{Expr}
Extract the :parameters and :kw value into an array of :kw expressions
we don't evaluate any expressions for values yet though.
"""
function extract_kwargs(expr::Expr)
kwargs = Expr[]
for x in expr.args[2:end]
if Mocking.iskwarg(x)
if x.head === :parameters
for kw in x.args
push!(kwargs, kw)
end
else
push!(kwargs, x)
end
end
end
return kwargs
end
5 changes: 4 additions & 1 deletion test/optional.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ end
patch = @patch hourvalue(; hour::Hour=Hour(21)) = 2 * Dates.value(hour)
apply(patch) do
@test (@mock hourvalue()) == 42
# @test (@mock hourvalue(hour=Hour(4))) == 8 # TODO

# Test @mock calls with keyword arguments
@test (@mock hourvalue(hour=Hour(4))) == 8 #:kw
@test (@mock hourvalue(; hour=Hour(4))) == 8 #:parameters
end
end

0 comments on commit 49dff5f

Please sign in to comment.