Fork of Pleroma with site-specific changes and feature branches https://git.pleroma.social/pleroma/pleroma
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 line
2.6KB

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