Fl4m3Ph03n1x

Fl4m3Ph03n1x

Test function was called exactly X times

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:

  1. A ton of code repetition
  2. It doesn’t check that :lookup was 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

  1. How do I check if a given message was received X times?
  2. How do I check if a given message was received at least X times?
  3. Are there any libraries that add decent stub support ?

Marked As Solved

LostKobrakai

LostKobrakai

x = 10
for _ <- 1..x, do: assert_received :lookup
refute_received :lookup

Also Liked

peerreynders

peerreynders

Just an observation.

I personally never got into mocking. I only crossed paths with it about 5 years ago when using Mocha/Sinon/Chai. Given the nature of JavaScript (or Ruby for that matter) I can see how one could go down that road.

My exposure to microtesting goes back to the early days JUnit.

Mocking only became a thing some time later and when I looked into it in Java-land, a lot of it relied on reflection - my reaction:

  • Eeewh! That’s cheating.

Well, not entirely. It’s justified if you are mocking 3rd party dependencies but even then there was always the choice to just decouple that behind a façade.

That’s cheating.

That reaction was driven by the notion that mocking your own code removes the incentive to constantly assess and re-evaluate your boundaries. With classical testing there is the constant pressure to adjust your boundaries to be able to test what you want to test.

To me personally the primary benefit of Test Driven Development (in the classical sense) was that constant challenging of those boundaries (and the portals passing through them) - not the test first religion.

Of course even that can go off the rails as evidenced by the whole test induced design damage discussion.

One thing that isn’t clear from this discussion is:

  • why is it so important that the lookup is called 10 times that it needs to be tested at this level?
  • what is responsible for performing that lookup in the real system?

For example, if the lookup goes to another process anyway, wouldn’t it make more sense to test it with a fake process which keeps track of the invocation details that are then sent to the testing process?


Somewhat related in the JavaScript space: Please don’t mock me

peerreynders

peerreynders

It’s already covered.

  • for _ <- 1…x, do: assert_received :lookup this will use assert_receive x times. If x receives do not happen, a timeout will fail the test.
  • refute_received :lookup this ensures that that there are no further receives beyond x for the specified timeout.

So combined the test ensures that exactly x messages were received within the specified timeouts.

amatalai

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)

Where Next?

Popular in Questions Top

vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 55125 245
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New

We're in Beta

About us Mission Statement