Merge branch 'develop' into feature/report-notes
[akkoma] / test / support / helpers.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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
10 defmacro clear_config(config_path) do
11 quote do
12 clear_config(unquote(config_path)) do
13 end
14 end
15 end
16
17 defmacro clear_config(config_path, do: yield) do
18 quote do
19 setup do
20 initial_setting = Pleroma.Config.get(unquote(config_path))
21 unquote(yield)
22 on_exit(fn -> Pleroma.Config.put(unquote(config_path), initial_setting) end)
23 :ok
24 end
25 end
26 end
27
28 defmacro clear_config_all(config_path) do
29 quote do
30 clear_config_all(unquote(config_path)) do
31 end
32 end
33 end
34
35 defmacro clear_config_all(config_path, do: yield) do
36 quote do
37 setup_all do
38 initial_setting = Pleroma.Config.get(unquote(config_path))
39 unquote(yield)
40 on_exit(fn -> Pleroma.Config.put(unquote(config_path), initial_setting) end)
41 :ok
42 end
43 end
44 end
45
46 defmacro __using__(_opts) do
47 quote do
48 import Pleroma.Tests.Helpers,
49 only: [
50 clear_config: 1,
51 clear_config: 2,
52 clear_config_all: 1,
53 clear_config_all: 2
54 ]
55
56 def collect_ids(collection) do
57 collection
58 |> Enum.map(& &1.id)
59 |> Enum.sort()
60 end
61
62 def refresh_record(%{id: id, __struct__: model} = _),
63 do: refresh_record(model, %{id: id})
64
65 def refresh_record(model, %{id: id} = _) do
66 Pleroma.Repo.get_by(model, id: id)
67 end
68
69 # Used for comparing json rendering during tests.
70 def render_json(view, template, assigns) do
71 assigns = Map.new(assigns)
72
73 view.render(template, assigns)
74 |> Poison.encode!()
75 |> Poison.decode!()
76 end
77
78 def stringify_keys(nil), do: nil
79
80 def stringify_keys(key) when key in [true, false], do: key
81 def stringify_keys(key) when is_atom(key), do: Atom.to_string(key)
82
83 def stringify_keys(map) when is_map(map) do
84 map
85 |> Enum.map(fn {k, v} -> {stringify_keys(k), stringify_keys(v)} end)
86 |> Enum.into(%{})
87 end
88
89 def stringify_keys([head | rest] = list) when is_list(list) do
90 [stringify_keys(head) | stringify_keys(rest)]
91 end
92
93 def stringify_keys(key), do: key
94
95 defmacro guards_config(config_path) do
96 quote do
97 initial_setting = Pleroma.Config.get(config_path)
98
99 Pleroma.Config.put(config_path, true)
100 on_exit(fn -> Pleroma.Config.put(config_path, initial_setting) end)
101 end
102 end
103 end
104 end
105 end