d6595f9714e72a8bb069b2877817d9daaf70d68e
[akkoma] / test / support / conn_case.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ConnCase do
6 @moduledoc """
7 This module defines the test case to be used by
8 tests that require setting up a connection.
9
10 Such tests rely on `Phoenix.ConnTest` and also
11 import other functionality to make it easier
12 to build common datastructures and query the data layer.
13
14 Finally, if the test case interacts with the database,
15 it cannot be async. For this reason, every test runs
16 inside a transaction which is reset at the beginning
17 of the test unless the test case is marked as async.
18 """
19
20 use ExUnit.CaseTemplate
21
22 using do
23 quote do
24 # Import conveniences for testing with connections
25 use Phoenix.ConnTest
26 use Pleroma.Tests.Helpers
27 import Pleroma.Web.Router.Helpers
28
29 # The default endpoint for testing
30 @endpoint Pleroma.Web.Endpoint
31
32 # Sets up OAuth access with specified scopes
33 defp oauth_access(scopes, opts \\ []) do
34 user =
35 Keyword.get_lazy(opts, :user, fn ->
36 Pleroma.Factory.insert(:user)
37 end)
38
39 token =
40 Keyword.get_lazy(opts, :oauth_token, fn ->
41 Pleroma.Factory.insert(:oauth_token, user: user, scopes: scopes)
42 end)
43
44 conn =
45 build_conn()
46 |> assign(:user, user)
47 |> assign(:token, token)
48
49 %{user: user, token: token, conn: conn}
50 end
51
52 defp ensure_federating_or_authenticated(conn, url, user) do
53 Pleroma.Config.put([:instance, :federating], false)
54
55 conn
56 |> get(url)
57 |> response(403)
58
59 conn
60 |> assign(:user, user)
61 |> get(url)
62 |> response(200)
63
64 Pleroma.Config.put([:instance, :federating], true)
65
66 conn
67 |> get(url)
68 |> response(200)
69 end
70 end
71 end
72
73 setup tags do
74 Cachex.clear(:user_cache)
75 Cachex.clear(:object_cache)
76 :ok = Ecto.Adapters.SQL.Sandbox.checkout(Pleroma.Repo)
77
78 unless tags[:async] do
79 Ecto.Adapters.SQL.Sandbox.mode(Pleroma.Repo, {:shared, self()})
80 end
81
82 if tags[:needs_streamer] do
83 start_supervised(Pleroma.Web.Streamer.supervisor())
84 end
85
86 {:ok, conn: Phoenix.ConnTest.build_conn()}
87 end
88 end