move to 2.5.5
[anni] / test / support / websocket_client.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Integration.WebsocketClient do
6   # https://github.com/phoenixframework/phoenix/blob/master/test/support/websocket_client.exs
7
8   use WebSockex
9
10   @doc """
11   Starts the WebSocket server for given ws URL. Received Socket.Message's
12   are forwarded to the sender pid
13   """
14   def start_link(sender, url, headers \\ []) do
15     WebSockex.start_link(
16       url,
17       __MODULE__,
18       %{sender: sender},
19       extra_headers: headers
20     )
21   end
22
23   @doc """
24   Closes the socket
25   """
26   def close(socket) do
27     send(socket, :close)
28   end
29
30   @doc """
31   Sends a low-level text message to the client.
32   """
33   def send_text(server_pid, msg) do
34     send(server_pid, {:text, msg})
35   end
36
37   @doc false
38   @impl true
39   def handle_frame(frame, state) do
40     send(state.sender, frame)
41     {:ok, state}
42   end
43
44   @impl true
45   def handle_disconnect(conn_status, state) do
46     send(state.sender, {:close, conn_status})
47     {:ok, state}
48   end
49
50   @doc false
51   @impl true
52   def handle_info({:text, msg}, state) do
53     {:reply, {:text, msg}, state}
54   end
55
56   @impl true
57   def handle_info(:close, _state) do
58     {:close, <<>>, "done"}
59   end
60
61   @doc false
62   @impl true
63   def terminate(_reason, _state) do
64     :ok
65   end
66 end