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