1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Tests.Helpers do
7 Helpers for use in tests.
13 defmacro clear_config(config_path) do
15 clear_config(unquote(config_path)) do
20 defmacro clear_config(config_path, do: yield) do
22 initial_setting = Config.fetch(unquote(config_path))
27 case initial_setting do
29 Config.delete(unquote(config_path))
32 Config.put(unquote(config_path), value)
40 defmacro clear_config(config_path, temp_setting) do
41 # NOTE: `clear_config([section, key], value)` != `clear_config([section], key: value)` (!)
42 # Displaying a warning to prevent unintentional clearing of all but one keys in section
43 if Keyword.keyword?(temp_setting) and length(temp_setting) == 1 do
45 "Please change `clear_config([section], key: value)` to `clear_config([section, key], value) (#{inspect(config_path)} = #{inspect(temp_setting)})`"
50 clear_config(unquote(config_path)) do
51 Config.put(unquote(config_path), unquote(temp_setting))
56 def require_migration(migration_name) do
57 [{module, _}] = Code.require_file("#{migration_name}.exs", "priv/repo/migrations")
58 {:ok, %{migration: module}}
61 defmacro __using__(_opts) do
63 import Pleroma.Tests.Helpers,
69 def time_travel(entity, seconds) do
70 new_time = NaiveDateTime.add(entity.inserted_at, seconds)
73 |> Ecto.Changeset.change(%{inserted_at: new_time, updated_at: new_time})
74 |> Pleroma.Repo.update()
77 def to_datetime(%NaiveDateTime{} = naive_datetime) do
79 |> DateTime.from_naive!("Etc/UTC")
80 |> DateTime.truncate(:second)
83 def to_datetime(datetime) when is_binary(datetime) do
85 |> NaiveDateTime.from_iso8601!()
89 def collect_ids(collection) do
95 def refresh_record(%{id: id, __struct__: model} = _),
96 do: refresh_record(model, %{id: id})
98 def refresh_record(model, %{id: id} = _) do
99 Pleroma.Repo.get_by(model, id: id)
102 # Used for comparing json rendering during tests.
103 def render_json(view, template, assigns) do
104 assigns = Map.new(assigns)
106 view.render(template, assigns)
111 def stringify_keys(nil), do: nil
113 def stringify_keys(key) when key in [true, false], do: key
114 def stringify_keys(key) when is_atom(key), do: Atom.to_string(key)
116 def stringify_keys(map) when is_map(map) do
118 |> Enum.map(fn {k, v} -> {stringify_keys(k), stringify_keys(v)} end)
122 def stringify_keys([head | rest] = list) when is_list(list) do
123 [stringify_keys(head) | stringify_keys(rest)]
126 def stringify_keys(key), do: key
128 defmacro guards_config(config_path) do
130 initial_setting = Config.get(config_path)
132 Config.put(config_path, true)
133 on_exit(fn -> Config.put(config_path, initial_setting) end)