Asd

Asd

Repatch - Everything you need for mocking and patching

Hi,

I am happy to release the Repatch library for mocking and patching implementation in tests and anywhere else. It brings new possibilities which make it possible to make literally any test async.

You can install it and start trying it out in iex right now, while reading the post!

For example,

iex(1)> Mix.install [repatch: "~> 1.1"]
Resolving Hex dependencies...
Resolution completed in 0.01s
New:
  repatch 1.1.0
* Getting repatch (Hex package)
==> repatch
Compiling 3 files (.ex)
Generated repatch app
:ok
iex(2)> Repatch.setup
:ok
iex(3)> Repatch.patch Range, :new, fn l, r -> Enum.to_list(Repatch.super(Range, :new, [l, r])) end
:ok
iex(4)> Range.new 1, 10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Continue in the docs: Repatch — Repatch v1.6.1

Features

  1. Patch any function or macro (except NIF and BIF). Elixir or Erlang, private or public, it can be patched!

  2. Designed to work with async: true. Has 3 isolation levels for testing multi-processes scenarios.

  3. Requires no boilerplate or explicit DI. Though, you are completely free to write in this style with Repatch!

  4. Every patch is consistent and applies to direct or indirect calls and any process you choose.

  5. Powerful call history tracking.

  6. super and real helpers for calling original functions.

  7. Works with other testing frameworks and even in environments like iex or remote shell.

  8. Battle-tested in real world production project. Using Repatch instead of Patch reduced time of the whole test suite by 10-20% (depending on amount of cores on the test runner machine) by reducing the time of sync tests by 2 times.

Quick comparison with other tools

  1. Mox is a great library but it works only with behaviours which is a good approach from the architectural point of view, but fails to work in situations when you’re using 3rd-party library without behaviours, what makes you wrap every function you want to mock into the behaviour. However, Repatch inherits allowances and global mode approaches from Mox, but implements them in more efficient genserver-less way.
  2. Patch is a great library too and it has been a good example and Repatch borrows some code from it. Patch doesn’t work with async: true what has been a problem because test suite was getting slower every time it was using Patch. However, Repatch shares same ideas as Patch does.
  3. Mimic is a library I’ve used and loved too and it shares most of it’s features with Repatch, however Repatch is more efficient in local-only (aka private in Mimic terms) patching and has a shared mode. Also, Repatch performs less amount of module recompilations (every module is recompiled at most once) in runtime.

New horizons

Features I describe here are unique to Repatch and they bring new possibilities to write faster tests. Here is a short list of ideas:

  • Patching Application and :application modules for async-friendly application env. I did this in my production project and I was able to make every sync test in the project I have to become async. I did not finish the work and benchmarking this approach yet, but I expect around 30s speedup in the whole suite, which is a lot.
  • Patching DateTime module for time travelling in timestamps. Yes, it’s possible and works for some tests, but I haven’t figured a way to make it work for functions like :erlang.monotonic_time(), so be careful when using these.
  • Patching System for async-friendly system env. I don’t usually write code which reads from system env in non-config files, but some people do and now you can test system env in async tests
  • Patching Process.sleep and Process.send_after for timeouts manipulation. This is also a risky thing to do, but, as the old Russian saying goes “Those who do not risk, do not drink champagne”!

Afterwords

Don’t be afraid to experiment with Repatch and don’t be afraid to experiment in general. This library was born from understanding that long-lived tools and approaches are limited and there is always a way to move forward.

Most Liked

Asd

Asd

Repatch 1.5.0

This is a big update which adds helpers on top of existing patch logic to support

  1. Mox-style define/expect explicit DI mocking for behaviors.
  2. ProtoMock-style define/expect explicit DI mocking for protocols.

That means that you no longer need to install a bunch of separate libraries, some of which require explicit dependency injection boilerplate, others don’t work with async tests, and so on. You no longer need to keep in mind the different limitations of these libraries with Repatch.

I’ve tried this update on the project of mine, I replaced all TestServer/Bypass, Mox, Patch and ProtoMock code with Repatch, made all of the tests async: true and tests now run 2 times faster, while testing code looks much more cleaner as a bonus.

Asd

Asd

Sure, here it is: How it works — Repatch v1.1.0
Codebase is really small, around 1.5k lines, so you can read it in half an hour

mudasobwa

mudasobwa

Creator of Cure

The library looks great. For those who are more of self-controlled code, there is also Bex library to generate behaviours for whatever to be mox’ed.

spicychickensauce

spicychickensauce

Thanks for creating Repatch!
I think this is the best of all the mocking libraries with the least restrictions, and it should deserve a lot more recognition from the community.

Patching DateTime module for time travelling in timestamps

Do you have a helper module / small library that you use for this which you can share?
I needed time travel testing in literally every project at some point and I hate to reinvent it every time.

With Repatch I’m currently just doing this, but it’s probably too simple for most situations:

    {:ok, time} = Agent.start_link(fn -> ~N[1990-01-01 00:00:00] end)
    Repatch.patch(NaiveDateTime, :utc_now, fn ->
      Agent.get(time, fn t -> t end)
    end)
    # ...
    Agent.update(time, fn _ -> ~N[2010-01-01 00:00:00] end)
Asd

Asd

Hi, uhh, I mentioned it in “New horizons” because it was worth exploring. And I did some exploration and found out that

  1. DateTime.utc_now uses System.os_time which uses :os.system_time. And :os.system_time can’t be patched
  2. We can patch DateTime.utc_now but it will only replace this call, since, for example, erlang dependencies will use :os.system_time which will always return unpatched, real values
  3. And there are also other functions like :erlang.monotonic_time which return different kinds of time

So my conclusion is that it’s not possible to use Repatch for 100% compatible time traveling. And it is not possible to use anything else, since erts implementation calls posix gettime directly, without any way to change it on erlang side only for some specific process.

My suggestion for you is to try to approach the problem another way: instead of travelling in time in order to make sure that some timers are triggered, you should try to make timeouts for these timers configurable and then set them up in tests accordingly.

Where Next?

Popular in Announcing Top

ityonemo
Currently just starting out on a new mini-project - getting zig NIFs to run in elixir. https://github.com/ityonemo/zigler The idea here...
New
BartOtten
Phoenix Live Favicon Favicon manipulation for Phoenix Live A lib enabling dynamic favicons in Phoenix Live View applications. To sho...
New
fuelen
Ecto.DevLogger is an alternative logger of SQL queries in development It inlines bindings into the query, so it is easy to copy-paste lo...
New
kasvith
Hello Everyone, I was working with some HTML-to-Markdown libraries and ran into a few issues when converting a complex markup file to Ma...
New
lud
Hello! I’ve been working on the Oaskit library for a while now, and just released a first version. Since I’ve built JSV I wanted to be ...
New
wingyplus
I just did a dirty hack after seeing Zoi on x.com a few hours ago. Quick Introduction The zoi_defstruct is a library to help you generat...
New
type1fool
WebAuthnLiveComponent WebAuthnComponents See this post about renaming the package. Passwordless authentication for Phoenix LiveView app...
New
mattmower
I’m pleased to announce that we’ve released DemoGen v0.1.7, a library for creating repeatable demo scenarios in your Ecto-based SaaS appl...
New
mudspot
Hi folks, I’d like to announce the release of Prometheus Agents, a set of subagents for Claude Code that cater to the Elixir Phoenix pro...
New
sodapopcan
I’ve heard that if you’re not embarrassed by v1 of your product Vim plugin then you’ve released too late. I’ve been sitting on this the ...
New

Other popular topics Top

_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New

We're in Beta

About us Mission Statement