Create Object.hashtags/1 wrapper
[akkoma] / test / support / data_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.DataCase do
6 @moduledoc """
7 This module defines the setup for tests requiring
8 access to the application's data layer.
9
10 You may define functions here to be used as helpers in
11 your tests.
12
13 Finally, if the test case interacts with the database,
14 it cannot be async. For this reason, every test runs
15 inside a transaction which is reset at the beginning
16 of the test unless the test case is marked as async.
17 """
18
19 use ExUnit.CaseTemplate
20
21 using do
22 quote do
23 alias Pleroma.Repo
24
25 import Ecto
26 import Ecto.Changeset
27 import Ecto.Query
28 import Pleroma.DataCase
29 use Pleroma.Tests.Helpers
30
31 # Sets up OAuth access with specified scopes
32 defp oauth_access(scopes, opts \\ []) do
33 user =
34 Keyword.get_lazy(opts, :user, fn ->
35 Pleroma.Factory.insert(:user)
36 end)
37
38 token =
39 Keyword.get_lazy(opts, :oauth_token, fn ->
40 Pleroma.Factory.insert(:oauth_token, user: user, scopes: scopes)
41 end)
42
43 %{user: user, token: token}
44 end
45 end
46 end
47
48 setup tags do
49 Cachex.clear(:user_cache)
50 Cachex.clear(:object_cache)
51 :ok = Ecto.Adapters.SQL.Sandbox.checkout(Pleroma.Repo)
52
53 unless tags[:async] do
54 Ecto.Adapters.SQL.Sandbox.mode(Pleroma.Repo, {:shared, self()})
55 end
56
57 if tags[:needs_streamer] do
58 start_supervised(%{
59 id: Pleroma.Web.Streamer.registry(),
60 start:
61 {Registry, :start_link, [[keys: :duplicate, name: Pleroma.Web.Streamer.registry()]]}
62 })
63 end
64
65 :ok
66 end
67
68 def ensure_local_uploader(context) do
69 test_uploader = Map.get(context, :uploader, Pleroma.Uploaders.Local)
70 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
71 filters = Pleroma.Config.get([Pleroma.Upload, :filters])
72
73 Pleroma.Config.put([Pleroma.Upload, :uploader], test_uploader)
74 Pleroma.Config.put([Pleroma.Upload, :filters], [])
75
76 on_exit(fn ->
77 Pleroma.Config.put([Pleroma.Upload, :uploader], uploader)
78 Pleroma.Config.put([Pleroma.Upload, :filters], filters)
79 end)
80
81 :ok
82 end
83
84 @doc """
85 A helper that transform changeset errors to a map of messages.
86
87 changeset = Accounts.create_user(%{password: "short"})
88 assert "password is too short" in errors_on(changeset).password
89 assert %{password: ["password is too short"]} = errors_on(changeset)
90
91 """
92 def errors_on(changeset) do
93 Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
94 Enum.reduce(opts, message, fn {key, value}, acc ->
95 String.replace(acc, "%{#{key}}", to_string(value))
96 end)
97 end)
98 end
99 end