1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.ConnCase do
7 This module defines the test case to be used by
8 tests that require setting up a connection.
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.
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.
20 use ExUnit.CaseTemplate
24 # Import conveniences for testing with connections
26 use Pleroma.Tests.Helpers
27 import Pleroma.Web.Router.Helpers
31 # The default endpoint for testing
32 @endpoint Pleroma.Web.Endpoint
34 # Sets up OAuth access with specified scopes
35 defp oauth_access(scopes, opts \\ []) do
37 Keyword.get_lazy(opts, :user, fn ->
38 Pleroma.Factory.insert(:user)
42 Keyword.get_lazy(opts, :oauth_token, fn ->
43 Pleroma.Factory.insert(:oauth_token, user: user, scopes: scopes)
48 |> assign(:user, user)
49 |> assign(:token, token)
51 %{user: user, token: token, conn: conn}
54 defp request_content_type(%{conn: conn}) do
55 conn = put_req_header(conn, "content-type", "multipart/form-data")
59 defp json_response_and_validate_schema(
62 open_api_spex: %{operation_id: op_id, operation_lookup: lookup, spec: spec}
69 |> Plug.Conn.get_resp_header("content-type")
74 status = Plug.Conn.Status.code(status)
76 unless lookup[op_id].responses[status] do
77 err = "Response schema not found for #{conn.status} #{conn.method} #{conn.request_path}"
81 schema = lookup[op_id].responses[status].content[content_type].schema
82 json = json_response(conn, status)
84 case OpenApiSpex.cast_value(json, schema, spec) do
90 Enum.map(errors, fn error ->
91 message = OpenApiSpex.Cast.Error.message(error)
92 path = OpenApiSpex.Cast.Error.path_to_string(error)
93 "#{message} at #{path}"
97 "Response does not conform to schema of #{op_id} operation: #{
98 Enum.join(errors, "\n")
104 defp json_response_and_validate_schema(conn, _status) do
105 flunk("Response schema not found for #{conn.method} #{conn.request_path} #{conn.status}")
108 defp ensure_federating_or_authenticated(conn, url, user) do
109 initial_setting = Config.get([:instance, :federating])
110 on_exit(fn -> Config.put([:instance, :federating], initial_setting) end)
112 Config.put([:instance, :federating], false)
119 |> assign(:user, user)
123 Config.put([:instance, :federating], true)
133 Cachex.clear(:user_cache)
134 Cachex.clear(:object_cache)
135 :ok = Ecto.Adapters.SQL.Sandbox.checkout(Pleroma.Repo)
137 unless tags[:async] do
138 Ecto.Adapters.SQL.Sandbox.mode(Pleroma.Repo, {:shared, self()})
141 if tags[:needs_streamer] do
142 start_supervised(Pleroma.Web.Streamer.supervisor())
145 {:ok, conn: Phoenix.ConnTest.build_conn()}