Merge branch 'test-mix-tasks' into 'develop'
[akkoma] / test / support / data_case.ex
1 defmodule Pleroma.DataCase do
2 @moduledoc """
3 This module defines the setup for tests requiring
4 access to the application's data layer.
5
6 You may define functions here to be used as helpers in
7 your tests.
8
9 Finally, if the test case interacts with the database,
10 it cannot be async. For this reason, every test runs
11 inside a transaction which is reset at the beginning
12 of the test unless the test case is marked as async.
13 """
14
15 use ExUnit.CaseTemplate
16
17 using do
18 quote do
19 alias Pleroma.Repo
20
21 import Ecto
22 import Ecto.Changeset
23 import Ecto.Query
24 import Pleroma.DataCase
25 use Pleroma.Tests.Helpers
26 end
27 end
28
29 setup tags do
30 Cachex.clear(:user_cache)
31 :ok = Ecto.Adapters.SQL.Sandbox.checkout(Pleroma.Repo)
32
33 unless tags[:async] do
34 Ecto.Adapters.SQL.Sandbox.mode(Pleroma.Repo, {:shared, self()})
35 end
36
37 :ok
38 end
39
40 def ensure_local_uploader(_context) do
41 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
42 filters = Pleroma.Config.get([Pleroma.Upload, :filters])
43
44 unless uploader == Pleroma.Uploaders.Local || filters != [] do
45 Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local)
46 Pleroma.Config.put([Pleroma.Upload, :filters], [])
47
48 on_exit(fn ->
49 Pleroma.Config.put([Pleroma.Upload, :uploader], uploader)
50 Pleroma.Config.put([Pleroma.Upload, :filters], filters)
51 end)
52 end
53
54 :ok
55 end
56
57 @doc """
58 A helper that transform changeset errors to a map of messages.
59
60 changeset = Accounts.create_user(%{password: "short"})
61 assert "password is too short" in errors_on(changeset).password
62 assert %{password: ["password is too short"]} = errors_on(changeset)
63
64 """
65 def errors_on(changeset) do
66 Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
67 Enum.reduce(opts, message, fn {key, value}, acc ->
68 String.replace(acc, "%{#{key}}", to_string(value))
69 end)
70 end)
71 end
72 end