Refactor require_migration/1 into a test helper function
[akkoma] / test / support / helpers.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.Tests.Helpers do
6 @moduledoc """
7 Helpers for use in tests.
8 """
9 alias Pleroma.Config
10
11 defmacro clear_config(config_path) do
12 quote do
13 clear_config(unquote(config_path)) do
14 end
15 end
16 end
17
18 defmacro clear_config(config_path, do: yield) do
19 quote do
20 initial_setting = Config.get(unquote(config_path))
21 unquote(yield)
22 on_exit(fn -> Config.put(unquote(config_path), initial_setting) end)
23 :ok
24 end
25 end
26
27 defmacro clear_config(config_path, temp_setting) do
28 quote do
29 clear_config(unquote(config_path)) do
30 Config.put(unquote(config_path), unquote(temp_setting))
31 end
32 end
33 end
34
35 def require_migration(migration_name) do
36 [{module, _}] = Code.require_file("#{migration_name}.exs", "priv/repo/migrations")
37 {:ok, %{migration: module}}
38 end
39
40 defmacro __using__(_opts) do
41 quote do
42 import Pleroma.Tests.Helpers,
43 only: [
44 clear_config: 1,
45 clear_config: 2
46 ]
47
48 def to_datetime(%NaiveDateTime{} = naive_datetime) do
49 naive_datetime
50 |> DateTime.from_naive!("Etc/UTC")
51 |> DateTime.truncate(:second)
52 end
53
54 def to_datetime(datetime) when is_binary(datetime) do
55 datetime
56 |> NaiveDateTime.from_iso8601!()
57 |> to_datetime()
58 end
59
60 def collect_ids(collection) do
61 collection
62 |> Enum.map(& &1.id)
63 |> Enum.sort()
64 end
65
66 def refresh_record(%{id: id, __struct__: model} = _),
67 do: refresh_record(model, %{id: id})
68
69 def refresh_record(model, %{id: id} = _) do
70 Pleroma.Repo.get_by(model, id: id)
71 end
72
73 # Used for comparing json rendering during tests.
74 def render_json(view, template, assigns) do
75 assigns = Map.new(assigns)
76
77 view.render(template, assigns)
78 |> Poison.encode!()
79 |> Poison.decode!()
80 end
81
82 def stringify_keys(nil), do: nil
83
84 def stringify_keys(key) when key in [true, false], do: key
85 def stringify_keys(key) when is_atom(key), do: Atom.to_string(key)
86
87 def stringify_keys(map) when is_map(map) do
88 map
89 |> Enum.map(fn {k, v} -> {stringify_keys(k), stringify_keys(v)} end)
90 |> Enum.into(%{})
91 end
92
93 def stringify_keys([head | rest] = list) when is_list(list) do
94 [stringify_keys(head) | stringify_keys(rest)]
95 end
96
97 def stringify_keys(key), do: key
98
99 defmacro guards_config(config_path) do
100 quote do
101 initial_setting = Config.get(config_path)
102
103 Config.put(config_path, true)
104 on_exit(fn -> Config.put(config_path, initial_setting) end)
105 end
106 end
107 end
108 end
109 end