Merge branch 'develop' into issue/1383
[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 to_datetime(naive_datetime) do
57 naive_datetime
58 |> DateTime.from_naive!("Etc/UTC")
59 |> DateTime.truncate(:second)
60 end
61
62 def collect_ids(collection) do
63 collection
64 |> Enum.map(& &1.id)
65 |> Enum.sort()
66 end
67
68 def refresh_record(%{id: id, __struct__: model} = _),
69 do: refresh_record(model, %{id: id})
70
71 def refresh_record(model, %{id: id} = _) do
72 Pleroma.Repo.get_by(model, id: id)
73 end
74
75 # Used for comparing json rendering during tests.
76 def render_json(view, template, assigns) do
77 assigns = Map.new(assigns)
78
79 view.render(template, assigns)
80 |> Poison.encode!()
81 |> Poison.decode!()
82 end
83
84 defmacro guards_config(config_path) do
85 quote do
86 initial_setting = Pleroma.Config.get(config_path)
87
88 Pleroma.Config.put(config_path, true)
89 on_exit(fn -> Pleroma.Config.put(config_path, initial_setting) end)
90 end
91 end
92 end
93 end
94 end