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

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
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
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

We're in Beta

About us Mission Statement