3f40c3670fb8c17ce86872c7aac627318c85c823
[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 end
26 end
27
28 setup tags do
29 :ok = Ecto.Adapters.SQL.Sandbox.checkout(Pleroma.Repo)
30
31 unless tags[:async] do
32 Ecto.Adapters.SQL.Sandbox.mode(Pleroma.Repo, {:shared, self()})
33 end
34
35 :ok
36 end
37
38 @doc """
39 A helper that transform changeset errors to a map of messages.
40
41 changeset = Accounts.create_user(%{password: "short"})
42 assert "password is too short" in errors_on(changeset).password
43 assert %{password: ["password is too short"]} = errors_on(changeset)
44
45 """
46 def errors_on(changeset) do
47 Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
48 Enum.reduce(opts, message, fn {key, value}, acc ->
49 String.replace(acc, "%{#{key}}", to_string(value))
50 end)
51 end)
52 end
53 end