I could not find a package that would allow to temporary override function implementation, so I’ve made one: Mock.jl.
I’ve checked other packages before, here what I could find:
Closest to the concept would be Pretend.jl but it requires annotation next to function declaration.
Similar behavior have Mocking but it requires annotation at call site, which is something completely different yet quite interesting.
There is also SimpleMock.jl but it is “kinda broken” according to the readme and Cassette.jl on top of which it is built is also having troubles supporting 1.12
The API is quite simplistic at the moment:
with_mocked(old=>new) do
# new is substituting old
end
Take a note that there is no need to modify old to work with Mock.jl - if function can be overridden it can be mocked (only built in functions can’t be mocked).
There is also a macro @original which allows you to call original method (the old one which was before mock was applied).
At this moment macro is not 100% working - recursive calls do not work at all. In experimental branch with even more abuse of the Julia runtime I’ve made it to call old code, but then for recursive function I have a silly sequence of new -> old [recursion happens here] -> new -> old [may be recursive again] etc which is not what I would call reasonable, so more work is ahead.
Internally this package is built on top of Base.delete_method functionality which allows to temporary override implementation, because if method is deleted with this function then the old implementation is available again.
For the package name there are doubts though:
Mock.jl violates community guideline of “at least 5 characters”.
What do you think about the name? Shall I leave it as it is, or you have a better suggestion?
Nice! I recall a comment during Juliacon that improvements in the world model (which functions are defined when) might soon improve mocking capabilities. The test ecosystem could use more ways to mock.
Naming is fun. How about Tempora.jl for temporary mocks. Or BaseMock.jl. Or ShadowCall.jl? I don’t know. Have fun with it.
Cheers,
Drew