defmodule EslHnWeb.Api.SocketTest do use ExUnit.Case, async: false import EslHn.Test.Data alias EslHn.Cache setup do assert {:ok, {host, port}} = EslHnWeb.Endpoint.server_info(:http) on_exit(fn -> Cache.flush(EslHn) end) {:ok, host: host, port: port} end defmodule Client do use Fresh def handle_in({:text, data}, {parent, counter}) do send(parent, {:ws, counter, JSON.decode!(data)}) {:ok, {parent, counter + 1}} end end test "receive initial list of stories", ctx do stories = Enum.take(story(), 50) ids = Enum.map(stories, & &1.id) Cache.write(EslHn, :index, ids) Cache.write_all(EslHn, Enum.map(stories, &{&1.id, &1})) start_supervised!( {Client, uri: "ws://localhost:#{ctx.port}/websocket", state: {self(), 0}} ) assert_receive {:ws, 0, init} recv_ids = Enum.map(init, & &1["id"]) assert Enum.all?(ids, &(&1 in recv_ids)) assert length(recv_ids) == length(ids) end test "broadcasted events are sent over socket", ctx do start_supervised!( {Client, uri: "ws://localhost:#{ctx.port}/websocket", state: {self(), 0}} ) assert_receive {:ws, 0, []} for stories <- Enum.take(StreamData.list_of(story(), min_length: 1), 10) do ids = Enum.map(stories, & &1.id) EslHn.broadcast_new(stories) assert_receive {:ws, _, msg} recv_ids = Enum.map(msg, & &1["id"]) assert Enum.all?(ids, &(&1 in recv_ids)) assert length(recv_ids) == length(ids) end end end