Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for kwargs in @mock calls. #21

Merged
merged 1 commit into from
Feb 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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