Merge branch 'streamer-worker-registry' into 'develop'
[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 end
31 end
32
33 setup tags do
34 Cachex.clear(:user_cache)
35 Cachex.clear(:object_cache)
36 :ok = Ecto.Adapters.SQL.Sandbox.checkout(Pleroma.Repo)
37
38 unless tags[:async] do
39 Ecto.Adapters.SQL.Sandbox.mode(Pleroma.Repo, {:shared, self()})
40 end
41
42 if tags[:needs_streamer] do
43 start_supervised(%{
44 id: Pleroma.Web.Streamer.registry(),
45 start:
46 {Registry, :start_link, [[keys: :duplicate, name: Pleroma.Web.Streamer.registry()]]}
47 })
48 end
49
50 :ok
51 end
52
53 def ensure_local_uploader(context) do
54 test_uploader = Map.get(context, :uploader, Pleroma.Uploaders.Local)
55 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
56 filters = Pleroma.Config.get([Pleroma.Upload, :filters])
57
58 Pleroma.Config.put([Pleroma.Upload, :uploader], test_uploader)
59 Pleroma.Config.put([Pleroma.Upload, :filters], [])
60
61 on_exit(fn ->
62 Pleroma.Config.put([Pleroma.Upload, :uploader], uploader)
63 Pleroma.Config.put([Pleroma.Upload, :filters], filters)
64 end)
65
66 :ok
67 end
68
69 @doc """
70 A helper that transform changeset errors to a map of messages.
71
72 changeset = Accounts.create_user(%{password: "short"})
73 assert "password is too short" in errors_on(changeset).password
74 assert %{password: ["password is too short"]} = errors_on(changeset)
75
76 """
77 def errors_on(changeset) do
78 Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
79 Enum.reduce(opts, message, fn {key, value}, acc ->
80 String.replace(acc, "%{#{key}}", to_string(value))
81 end)
82 end)
83 end
84 end