Skip to content

Commit

Permalink
FAQ entry on calling un-patched function inside patch (#136)
Browse files Browse the repository at this point in the history
* FAQ entry on calling un-patched function inside patch

I've added an FAQ entry on how to call the "un-patched" version of a function inside a patch (if you e.g. want to modify the arguments before calling a function).

@omus mentioned that using `@mock` inside a patch can be useful as well but I couldn't immediately come up with an example off the top of my head, so I just left a short note about that being possible.

* Update docs/src/faq.md

Co-authored-by: Curtis Vogt <[email protected]>

---------

Co-authored-by: Curtis Vogt <[email protected]>
  • Loading branch information
kleinschmidt and omus authored Oct 23, 2024
1 parent 49be98e commit 48aaacf
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions docs/src/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,35 @@ displayed if `Mocking.activate` has been called.
We recommend putting the call to [`Mocking.activate`](@ref activate) in your package's
`test/runtests.jl` file after all of your import statements. The only true requirement is
that you call `Mocking.activate()` before the first [`apply`](@ref) call.

## What if I want to call the un-patched function inside a patch?

Simply call the function without using `@mock` within the patch. For example we can count the number of calls a recursive function does like this:

```julia
function fibonacci(n)
if n <= 1
return n
else
return @mock(fibonacci(n - 1)) + @mock(fibonacci(n - 2))
end
end

calls = Ref(0)
p = @patch function fibonacci(n)
calls[] += 1
return fibonacci(n) # Calls original function
end

apply(p) do
@test @mock(fibonacci(1)) == 1
@test calls[] == 1

calls[] = 0
@test @mock(fibonacci(4)) == 3
@test calls[] == 9
end
```

Note that you can also use `@mock` _inside_ a patch, which can be useful when using
multiple dispatch with patches.

0 comments on commit 48aaacf

Please sign in to comment.