Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Testing Asynchronous OTP

Testing Asynchronous OTP

Andrea Leopardi

September 09, 2021
Tweet

More Decks by Andrea Leopardi

Other Decks in Programming

Transcript

  1. defmodule RollingAverage do use GenServer def start_link(limit), do: # ...

    def add(pid, n), do: # ... 
 def average(pid), do: # ... end
  2. test "add/2 and average/1" do {:ok, pid} = RollingAverage.start_link(2) RollingAverage.add(pid,

    3) RollingAverage.add(pid, 4) assert RollingAverage.average(pid) == 3.5 RollingAverage.add(pid, 5) assert RollingAverage.average(pid) == 4.5 end
  3. defmodule RollingList do def new(limit), do: {limit, []} def add({limit,

    list}, n), do: # ... def average({_limit, list}), do: # ... end
  4. test "add/2" do {:ok, pid} = RollingAverage.start_link(2) RollingAverage.add(pid, 3) state

    = :sys.get_state(pid) assert state == {_limit = 2, [3]} end
  5. test "background_work/0" do parent = self() ref = make_ref() Mox.expect(TwitterMock,

    :post, fn -> send(parent, ref) :ok end) background_work() assert_receive ^ref end
  6. defmodule WeatherChecker do use GenServer def init(_) do :timer.send_interval(5000, self(),

    :tick) end def handle_info(:tick, _) do check_weather() end end
  7. defmodule WeatherChecker do use GenServer def init(_) do :timer.send_interval(5000, self(),

    :tick) end def tick(pid), do: send(pid, :tick) def handle_info(:tick, _) do check_weather() end end
  8. @mix_env Mix.env() def start(_type, _args) do Supervisor.start_link(children(@mix_env), ...) end defp

    children(:test), do: [...] defp children(_env), do: [WeatherChecker | ...]
  9. test "cleanup after crashes" do Process.flag(:trap_exit, true) {:ok, pid} =

    start_supervised(MyServer) Process.exit(pid, :kill) assert cleanup_successful?() end