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

Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;%= ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
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
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
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
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

skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
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
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
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
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31142 143
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
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
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement