summaryrefslogtreecommitdiff
path: root/test/support/websocket_client.ex
blob: 70d331999fd43904d5fae27fcbca90feff1c3aa3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Pleroma: A lightweight social networking server
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Integration.WebsocketClient do
  # https://github.com/phoenixframework/phoenix/blob/master/test/support/websocket_client.exs

  use WebSockex

  @doc """
  Starts the WebSocket server for given ws URL. Received Socket.Message's
  are forwarded to the sender pid
  """
  def start_link(sender, url, headers \\ []) do
    WebSockex.start_link(
      url,
      __MODULE__,
      %{sender: sender},
      extra_headers: headers
    )
  end

  @doc """
  Closes the socket
  """
  def close(socket) do
    send(socket, :close)
  end

  @doc """
  Sends a low-level text message to the client.
  """
  def send_text(server_pid, msg) do
    send(server_pid, {:text, msg})
  end

  @doc false
  @impl true
  def handle_frame(frame, state) do
    send(state.sender, frame)
    {:ok, state}
  end

  @impl true
  def handle_disconnect(conn_status, state) do
    send(state.sender, {:close, conn_status})
    {:ok, state}
  end

  @doc false
  @impl true
  def handle_info({:text, msg}, state) do
    {:reply, {:text, msg}, state}
  end

  @impl true
  def handle_info(:close, _state) do
    {:close, <<>>, "done"}
  end

  @doc false
  @impl true
  def terminate(_reason, _state) do
    :ok
  end
end