sylv3r

sylv3r

Best way to write test for a GenServer interacting with the filesystem

Hello guys,

I’m new to elixir and I need some help.

I’m writing an API backend, without phoenix, and I don’t know how to write a test for a GenServer which is watching source code for hot reloading on dev environment.
The server is working, but I’d like to ensure consistent unit tests for future improvements and … well… this should have tests anyway.

The goal is to be in a project fs-like environment, starts the GenServer, touch a file and see if the recompilation is triggered as expected.

Thanks for your lights !

Most Liked

peerreynders

peerreynders

Rather than hardcoding the “Mix.Tasks.Compile.Elixir” function, you could just inject it in the init function on the GenServer. Then for testing you can just inject a function that sends the parameters back to the test for comparison.

defmodule Demo do
  def init([notify]) do
    {:ok, notify}
  end

  def terminate(reason, notify),
    do: notify.(:terminate, reason, self())

  def handle_call(request, {pid, _}, notify) do
    notify.(:call, request, pid)
    {:reply, :ok, notify}
  end

  def handle_cast(request, notify) do
    notify.(:cast, request, self())
    {:noreply, notify}
  end

  def handle_info(msg, notify) do
    notify.(:info, msg, self())
    {:noreply, notify}
  end

  def default_fun(t,r,p),
    do: IO.puts "#{t} #{inspect r} #{inspect p}"

end

run = fn demo, wait ->
  Process.sleep wait
  GenServer.call demo, {:hello,"there"}
  Process.sleep wait
  GenServer.cast demo, "For You Information"
  Process.sleep wait
  Kernel.send demo, 42
  Process.sleep wait
  GenServer.stop demo
  Process.sleep wait
end

fetch = fn wait ->
  receive do
    msg ->
      IO.inspect msg
  after
    wait ->
      :ok
  end
end

fun = &Demo.default_fun/3
{:ok, demo} = GenServer.start_link Demo, [fun]
run.(demo, 200)

dest = self()
test_fun = fn (t, r, p) -> Kernel.send dest, {t,r,p} end
{:ok, test} = GenServer.start_link Demo, [test_fun]
run.(test, 10)
fetch.(10)
fetch.(10)
fetch.(10)
fetch.(10)
{:message_queue_len, count} = Process.info self(), :message_queue_len
IO.puts "Message queue empty: #{count == 0}"
$ elixir demo.exs
call {:hello, "there"} #PID<0.80.0>
cast "For You Information" #PID<0.86.0>
info 42 #PID<0.86.0>
terminate :normal #PID<0.86.0>
{:call, {:hello, "there"}, #PID<0.80.0>}
{:cast, "For You Information", #PID<0.88.0>}
{:info, 42, #PID<0.88.0>}
{:terminate, :normal, #PID<0.88.0>}
Message queue empty: true
$

An excerpt how that might be used in ExUnit:

defmodule PhoneSupTest do
  use ExUnit.Case

  # ... setup and stuff ...

  # function that returns the function to be injected
  def notify_callback do
    pid = self()
    fn (reason, other, ms) ->
      Kernel.send pid, {reason, other, ms} # send tuple back to test process
      :ok
    end
  end


  test "PhoneSup - demo" do
    notify = notify_callback() # 1. Create function to inject
    ms1 = 1
    ms2 = 2

    {:ok, p1} = PhoneSup.attach_phone ms1, notify # 2. inject function
    {:ok, p2} = PhoneSup.attach_phone ms2, notify # 2. inject function

    assert (PhoneFsm.action {:outbound, ms1}, p2) == :ok # 3. test something
    assert_receive {:outbound, ^ms1, ^ms2}               # 4. verify contents
    assert_receive {:inbound, ^p2, ^ms1}                 #    of generated
                                                         #    messages

    # ... more assertions, etc ...

  end
end

Where Next?

Popular in Questions Top

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
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
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
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
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
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
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
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
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
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
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

We're in Beta

About us Mission Statement