Merge branch 'develop' into refactor/subscription
[akkoma] / test / support / data_case.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2018 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 :ok
43 end
44
45 def ensure_local_uploader(context) do
46 test_uploader = Map.get(context, :uploader, Pleroma.Uploaders.Local)
47 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
48 filters = Pleroma.Config.get([Pleroma.Upload, :filters])
49
50 Pleroma.Config.put([Pleroma.Upload, :uploader], test_uploader)
51 Pleroma.Config.put([Pleroma.Upload, :filters], [])
52
53 on_exit(fn ->
54 Pleroma.Config.put([Pleroma.Upload, :uploader], uploader)
55 Pleroma.Config.put([Pleroma.Upload, :filters], filters)
56 end)
57
58 :ok
59 end
60
61 @doc """
62 A helper that transform changeset errors to a map of messages.
63
64 changeset = Accounts.create_user(%{password: "short"})
65 assert "password is too short" in errors_on(changeset).password
66 assert %{password: ["password is too short"]} = errors_on(changeset)
67
68 """
69 def errors_on(changeset) do
70 Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
71 Enum.reduce(opts, message, fn {key, value}, acc ->
72 String.replace(acc, "%{#{key}}", to_string(value))
73 end)
74 end)
75 end
76 end