live_beats/test/live_beats/presence/presence_client_test.exs

74 lines
2 KiB
Elixir
Raw Normal View History

2021-12-13 18:33:13 +00:00
defmodule Phoenix.Presence.ClientTest do
2021-12-14 22:14:37 +00:00
use ExUnit.Case
2021-12-13 18:33:13 +00:00
alias Phoenix.Presence.Client.PresenceMock
2021-12-14 22:14:37 +00:00
alias Phoenix.Presence.Client
2021-12-13 18:33:13 +00:00
2021-12-14 22:14:37 +00:00
@pubsub LiveBeats.PubSub
@client Phoenix.Presence.Client.Mock
@presence LiveBeatsWeb.Presence
@presence_client_opts [client: @client, pubsub: @pubsub, presence: @presence]
setup tags do
pid = Ecto.Adapters.SQL.Sandbox.start_owner!(LiveBeats.Repo, shared: not tags[:async])
on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
:ok
end
test "When a new process is tracked, a topic key is added to the topics state" do
2021-12-13 18:33:13 +00:00
presence_key = 1
2021-12-14 22:14:37 +00:00
topic = topic(100)
{:ok, presence_client} = Client.start_link(@presence_client_opts)
{:ok, presence_process} = PresenceMock.start_link(id: presence_key)
Phoenix.PubSub.subscribe(@pubsub, topic)
Process.monitor(presence_process)
2021-12-13 18:33:13 +00:00
2021-12-14 22:14:37 +00:00
PresenceMock.track(presence_client, presence_process, topic, presence_key)
2021-12-13 18:33:13 +00:00
2021-12-14 22:14:37 +00:00
assert Process.alive?(presence_process)
2021-12-13 18:33:13 +00:00
2021-12-14 22:14:37 +00:00
assert_receive %{event: "presence_diff"}
2021-12-13 18:33:13 +00:00
2021-12-14 22:14:37 +00:00
client_state = :sys.get_state(presence_client)
assert %{topics: %{^topic => %{"1" => [%{phx_ref: _ref}]}}} = client_state
2021-12-13 18:33:13 +00:00
end
test "topic is removed from the topics state when there is no more presences" do
presence_key = 1
2021-12-14 22:14:37 +00:00
topic = topic(100)
{:ok, presence_client} = Client.start_link(@presence_client_opts)
{:ok, presence_process} = PresenceMock.start_link(id: presence_key)
Phoenix.PubSub.subscribe(@pubsub, topic)
Process.monitor(presence_process)
PresenceMock.track(presence_client, presence_process, topic, presence_key)
assert Process.alive?(presence_process)
assert_receive %{event: "presence_diff"}
client_state = :sys.get_state(presence_client)
2021-12-13 18:33:13 +00:00
2021-12-14 22:14:37 +00:00
assert %{topics: %{^topic => %{"1" => [%{phx_ref: _ref}]}}} = client_state
2021-12-13 18:33:13 +00:00
2021-12-14 22:14:37 +00:00
send(presence_process, :quit)
2021-12-13 18:33:13 +00:00
2021-12-14 22:14:37 +00:00
assert_receive {:DOWN, _ref, :process, ^presence_process, _reason}
2021-12-13 18:33:13 +00:00
2021-12-14 22:14:37 +00:00
client_state = :sys.get_state(presence_client)
2021-12-13 18:33:13 +00:00
2021-12-14 22:14:37 +00:00
assert %{topics: %{}} = client_state
2021-12-13 18:33:13 +00:00
end
defp topic(id) do
"mock_topic:#{id}"
end
end