Merge branch 'fix/ci-cache-improved' into 'develop'
[akkoma] / test / integration / mastodon_websocket_test.exs
1 defmodule Pleroma.Integration.MastodonWebsocketTest do
2 use Pleroma.DataCase
3
4 import Pleroma.Factory
5
6 alias Pleroma.Web.CommonAPI
7 alias Pleroma.Web.OAuth
8 alias Pleroma.Integration.WebsocketClient
9 alias Pleroma.Web.Streamer
10
11 @path Pleroma.Web.Endpoint.url()
12 |> URI.parse()
13 |> Map.put(:scheme, "ws")
14 |> Map.put(:path, "/api/v1/streaming")
15 |> URI.to_string()
16
17 setup do
18 GenServer.start(Streamer, %{}, name: Streamer)
19
20 on_exit(fn ->
21 if pid = Process.whereis(Streamer) do
22 Process.exit(pid, :kill)
23 end
24 end)
25 end
26
27 def start_socket(qs \\ nil, headers \\ []) do
28 path =
29 case qs do
30 nil -> @path
31 qs -> @path <> qs
32 end
33
34 WebsocketClient.start_link(self(), path, headers)
35 end
36
37 test "refuses invalid requests" do
38 assert {:error, {400, _}} = start_socket()
39 assert {:error, {404, _}} = start_socket("?stream=ncjdk")
40 end
41
42 test "requires authentication and a valid token for protected streams" do
43 assert {:error, {403, _}} = start_socket("?stream=user&access_token=aaaaaaaaaaaa")
44 assert {:error, {403, _}} = start_socket("?stream=user")
45 end
46
47 test "allows public streams without authentication" do
48 assert {:ok, _} = start_socket("?stream=public")
49 assert {:ok, _} = start_socket("?stream=public:local")
50 assert {:ok, _} = start_socket("?stream=hashtag&tag=lain")
51 end
52
53 test "receives well formatted events" do
54 user = insert(:user)
55 {:ok, _} = start_socket("?stream=public")
56 {:ok, activity} = CommonAPI.post(user, %{"status" => "nice echo chamber"})
57
58 assert_receive {:text, raw_json}, 1_000
59 assert {:ok, json} = Jason.decode(raw_json)
60
61 assert "update" == json["event"]
62 assert json["payload"]
63 assert {:ok, json} = Jason.decode(json["payload"])
64
65 # Note: we remove the "statuses_count" from this result as it changes in the meantime
66
67 view_json =
68 Pleroma.Web.MastodonAPI.StatusView.render("status.json", activity: activity, for: nil)
69 |> Jason.encode!()
70 |> Jason.decode!()
71 |> put_in(["account", "statuses_count"], 0)
72
73 assert json == view_json
74 end
75
76 describe "with a valid user token" do
77 setup do
78 {:ok, app} =
79 Pleroma.Repo.insert(
80 OAuth.App.register_changeset(%OAuth.App{}, %{
81 client_name: "client",
82 scopes: "scope",
83 redirect_uris: "url"
84 })
85 )
86
87 user = insert(:user)
88
89 {:ok, auth} = OAuth.Authorization.create_authorization(app, user)
90
91 {:ok, token} = OAuth.Token.exchange_token(app, auth)
92
93 %{user: user, token: token}
94 end
95
96 test "accepts valid tokens", state do
97 assert {:ok, _} = start_socket("?stream=user&access_token=#{state.token.token}")
98 end
99 end
100 end