Fl4m3Ph03n1x
Background
I have some code that invokes a given function a certain number of times. I pass this function in the parameters so it is easy to stub.
However I need to know that under some conditions the function was called exactly X times. ExUnit.Case has an extremely limited support for this however, so I went ahead with the “send yourself a given message trick”
Code
@tag :wip
test "calls given function X times" do
my_pid = self()
deps = [
lookup_fn: fn _key ->
send(my_pid, :lookup)
{:ok, 1}
end
]
MyApp.do_work(deps)
# how to test I got the :lookup message exactly twice?
end
Research
The first easy solution is using receive multiple times:
receive do
msg -> assert msg == :lookup
end
receive do
msg -> assert msg == :lookup
end
receive do
msg -> assert msg == :lookup
end
# etc...
For example, if I wanted to check :lookup was called 10 times, I would have 10 receives.
This solution is very poor for 2 reasons:
- A ton of code repetition
- It doesn’t check that
:lookupwas called exactly X times, it checks it was received at least X times.
I searched for some libraries but couldn’t find anything. The closes thing I found was the SO question using macros:
Which I tried to adapt into an assert_receive_at_least (but failed miserably):
defmacro assert_receive_at_least(pattern, times, timeout \\ 500) do
quote do
defp loop(_pattern, current_times, total_times, _timeout) when current_times == total_times do
{:ok, :received}
end
defp loop(pattern, current_times, total_times, timeout) do
receive do
msg -> assert pattern == msg
after timeout -> {:error, :timeout}
end
end
defp run(pattern, times, timeout) do
loop(pattern, 0, times, timeout)
end
run(unquote(pattern), unquote(times), unquote(timeout))
end
end
Questions
- How do I check if a given message was received X times?
- How do I check if a given message was received at least X times?
- Are there any libraries that add decent stub support ?
Trending in Questions
Hey guys,
I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly
Do you guys have any suggestions what is the best prac...
New
Hello!
Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app.
I creat...
New
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
Anyone here using Honeybadger?
My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of
Bandit.HTTPError...
New
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
There are three potential reasons for members of this forum to have a look at https://vutuv.de
You are tired or annoyed of LinkedIn.
Yo...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixir-ls
- #ai
- #elixirconf-us
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
LostKobrakai
shanesveller
I would encourage you to think about the problem differently if possible - are there existing, concrete side effects you can observe directly after the function has been called N times? Perhaps several new DB rows get created, a counter gets incremented, etc.
If you’ve read Mocks and Explicit Contracts and still want to continue with this path knowing those trade-offs and accepting them, Mox is a great choice. May require some refactoring to establish your contracts as a behaviour.
Fl4m3Ph03n1x
Could you elaborate a little bit more on your solution?
Also, I assume that is the solution to question 1. Would you be kind enough to suggest something about the second question?
This is precisely the things I don’t want to test. I want to test that the messages of my system were sent to its collaborators. I don’t wanna know what they did. This is a hallmark principle of good testing and good design I won’t abandon so easily.
I have read that article. In fact that article is the reason why I am injecting the dependencies via functional injection. First, because not every code benefits from the added noise of a contract, and second because José Valim himself suggests in the article that functional dependency injection is better.
But even if I were to use Mox, it would still fall (very) short of the basic features I need to test, such as meaningful stub and spies.
shanesveller
There is a fairly subtle important distinction between “was this function called N times”, which is a blatant implementation detail, and “was this message delivered N times”, which is still an implementation detail, but one that is likely to survive longer within your business domain than a function name. You can test the latter without any external libraries, depending on how your code is structured. Presumably the pid or registered name of your collaborator appears somewhere within your function arguments, and you can point that to another listener in various ways that would allow you to assert on the messages received.
Can you mention some of the shortcomings you found when trying the library? Have you opened any GitHub issues on the project to have them considered? It supports defining stubs and mocks based on anonymous or captured functions, and it would be fairly trivial to pass from that back into a “real” behavioral module to observe that the functions were called but still test the real behavior too.
amatalai
Maybe GitHub - appunite/mockery: Simple mocking library for asynchronous testing in Elixir. · GitHub would be better for your needs. It works well if you don’t need to check function calls between different processes (disclaimer: I am the author of this library, I can be biased)
peerreynders
It’s already covered.
for _ <- 1…x, do: assert_received :lookupthis will useassert_receivextimes. Ifxreceives do not happen, a timeout will fail the test.refute_received :lookupthis ensures that that there are no further receives beyondxfor the specified timeout.So combined the test ensures that exactly
xmessages were received within the specified timeouts.hauleth
If you are using OTP 21+ then you can write it as:
Fl4m3Ph03n1x
The function name is a detail, you are correct. I don’t care which specific function my code runs (if its name is A or B or whatever) but I do care that it runs the functions I inject on it a given number of times. This is the basics of testing (usually you test if a function was called once) and coulnd’t be farther from an implementation detail.
Allow me to showcase what a real test library is
https://sinonjs.org/releases/v7.2.4/
spies, stubs, fakes, mocks, timers, etc.
Admittedly they go out of the way with their own assertions (something which ExUnit could benefit from) but that’s another discussion.
A fair point, but one that I feel would be a waste of my time. I find it that Jose Valim would rather do other things then listening for a cry baby asking for features. Not only that, I need a solution I can use now, not a solution I can use in 4 months when the Elixir team finally has time to update Mox.
Ultimately, even though you are 100% logically correct, I still don’t engage in that course of action because I have a strong believe my efforts would be fruitless.
From the documentation I see a couple of profound limitations:
If I am incorrect, please feel free to en-light me
Checking it, thanks for popping in !
Using a global state ETS table on my tests truly is something I frown upon. My main issues with this approach are:
I will give it to you that your solution does technically work and that it may end up being less complex than the process approach. So it is something to have in mind. Thanks for sharing!
hauleth
No, you do not need to, as you are passing counter, which is unnamed and identified by reference.
Like most mocking libraries, fakes, etc. It just mean that sometimes it is just hidden from you. And if you want, you can always use
Agentinstead of:counters.Not exactly, just use unnamed ETS tables, and you will be good to go.
Fl4m3Ph03n1x
So I don’t have to keep track? Quite interesting.
A fair argument. Truth is as long as I can run my tests with
async: trueI don’t really care.Like the one
:counterscreate?You have overall good arguments and have convinced me.
Do you have any links or documentation to :counters.new ?
I check the official erlang docs but was unable to find anything.