diff options
Diffstat (limited to 'test')
77 files changed, 4598 insertions, 3073 deletions
diff --git a/test/captcha_test.exs b/test/captcha_test.exs index 9f395d6b4..393c8219e 100644 --- a/test/captcha_test.exs +++ b/test/captcha_test.exs @@ -8,6 +8,7 @@ defmodule Pleroma.CaptchaTest do import Tesla.Mock alias Pleroma.Captcha.Kocaptcha + alias Pleroma.Captcha.Native @ets_options [:ordered_set, :private, :named_table, {:read_concurrency, true}] @@ -43,4 +44,21 @@ defmodule Pleroma.CaptchaTest do ) == :ok end end + + describe "Native" do + test "new and validate" do + new = Native.new() + + assert %{ + answer_data: answer, + token: token, + type: :native, + url: "data:image/png;base64," <> _ + } = new + + assert is_binary(answer) + assert :ok = Native.validate(token, answer, answer) + assert {:error, "Invalid CAPTCHA"} == Native.validate(token, answer, answer <> "foobar") + end + end end diff --git a/test/config/config_db_test.exs b/test/config/config_db_test.exs new file mode 100644 index 000000000..812709fd8 --- /dev/null +++ b/test/config/config_db_test.exs @@ -0,0 +1,713 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.ConfigDBTest do + use Pleroma.DataCase, async: true + import Pleroma.Factory + alias Pleroma.ConfigDB + + test "get_by_key/1" do + config = insert(:config) + insert(:config) + + assert config == ConfigDB.get_by_params(%{group: config.group, key: config.key}) + end + + test "create/1" do + {:ok, config} = ConfigDB.create(%{group: ":pleroma", key: ":some_key", value: "some_value"}) + assert config == ConfigDB.get_by_params(%{group: ":pleroma", key: ":some_key"}) + end + + test "update/1" do + config = insert(:config) + {:ok, updated} = ConfigDB.update(config, %{value: "some_value"}) + loaded = ConfigDB.get_by_params(%{group: config.group, key: config.key}) + assert loaded == updated + end + + test "get_all_as_keyword/0" do + saved = insert(:config) + insert(:config, group: ":quack", key: ":level", value: ConfigDB.to_binary(:info)) + insert(:config, group: ":quack", key: ":meta", value: ConfigDB.to_binary([:none])) + + insert(:config, + group: ":quack", + key: ":webhook_url", + value: ConfigDB.to_binary("https://hooks.slack.com/services/KEY/some_val") + ) + + config = ConfigDB.get_all_as_keyword() + + assert config[:pleroma] == [ + {ConfigDB.from_string(saved.key), ConfigDB.from_binary(saved.value)} + ] + + assert config[:quack] == [ + level: :info, + meta: [:none], + webhook_url: "https://hooks.slack.com/services/KEY/some_val" + ] + end + + describe "update_or_create/1" do + test "common" do + config = insert(:config) + key2 = "another_key" + + params = [ + %{group: "pleroma", key: key2, value: "another_value"}, + %{group: config.group, key: config.key, value: "new_value"} + ] + + assert Repo.all(ConfigDB) |> length() == 1 + + Enum.each(params, &ConfigDB.update_or_create(&1)) + + assert Repo.all(ConfigDB) |> length() == 2 + + config1 = ConfigDB.get_by_params(%{group: config.group, key: config.key}) + config2 = ConfigDB.get_by_params(%{group: "pleroma", key: key2}) + + assert config1.value == ConfigDB.transform("new_value") + assert config2.value == ConfigDB.transform("another_value") + end + + test "partial update" do + config = insert(:config, value: ConfigDB.to_binary(key1: "val1", key2: :val2)) + + {:ok, _config} = + ConfigDB.update_or_create(%{ + group: config.group, + key: config.key, + value: [key1: :val1, key3: :val3] + }) + + updated = ConfigDB.get_by_params(%{group: config.group, key: config.key}) + + value = ConfigDB.from_binary(updated.value) + assert length(value) == 3 + assert value[:key1] == :val1 + assert value[:key2] == :val2 + assert value[:key3] == :val3 + end + + test "deep merge" do + config = insert(:config, value: ConfigDB.to_binary(key1: "val1", key2: [k1: :v1, k2: "v2"])) + + {:ok, config} = + ConfigDB.update_or_create(%{ + group: config.group, + key: config.key, + value: [key1: :val1, key2: [k2: :v2, k3: :v3], key3: :val3] + }) + + updated = ConfigDB.get_by_params(%{group: config.group, key: config.key}) + + assert config.value == updated.value + + value = ConfigDB.from_binary(updated.value) + assert value[:key1] == :val1 + assert value[:key2] == [k1: :v1, k2: :v2, k3: :v3] + assert value[:key3] == :val3 + end + + test "only full update for some keys" do + config1 = insert(:config, key: ":ecto_repos", value: ConfigDB.to_binary(repo: Pleroma.Repo)) + + config2 = + insert(:config, group: ":cors_plug", key: ":max_age", value: ConfigDB.to_binary(18)) + + {:ok, _config} = + ConfigDB.update_or_create(%{ + group: config1.group, + key: config1.key, + value: [another_repo: [Pleroma.Repo]] + }) + + {:ok, _config} = + ConfigDB.update_or_create(%{ + group: config2.group, + key: config2.key, + value: 777 + }) + + updated1 = ConfigDB.get_by_params(%{group: config1.group, key: config1.key}) + updated2 = ConfigDB.get_by_params(%{group: config2.group, key: config2.key}) + + assert ConfigDB.from_binary(updated1.value) == [another_repo: [Pleroma.Repo]] + assert ConfigDB.from_binary(updated2.value) == 777 + end + + test "full update if value is not keyword" do + config = + insert(:config, + group: ":tesla", + key: ":adapter", + value: ConfigDB.to_binary(Tesla.Adapter.Hackney) + ) + + {:ok, _config} = + ConfigDB.update_or_create(%{ + group: config.group, + key: config.key, + value: Tesla.Adapter.Httpc + }) + + updated = ConfigDB.get_by_params(%{group: config.group, key: config.key}) + + assert ConfigDB.from_binary(updated.value) == Tesla.Adapter.Httpc + end + + test "only full update for some subkeys" do + config1 = + insert(:config, + key: ":emoji", + value: ConfigDB.to_binary(groups: [a: 1, b: 2], key: [a: 1]) + ) + + config2 = + insert(:config, + key: ":assets", + value: ConfigDB.to_binary(mascots: [a: 1, b: 2], key: [a: 1]) + ) + + {:ok, _config} = + ConfigDB.update_or_create(%{ + group: config1.group, + key: config1.key, + value: [groups: [c: 3, d: 4], key: [b: 2]] + }) + + {:ok, _config} = + ConfigDB.update_or_create(%{ + group: config2.group, + key: config2.key, + value: [mascots: [c: 3, d: 4], key: [b: 2]] + }) + + updated1 = ConfigDB.get_by_params(%{group: config1.group, key: config1.key}) + updated2 = ConfigDB.get_by_params(%{group: config2.group, key: config2.key}) + + assert ConfigDB.from_binary(updated1.value) == [groups: [c: 3, d: 4], key: [a: 1, b: 2]] + assert ConfigDB.from_binary(updated2.value) == [mascots: [c: 3, d: 4], key: [a: 1, b: 2]] + end + end + + describe "delete/1" do + test "error on deleting non existing setting" do + {:error, error} = ConfigDB.delete(%{group: ":pleroma", key: ":key"}) + assert error =~ "Config with params %{group: \":pleroma\", key: \":key\"} not found" + end + + test "full delete" do + config = insert(:config) + {:ok, deleted} = ConfigDB.delete(%{group: config.group, key: config.key}) + assert Ecto.get_meta(deleted, :state) == :deleted + refute ConfigDB.get_by_params(%{group: config.group, key: config.key}) + end + + test "partial subkeys delete" do + config = insert(:config, value: ConfigDB.to_binary(groups: [a: 1, b: 2], key: [a: 1])) + + {:ok, deleted} = + ConfigDB.delete(%{group: config.group, key: config.key, subkeys: [":groups"]}) + + assert Ecto.get_meta(deleted, :state) == :loaded + + assert deleted.value == ConfigDB.to_binary(key: [a: 1]) + + updated = ConfigDB.get_by_params(%{group: config.group, key: config.key}) + + assert updated.value == deleted.value + end + + test "full delete if remaining value after subkeys deletion is empty list" do + config = insert(:config, value: ConfigDB.to_binary(groups: [a: 1, b: 2])) + + {:ok, deleted} = + ConfigDB.delete(%{group: config.group, key: config.key, subkeys: [":groups"]}) + + assert Ecto.get_meta(deleted, :state) == :deleted + + refute ConfigDB.get_by_params(%{group: config.group, key: config.key}) + end + end + + describe "transform/1" do + test "string" do + binary = ConfigDB.transform("value as string") + assert binary == :erlang.term_to_binary("value as string") + assert ConfigDB.from_binary(binary) == "value as string" + end + + test "boolean" do + binary = ConfigDB.transform(false) + assert binary == :erlang.term_to_binary(false) + assert ConfigDB.from_binary(binary) == false + end + + test "nil" do + binary = ConfigDB.transform(nil) + assert binary == :erlang.term_to_binary(nil) + assert ConfigDB.from_binary(binary) == nil + end + + test "integer" do + binary = ConfigDB.transform(150) + assert binary == :erlang.term_to_binary(150) + assert ConfigDB.from_binary(binary) == 150 + end + + test "atom" do + binary = ConfigDB.transform(":atom") + assert binary == :erlang.term_to_binary(:atom) + assert ConfigDB.from_binary(binary) == :atom + end + + test "ssl options" do + binary = ConfigDB.transform([":tlsv1", ":tlsv1.1", ":tlsv1.2"]) + assert binary == :erlang.term_to_binary([:tlsv1, :"tlsv1.1", :"tlsv1.2"]) + assert ConfigDB.from_binary(binary) == [:tlsv1, :"tlsv1.1", :"tlsv1.2"] + end + + test "pleroma module" do + binary = ConfigDB.transform("Pleroma.Bookmark") + assert binary == :erlang.term_to_binary(Pleroma.Bookmark) + assert ConfigDB.from_binary(binary) == Pleroma.Bookmark + end + + test "pleroma string" do + binary = ConfigDB.transform("Pleroma") + assert binary == :erlang.term_to_binary("Pleroma") + assert ConfigDB.from_binary(binary) == "Pleroma" + end + + test "phoenix module" do + binary = ConfigDB.transform("Phoenix.Socket.V1.JSONSerializer") + assert binary == :erlang.term_to_binary(Phoenix.Socket.V1.JSONSerializer) + assert ConfigDB.from_binary(binary) == Phoenix.Socket.V1.JSONSerializer + end + + test "tesla module" do + binary = ConfigDB.transform("Tesla.Adapter.Hackney") + assert binary == :erlang.term_to_binary(Tesla.Adapter.Hackney) + assert ConfigDB.from_binary(binary) == Tesla.Adapter.Hackney + end + + test "ExSyslogger module" do + binary = ConfigDB.transform("ExSyslogger") + assert binary == :erlang.term_to_binary(ExSyslogger) + assert ConfigDB.from_binary(binary) == ExSyslogger + end + + test "Quack.Logger module" do + binary = ConfigDB.transform("Quack.Logger") + assert binary == :erlang.term_to_binary(Quack.Logger) + assert ConfigDB.from_binary(binary) == Quack.Logger + end + + test "Swoosh.Adapters modules" do + binary = ConfigDB.transform("Swoosh.Adapters.SMTP") + assert binary == :erlang.term_to_binary(Swoosh.Adapters.SMTP) + assert ConfigDB.from_binary(binary) == Swoosh.Adapters.SMTP + binary = ConfigDB.transform("Swoosh.Adapters.AmazonSES") + assert binary == :erlang.term_to_binary(Swoosh.Adapters.AmazonSES) + assert ConfigDB.from_binary(binary) == Swoosh.Adapters.AmazonSES + end + + test "sigil" do + binary = ConfigDB.transform("~r[comp[lL][aA][iI][nN]er]") + assert binary == :erlang.term_to_binary(~r/comp[lL][aA][iI][nN]er/) + assert ConfigDB.from_binary(binary) == ~r/comp[lL][aA][iI][nN]er/ + end + + test "link sigil" do + binary = ConfigDB.transform("~r/https:\/\/example.com/") + assert binary == :erlang.term_to_binary(~r/https:\/\/example.com/) + assert ConfigDB.from_binary(binary) == ~r/https:\/\/example.com/ + end + + test "link sigil with um modifiers" do + binary = ConfigDB.transform("~r/https:\/\/example.com/um") + assert binary == :erlang.term_to_binary(~r/https:\/\/example.com/um) + assert ConfigDB.from_binary(binary) == ~r/https:\/\/example.com/um + end + + test "link sigil with i modifier" do + binary = ConfigDB.transform("~r/https:\/\/example.com/i") + assert binary == :erlang.term_to_binary(~r/https:\/\/example.com/i) + assert ConfigDB.from_binary(binary) == ~r/https:\/\/example.com/i + end + + test "link sigil with s modifier" do + binary = ConfigDB.transform("~r/https:\/\/example.com/s") + assert binary == :erlang.term_to_binary(~r/https:\/\/example.com/s) + assert ConfigDB.from_binary(binary) == ~r/https:\/\/example.com/s + end + + test "raise if valid delimiter not found" do + assert_raise ArgumentError, "valid delimiter for Regex expression not found", fn -> + ConfigDB.transform("~r/https://[]{}<>\"'()|example.com/s") + end + end + + test "2 child tuple" do + binary = ConfigDB.transform(%{"tuple" => ["v1", ":v2"]}) + assert binary == :erlang.term_to_binary({"v1", :v2}) + assert ConfigDB.from_binary(binary) == {"v1", :v2} + end + + test "proxy tuple with localhost" do + binary = + ConfigDB.transform(%{ + "tuple" => [":proxy_url", %{"tuple" => [":socks5", "localhost", 1234]}] + }) + + assert binary == :erlang.term_to_binary({:proxy_url, {:socks5, :localhost, 1234}}) + assert ConfigDB.from_binary(binary) == {:proxy_url, {:socks5, :localhost, 1234}} + end + + test "proxy tuple with domain" do + binary = + ConfigDB.transform(%{ + "tuple" => [":proxy_url", %{"tuple" => [":socks5", "domain.com", 1234]}] + }) + + assert binary == :erlang.term_to_binary({:proxy_url, {:socks5, 'domain.com', 1234}}) + assert ConfigDB.from_binary(binary) == {:proxy_url, {:socks5, 'domain.com', 1234}} + end + + test "proxy tuple with ip" do + binary = + ConfigDB.transform(%{ + "tuple" => [":proxy_url", %{"tuple" => [":socks5", "127.0.0.1", 1234]}] + }) + + assert binary == :erlang.term_to_binary({:proxy_url, {:socks5, {127, 0, 0, 1}, 1234}}) + assert ConfigDB.from_binary(binary) == {:proxy_url, {:socks5, {127, 0, 0, 1}, 1234}} + end + + test "tuple with n childs" do + binary = + ConfigDB.transform(%{ + "tuple" => [ + "v1", + ":v2", + "Pleroma.Bookmark", + 150, + false, + "Phoenix.Socket.V1.JSONSerializer" + ] + }) + + assert binary == + :erlang.term_to_binary( + {"v1", :v2, Pleroma.Bookmark, 150, false, Phoenix.Socket.V1.JSONSerializer} + ) + + assert ConfigDB.from_binary(binary) == + {"v1", :v2, Pleroma.Bookmark, 150, false, Phoenix.Socket.V1.JSONSerializer} + end + + test "map with string key" do + binary = ConfigDB.transform(%{"key" => "value"}) + assert binary == :erlang.term_to_binary(%{"key" => "value"}) + assert ConfigDB.from_binary(binary) == %{"key" => "value"} + end + + test "map with atom key" do + binary = ConfigDB.transform(%{":key" => "value"}) + assert binary == :erlang.term_to_binary(%{key: "value"}) + assert ConfigDB.from_binary(binary) == %{key: "value"} + end + + test "list of strings" do + binary = ConfigDB.transform(["v1", "v2", "v3"]) + assert binary == :erlang.term_to_binary(["v1", "v2", "v3"]) + assert ConfigDB.from_binary(binary) == ["v1", "v2", "v3"] + end + + test "list of modules" do + binary = ConfigDB.transform(["Pleroma.Repo", "Pleroma.Activity"]) + assert binary == :erlang.term_to_binary([Pleroma.Repo, Pleroma.Activity]) + assert ConfigDB.from_binary(binary) == [Pleroma.Repo, Pleroma.Activity] + end + + test "list of atoms" do + binary = ConfigDB.transform([":v1", ":v2", ":v3"]) + assert binary == :erlang.term_to_binary([:v1, :v2, :v3]) + assert ConfigDB.from_binary(binary) == [:v1, :v2, :v3] + end + + test "list of mixed values" do + binary = + ConfigDB.transform([ + "v1", + ":v2", + "Pleroma.Repo", + "Phoenix.Socket.V1.JSONSerializer", + 15, + false + ]) + + assert binary == + :erlang.term_to_binary([ + "v1", + :v2, + Pleroma.Repo, + Phoenix.Socket.V1.JSONSerializer, + 15, + false + ]) + + assert ConfigDB.from_binary(binary) == [ + "v1", + :v2, + Pleroma.Repo, + Phoenix.Socket.V1.JSONSerializer, + 15, + false + ] + end + + test "simple keyword" do + binary = ConfigDB.transform([%{"tuple" => [":key", "value"]}]) + assert binary == :erlang.term_to_binary([{:key, "value"}]) + assert ConfigDB.from_binary(binary) == [{:key, "value"}] + assert ConfigDB.from_binary(binary) == [key: "value"] + end + + test "keyword with partial_chain key" do + binary = + ConfigDB.transform([%{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]}]) + + assert binary == :erlang.term_to_binary(partial_chain: &:hackney_connect.partial_chain/1) + assert ConfigDB.from_binary(binary) == [partial_chain: &:hackney_connect.partial_chain/1] + end + + test "keyword" do + binary = + ConfigDB.transform([ + %{"tuple" => [":types", "Pleroma.PostgresTypes"]}, + %{"tuple" => [":telemetry_event", ["Pleroma.Repo.Instrumenter"]]}, + %{"tuple" => [":migration_lock", nil]}, + %{"tuple" => [":key1", 150]}, + %{"tuple" => [":key2", "string"]} + ]) + + assert binary == + :erlang.term_to_binary( + types: Pleroma.PostgresTypes, + telemetry_event: [Pleroma.Repo.Instrumenter], + migration_lock: nil, + key1: 150, + key2: "string" + ) + + assert ConfigDB.from_binary(binary) == [ + types: Pleroma.PostgresTypes, + telemetry_event: [Pleroma.Repo.Instrumenter], + migration_lock: nil, + key1: 150, + key2: "string" + ] + end + + test "complex keyword with nested mixed childs" do + binary = + ConfigDB.transform([ + %{"tuple" => [":uploader", "Pleroma.Uploaders.Local"]}, + %{"tuple" => [":filters", ["Pleroma.Upload.Filter.Dedupe"]]}, + %{"tuple" => [":link_name", true]}, + %{"tuple" => [":proxy_remote", false]}, + %{"tuple" => [":common_map", %{":key" => "value"}]}, + %{ + "tuple" => [ + ":proxy_opts", + [ + %{"tuple" => [":redirect_on_failure", false]}, + %{"tuple" => [":max_body_length", 1_048_576]}, + %{ + "tuple" => [ + ":http", + [%{"tuple" => [":follow_redirect", true]}, %{"tuple" => [":pool", ":upload"]}] + ] + } + ] + ] + } + ]) + + assert binary == + :erlang.term_to_binary( + uploader: Pleroma.Uploaders.Local, + filters: [Pleroma.Upload.Filter.Dedupe], + link_name: true, + proxy_remote: false, + common_map: %{key: "value"}, + proxy_opts: [ + redirect_on_failure: false, + max_body_length: 1_048_576, + http: [ + follow_redirect: true, + pool: :upload + ] + ] + ) + + assert ConfigDB.from_binary(binary) == + [ + uploader: Pleroma.Uploaders.Local, + filters: [Pleroma.Upload.Filter.Dedupe], + link_name: true, + proxy_remote: false, + common_map: %{key: "value"}, + proxy_opts: [ + redirect_on_failure: false, + max_body_length: 1_048_576, + http: [ + follow_redirect: true, + pool: :upload + ] + ] + ] + end + + test "common keyword" do + binary = + ConfigDB.transform([ + %{"tuple" => [":level", ":warn"]}, + %{"tuple" => [":meta", [":all"]]}, + %{"tuple" => [":path", ""]}, + %{"tuple" => [":val", nil]}, + %{"tuple" => [":webhook_url", "https://hooks.slack.com/services/YOUR-KEY-HERE"]} + ]) + + assert binary == + :erlang.term_to_binary( + level: :warn, + meta: [:all], + path: "", + val: nil, + webhook_url: "https://hooks.slack.com/services/YOUR-KEY-HERE" + ) + + assert ConfigDB.from_binary(binary) == [ + level: :warn, + meta: [:all], + path: "", + val: nil, + webhook_url: "https://hooks.slack.com/services/YOUR-KEY-HERE" + ] + end + + test "complex keyword with sigil" do + binary = + ConfigDB.transform([ + %{"tuple" => [":federated_timeline_removal", []]}, + %{"tuple" => [":reject", ["~r/comp[lL][aA][iI][nN]er/"]]}, + %{"tuple" => [":replace", []]} + ]) + + assert binary == + :erlang.term_to_binary( + federated_timeline_removal: [], + reject: [~r/comp[lL][aA][iI][nN]er/], + replace: [] + ) + + assert ConfigDB.from_binary(binary) == + [federated_timeline_removal: [], reject: [~r/comp[lL][aA][iI][nN]er/], replace: []] + end + + test "complex keyword with tuples with more than 2 values" do + binary = + ConfigDB.transform([ + %{ + "tuple" => [ + ":http", + [ + %{ + "tuple" => [ + ":key1", + [ + %{ + "tuple" => [ + ":_", + [ + %{ + "tuple" => [ + "/api/v1/streaming", + "Pleroma.Web.MastodonAPI.WebsocketHandler", + [] + ] + }, + %{ + "tuple" => [ + "/websocket", + "Phoenix.Endpoint.CowboyWebSocket", + %{ + "tuple" => [ + "Phoenix.Transports.WebSocket", + %{ + "tuple" => [ + "Pleroma.Web.Endpoint", + "Pleroma.Web.UserSocket", + [] + ] + } + ] + } + ] + }, + %{ + "tuple" => [ + ":_", + "Phoenix.Endpoint.Cowboy2Handler", + %{"tuple" => ["Pleroma.Web.Endpoint", []]} + ] + } + ] + ] + } + ] + ] + } + ] + ] + } + ]) + + assert binary == + :erlang.term_to_binary( + http: [ + key1: [ + _: [ + {"/api/v1/streaming", Pleroma.Web.MastodonAPI.WebsocketHandler, []}, + {"/websocket", Phoenix.Endpoint.CowboyWebSocket, + {Phoenix.Transports.WebSocket, + {Pleroma.Web.Endpoint, Pleroma.Web.UserSocket, []}}}, + {:_, Phoenix.Endpoint.Cowboy2Handler, {Pleroma.Web.Endpoint, []}} + ] + ] + ] + ) + + assert ConfigDB.from_binary(binary) == [ + http: [ + key1: [ + {:_, + [ + {"/api/v1/streaming", Pleroma.Web.MastodonAPI.WebsocketHandler, []}, + {"/websocket", Phoenix.Endpoint.CowboyWebSocket, + {Phoenix.Transports.WebSocket, + {Pleroma.Web.Endpoint, Pleroma.Web.UserSocket, []}}}, + {:_, Phoenix.Endpoint.Cowboy2Handler, {Pleroma.Web.Endpoint, []}} + ]} + ] + ] + ] + end + end +end diff --git a/test/config/holder_test.exs b/test/config/holder_test.exs new file mode 100644 index 000000000..0c1882d0f --- /dev/null +++ b/test/config/holder_test.exs @@ -0,0 +1,34 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Config.HolderTest do + use ExUnit.Case, async: true + + alias Pleroma.Config.Holder + + test "config/0" do + config = Holder.config() + assert config[:pleroma][Pleroma.Uploaders.Local][:uploads] == "test/uploads" + assert config[:tesla][:adapter] == Tesla.Mock + + refute config[:pleroma][Pleroma.Repo] + refute config[:pleroma][Pleroma.Web.Endpoint] + refute config[:pleroma][:env] + refute config[:pleroma][:configurable_from_database] + refute config[:pleroma][:database] + refute config[:phoenix][:serve_endpoints] + end + + test "config/1" do + pleroma_config = Holder.config(:pleroma) + assert pleroma_config[Pleroma.Uploaders.Local][:uploads] == "test/uploads" + tesla_config = Holder.config(:tesla) + assert tesla_config[:adapter] == Tesla.Mock + end + + test "config/2" do + assert Holder.config(:pleroma, Pleroma.Uploaders.Local) == [uploads: "test/uploads"] + assert Holder.config(:tesla, :adapter) == Tesla.Mock + end +end diff --git a/test/config/loader_test.exs b/test/config/loader_test.exs new file mode 100644 index 000000000..0dd4c60bb --- /dev/null +++ b/test/config/loader_test.exs @@ -0,0 +1,44 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Config.LoaderTest do + use ExUnit.Case, async: true + + alias Pleroma.Config.Loader + + test "load/1" do + config = Loader.load("test/fixtures/config/temp.secret.exs") + assert config[:pleroma][:first_setting][:key] == "value" + assert config[:pleroma][:first_setting][:key2] == [Pleroma.Repo] + assert config[:quack][:level] == :info + end + + test "load_and_merge/0" do + config = Loader.load_and_merge() + + refute config[:pleroma][Pleroma.Repo] + refute config[:pleroma][Pleroma.Web.Endpoint] + refute config[:pleroma][:env] + refute config[:pleroma][:configurable_from_database] + refute config[:pleroma][:database] + refute config[:phoenix][:serve_endpoints] + + assert config[:pleroma][:ecto_repos] == [Pleroma.Repo] + assert config[:pleroma][Pleroma.Uploaders.Local][:uploads] == "test/uploads" + assert config[:tesla][:adapter] == Tesla.Mock + end + + test "filter_group/2" do + assert Loader.filter_group(:pleroma, + pleroma: [ + {Pleroma.Repo, [a: 1, b: 2]}, + {Pleroma.Upload, [a: 1, b: 2]}, + {Pleroma.Web.Endpoint, []}, + env: :test, + configurable_from_database: true, + database: [] + ] + ) == [{Pleroma.Upload, [a: 1, b: 2]}] + end +end diff --git a/test/config/transfer_task_test.exs b/test/config/transfer_task_test.exs index 9074f3b97..53e8703fd 100644 --- a/test/config/transfer_task_test.exs +++ b/test/config/transfer_task_test.exs @@ -5,47 +5,104 @@ defmodule Pleroma.Config.TransferTaskTest do use Pleroma.DataCase - clear_config([:instance, :dynamic_configuration]) do - Pleroma.Config.put([:instance, :dynamic_configuration], true) + alias Pleroma.Config.TransferTask + alias Pleroma.ConfigDB + + clear_config(:configurable_from_database) do + Pleroma.Config.put(:configurable_from_database, true) end test "transfer config values from db to env" do refute Application.get_env(:pleroma, :test_key) refute Application.get_env(:idna, :test_key) + refute Application.get_env(:quack, :test_key) - Pleroma.Web.AdminAPI.Config.create(%{ - group: "pleroma", - key: "test_key", + ConfigDB.create(%{ + group: ":pleroma", + key: ":test_key", value: [live: 2, com: 3] }) - Pleroma.Web.AdminAPI.Config.create(%{ - group: "idna", - key: "test_key", + ConfigDB.create(%{ + group: ":idna", + key: ":test_key", value: [live: 15, com: 35] }) - Pleroma.Config.TransferTask.start_link([]) + ConfigDB.create(%{ + group: ":quack", + key: ":test_key", + value: [:test_value1, :test_value2] + }) + + TransferTask.start_link([]) assert Application.get_env(:pleroma, :test_key) == [live: 2, com: 3] assert Application.get_env(:idna, :test_key) == [live: 15, com: 35] + assert Application.get_env(:quack, :test_key) == [:test_value1, :test_value2] on_exit(fn -> Application.delete_env(:pleroma, :test_key) Application.delete_env(:idna, :test_key) + Application.delete_env(:quack, :test_key) end) end - test "non existing atom" do - Pleroma.Web.AdminAPI.Config.create(%{ - group: "pleroma", - key: "undefined_atom_key", - value: [live: 2, com: 3] + test "transfer config values for 1 group and some keys" do + level = Application.get_env(:quack, :level) + meta = Application.get_env(:quack, :meta) + + ConfigDB.create(%{ + group: ":quack", + key: ":level", + value: :info + }) + + ConfigDB.create(%{ + group: ":quack", + key: ":meta", + value: [:none] + }) + + TransferTask.start_link([]) + + assert Application.get_env(:quack, :level) == :info + assert Application.get_env(:quack, :meta) == [:none] + default = Pleroma.Config.Holder.config(:quack, :webhook_url) + assert Application.get_env(:quack, :webhook_url) == default + + on_exit(fn -> + Application.put_env(:quack, :level, level) + Application.put_env(:quack, :meta, meta) + end) + end + + test "transfer config values with full subkey update" do + emoji = Application.get_env(:pleroma, :emoji) + assets = Application.get_env(:pleroma, :assets) + + ConfigDB.create(%{ + group: ":pleroma", + key: ":emoji", + value: [groups: [a: 1, b: 2]] }) - assert ExUnit.CaptureLog.capture_log(fn -> - Pleroma.Config.TransferTask.start_link([]) - end) =~ - "updating env causes error, key: \"undefined_atom_key\", error: %ArgumentError{message: \"argument error\"}" + ConfigDB.create(%{ + group: ":pleroma", + key: ":assets", + value: [mascots: [a: 1, b: 2]] + }) + + TransferTask.start_link([]) + + emoji_env = Application.get_env(:pleroma, :emoji) + assert emoji_env[:groups] == [a: 1, b: 2] + assets_env = Application.get_env(:pleroma, :assets) + assert assets_env[:mascots] == [a: 1, b: 2] + + on_exit(fn -> + Application.put_env(:pleroma, :emoji, emoji) + Application.put_env(:pleroma, :assets, assets) + end) end end diff --git a/test/conversation/participation_test.exs b/test/conversation/participation_test.exs index 9b2c97963..ab9f27b2f 100644 --- a/test/conversation/participation_test.exs +++ b/test/conversation/participation_test.exs @@ -5,7 +5,9 @@ defmodule Pleroma.Conversation.ParticipationTest do use Pleroma.DataCase import Pleroma.Factory + alias Pleroma.Conversation alias Pleroma.Conversation.Participation + alias Pleroma.Repo alias Pleroma.User alias Pleroma.Web.CommonAPI @@ -98,7 +100,9 @@ defmodule Pleroma.Conversation.ParticipationTest do assert participation.user_id == user.id assert participation.conversation_id == conversation.id + # Needed because updated_at is accurate down to a second :timer.sleep(1000) + # Creating again returns the same participation {:ok, %Participation{} = participation_two} = Participation.create_for_user_and_conversation(user, conversation) @@ -121,9 +125,10 @@ defmodule Pleroma.Conversation.ParticipationTest do test "it marks a participation as read" do participation = insert(:participation, %{read: false}) - {:ok, participation} = Participation.mark_as_read(participation) + {:ok, updated_participation} = Participation.mark_as_read(participation) - assert participation.read + assert updated_participation.read + assert updated_participation.updated_at == participation.updated_at end test "it marks a participation as unread" do @@ -150,9 +155,7 @@ defmodule Pleroma.Conversation.ParticipationTest do test "gets all the participations for a user, ordered by updated at descending" do user = insert(:user) {:ok, activity_one} = CommonAPI.post(user, %{"status" => "x", "visibility" => "direct"}) - :timer.sleep(1000) {:ok, activity_two} = CommonAPI.post(user, %{"status" => "x", "visibility" => "direct"}) - :timer.sleep(1000) {:ok, activity_three} = CommonAPI.post(user, %{ @@ -161,6 +164,17 @@ defmodule Pleroma.Conversation.ParticipationTest do "in_reply_to_status_id" => activity_one.id }) + # Offset participations because the accuracy of updated_at is down to a second + + for {activity, offset} <- [{activity_two, 1}, {activity_three, 2}] do + conversation = Conversation.get_for_ap_id(activity.data["context"]) + participation = Participation.for_user_and_conversation(user, conversation) + updated_at = NaiveDateTime.add(Map.get(participation, :updated_at), offset) + + Ecto.Changeset.change(participation, %{updated_at: updated_at}) + |> Repo.update!() + end + assert [participation_one, participation_two] = Participation.for_user(user) object2 = Pleroma.Object.normalize(activity_two) diff --git a/test/docs/generator_test.exs b/test/docs/generator_test.exs new file mode 100644 index 000000000..9c9f4357b --- /dev/null +++ b/test/docs/generator_test.exs @@ -0,0 +1,230 @@ +defmodule Pleroma.Docs.GeneratorTest do + use ExUnit.Case, async: true + alias Pleroma.Docs.Generator + + @descriptions [ + %{ + group: :pleroma, + key: Pleroma.Upload, + type: :group, + description: "", + children: [ + %{ + key: :uploader, + type: :module, + description: "", + suggestions: + Generator.list_modules_in_dir( + "lib/pleroma/upload/filter", + "Elixir.Pleroma.Upload.Filter." + ) + }, + %{ + key: :filters, + type: {:list, :module}, + description: "", + suggestions: + Generator.list_modules_in_dir( + "lib/pleroma/web/activity_pub/mrf", + "Elixir.Pleroma.Web.ActivityPub.MRF." + ) + }, + %{ + key: Pleroma.Upload, + type: :string, + description: "", + suggestions: [""] + }, + %{ + key: :some_key, + type: :keyword, + description: "", + suggestions: [], + children: [ + %{ + key: :another_key, + type: :integer, + description: "", + suggestions: [5] + }, + %{ + key: :another_key_with_label, + label: "Another label", + type: :integer, + description: "", + suggestions: [7] + } + ] + }, + %{ + key: :key1, + type: :atom, + description: "", + suggestions: [ + :atom, + Pleroma.Upload, + {:tuple, "string", 8080}, + [:atom, Pleroma.Upload, {:atom, Pleroma.Upload}] + ] + }, + %{ + key: Pleroma.Upload, + label: "Special Label", + type: :string, + description: "", + suggestions: [""] + }, + %{ + group: {:subgroup, Swoosh.Adapters.SMTP}, + key: :auth, + type: :atom, + description: "`Swoosh.Adapters.SMTP` adapter specific setting", + suggestions: [:always, :never, :if_available] + }, + %{ + key: "application/xml", + type: {:list, :string}, + suggestions: ["xml"] + }, + %{ + key: :versions, + type: {:list, :atom}, + description: "List of TLS version to use", + suggestions: [:tlsv1, ":tlsv1.1", ":tlsv1.2"] + } + ] + }, + %{ + group: :tesla, + key: :adapter, + type: :group, + description: "" + }, + %{ + group: :cors_plug, + type: :group, + children: [%{key: :key1, type: :string, suggestions: [""]}] + }, + %{group: "Some string group", key: "Some string key", type: :group} + ] + + describe "convert_to_strings/1" do + test "group, key, label" do + [desc1, desc2 | _] = Generator.convert_to_strings(@descriptions) + + assert desc1[:group] == ":pleroma" + assert desc1[:key] == "Pleroma.Upload" + assert desc1[:label] == "Pleroma.Upload" + + assert desc2[:group] == ":tesla" + assert desc2[:key] == ":adapter" + assert desc2[:label] == "Adapter" + end + + test "group without key" do + descriptions = Generator.convert_to_strings(@descriptions) + desc = Enum.at(descriptions, 2) + + assert desc[:group] == ":cors_plug" + refute desc[:key] + assert desc[:label] == "Cors plug" + end + + test "children key, label, type" do + [%{children: [child1, child2, child3, child4 | _]} | _] = + Generator.convert_to_strings(@descriptions) + + assert child1[:key] == ":uploader" + assert child1[:label] == "Uploader" + assert child1[:type] == :module + + assert child2[:key] == ":filters" + assert child2[:label] == "Filters" + assert child2[:type] == {:list, :module} + + assert child3[:key] == "Pleroma.Upload" + assert child3[:label] == "Pleroma.Upload" + assert child3[:type] == :string + + assert child4[:key] == ":some_key" + assert child4[:label] == "Some key" + assert child4[:type] == :keyword + end + + test "child with predefined label" do + [%{children: children} | _] = Generator.convert_to_strings(@descriptions) + child = Enum.at(children, 5) + assert child[:key] == "Pleroma.Upload" + assert child[:label] == "Special Label" + end + + test "subchild" do + [%{children: children} | _] = Generator.convert_to_strings(@descriptions) + child = Enum.at(children, 3) + %{children: [subchild | _]} = child + + assert subchild[:key] == ":another_key" + assert subchild[:label] == "Another key" + assert subchild[:type] == :integer + end + + test "subchild with predefined label" do + [%{children: children} | _] = Generator.convert_to_strings(@descriptions) + child = Enum.at(children, 3) + %{children: subchildren} = child + subchild = Enum.at(subchildren, 1) + + assert subchild[:key] == ":another_key_with_label" + assert subchild[:label] == "Another label" + end + + test "module suggestions" do + [%{children: [%{suggestions: suggestions} | _]} | _] = + Generator.convert_to_strings(@descriptions) + + Enum.each(suggestions, fn suggestion -> + assert String.starts_with?(suggestion, "Pleroma.") + end) + end + + test "atoms in suggestions with leading `:`" do + [%{children: children} | _] = Generator.convert_to_strings(@descriptions) + %{suggestions: suggestions} = Enum.at(children, 4) + assert Enum.at(suggestions, 0) == ":atom" + assert Enum.at(suggestions, 1) == "Pleroma.Upload" + assert Enum.at(suggestions, 2) == {":tuple", "string", 8080} + assert Enum.at(suggestions, 3) == [":atom", "Pleroma.Upload", {":atom", "Pleroma.Upload"}] + + %{suggestions: suggestions} = Enum.at(children, 6) + assert Enum.at(suggestions, 0) == ":always" + assert Enum.at(suggestions, 1) == ":never" + assert Enum.at(suggestions, 2) == ":if_available" + end + + test "group, key as string in main desc" do + descriptions = Generator.convert_to_strings(@descriptions) + desc = Enum.at(descriptions, 3) + assert desc[:group] == "Some string group" + assert desc[:key] == "Some string key" + end + + test "key as string subchild" do + [%{children: children} | _] = Generator.convert_to_strings(@descriptions) + child = Enum.at(children, 7) + assert child[:key] == "application/xml" + end + + test "suggestion for tls versions" do + [%{children: children} | _] = Generator.convert_to_strings(@descriptions) + child = Enum.at(children, 8) + assert child[:suggestions] == [":tlsv1", ":tlsv1.1", ":tlsv1.2"] + end + + test "subgroup with module name" do + [%{children: children} | _] = Generator.convert_to_strings(@descriptions) + + %{group: subgroup} = Enum.at(children, 6) + assert subgroup == {":subgroup", "Swoosh.Adapters.SMTP"} + end + end +end diff --git a/test/fixtures/config/temp.secret.exs b/test/fixtures/config/temp.secret.exs new file mode 100644 index 000000000..f4686c101 --- /dev/null +++ b/test/fixtures/config/temp.secret.exs @@ -0,0 +1,9 @@ +use Mix.Config + +config :pleroma, :first_setting, key: "value", key2: [Pleroma.Repo] + +config :pleroma, :second_setting, key: "value2", key2: ["Activity"] + +config :quack, level: :info + +config :pleroma, Pleroma.Repo, pool: Ecto.Adapters.SQL.Sandbox diff --git a/test/fixtures/modules/runtime_module.ex b/test/fixtures/modules/runtime_module.ex new file mode 100644 index 000000000..4711c3532 --- /dev/null +++ b/test/fixtures/modules/runtime_module.ex @@ -0,0 +1,9 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule RuntimeModule do + @moduledoc """ + This is a dummy module to test custom runtime modules. + """ +end diff --git a/test/fixtures/tesla_mock/mobilizon.org-event.json b/test/fixtures/tesla_mock/mobilizon.org-event.json new file mode 100644 index 000000000..7411cf817 --- /dev/null +++ b/test/fixtures/tesla_mock/mobilizon.org-event.json @@ -0,0 +1 @@ +{"@context":["https://www.w3.org/ns/activitystreams","https://litepub.social/litepub/context.jsonld",{"GeoCoordinates":"sc:GeoCoordinates","Hashtag":"as:Hashtag","Place":"sc:Place","PostalAddress":"sc:PostalAddress","address":{"@id":"sc:address","@type":"sc:PostalAddress"},"addressCountry":"sc:addressCountry","addressLocality":"sc:addressLocality","addressRegion":"sc:addressRegion","category":"sc:category","commentsEnabled":{"@id":"pt:commentsEnabled","@type":"sc:Boolean"},"geo":{"@id":"sc:geo","@type":"sc:GeoCoordinates"},"ical":"http://www.w3.org/2002/12/cal/ical#","joinMode":{"@id":"mz:joinMode","@type":"mz:joinModeType"},"joinModeType":{"@id":"mz:joinModeType","@type":"rdfs:Class"},"location":{"@id":"sc:location","@type":"sc:Place"},"maximumAttendeeCapacity":"sc:maximumAttendeeCapacity","mz":"https://joinmobilizon.org/ns#","postalCode":"sc:postalCode","pt":"https://joinpeertube.org/ns#","repliesModerationOption":{"@id":"mz:repliesModerationOption","@type":"mz:repliesModerationOptionType"},"repliesModerationOptionType":{"@id":"mz:repliesModerationOptionType","@type":"rdfs:Class"},"sc":"http://schema.org#","streetAddress":"sc:streetAddress","uuid":"sc:identifier"}],"actor":"https://mobilizon.org/@tcit","attributedTo":"https://mobilizon.org/@tcit","category":"meeting","cc":[],"commentsEnabled":true,"content":"<p>Mobilizon is now federated! 🎉</p><p></p><p>You can view this event from other instances if they are subscribed to mobilizon.org, and soon directly from Mastodon and Pleroma. It is possible that you may see some comments from other instances, including Mastodon ones, just below.</p><p></p><p>With a Mobilizon account on an instance, you may <strong>participate</strong> at events from other instances and <strong>add comments</strong> on events.</p><p></p><p>Of course, it's still <u>a work in progress</u>: if reports made from an instance on events and comments can be federated, you can't block people right now, and moderators actions are rather limited, but this <strong>will definitely get fixed over time</strong> until first stable version next year.</p><p></p><p>Anyway, if you want to come up with some feedback, head over to our forum or - if you feel you have technical skills and are familiar with it - on our Gitlab repository.</p><p></p><p>Also, to people that want to set Mobilizon themselves even though we really don't advise to do that for now, we have a little documentation but it's quite the early days and you'll probably need some help. No worries, you can chat with us on our Forum or though our Matrix channel.</p><p></p><p>Check our website for more informations and follow us on Twitter or Mastodon.</p>","endTime":"2019-12-18T14:00:00Z","ical:status":"CONFIRMED","id":"https://mobilizon.org/events/252d5816-00a3-4a89-a66f-15bf65c33e39","joinMode":"free","location":{"address":{"addressCountry":"France","addressLocality":"Nantes","addressRegion":"Pays de la Loire","postalCode":null,"streetAddress":" ","type":"PostalAddress"},"geo":{"latitude":-1.54939699141711,"longitude":47.21617415,"type":"GeoCoordinates"},"id":"https://mobilizon.org/address/1368fdab-1e2c-4de6-bcff-a90c84abdee1","name":"Cour du Château des Ducs de Bretagne","type":"Place"},"maximumAttendeeCapacity":0,"mediaType":"text/html","name":"Mobilizon Launching Party","published":"2019-12-17T11:33:56Z","repliesModerationOption":"allow_all","startTime":"2019-12-18T13:00:00Z","tag":[{"href":"https://mobilizon.org/tags/mobilizon","name":"#Mobilizon","type":"Hashtag"},{"href":"https://mobilizon.org/tags/federation","name":"#Federation","type":"Hashtag"},{"href":"https://mobilizon.org/tags/activitypub","name":"#ActivityPub","type":"Hashtag"},{"href":"https://mobilizon.org/tags/party","name":"#Party","type":"Hashtag"}],"to":["https://www.w3.org/ns/activitystreams#Public"],"type":"Event","updated":"2019-12-17T12:25:01Z","url":"https://mobilizon.org/events/252d5816-00a3-4a89-a66f-15bf65c33e39","uuid":"252d5816-00a3-4a89-a66f-15bf65c33e39"}
\ No newline at end of file diff --git a/test/fixtures/tesla_mock/mobilizon.org-user.json b/test/fixtures/tesla_mock/mobilizon.org-user.json new file mode 100644 index 000000000..f948ae5f0 --- /dev/null +++ b/test/fixtures/tesla_mock/mobilizon.org-user.json @@ -0,0 +1 @@ +{"@context":["https://www.w3.org/ns/activitystreams","https://litepub.social/litepub/context.jsonld",{"GeoCoordinates":"sc:GeoCoordinates","Hashtag":"as:Hashtag","Place":"sc:Place","PostalAddress":"sc:PostalAddress","address":{"@id":"sc:address","@type":"sc:PostalAddress"},"addressCountry":"sc:addressCountry","addressLocality":"sc:addressLocality","addressRegion":"sc:addressRegion","category":"sc:category","commentsEnabled":{"@id":"pt:commentsEnabled","@type":"sc:Boolean"},"geo":{"@id":"sc:geo","@type":"sc:GeoCoordinates"},"ical":"http://www.w3.org/2002/12/cal/ical#","joinMode":{"@id":"mz:joinMode","@type":"mz:joinModeType"},"joinModeType":{"@id":"mz:joinModeType","@type":"rdfs:Class"},"location":{"@id":"sc:location","@type":"sc:Place"},"maximumAttendeeCapacity":"sc:maximumAttendeeCapacity","mz":"https://joinmobilizon.org/ns#","postalCode":"sc:postalCode","pt":"https://joinpeertube.org/ns#","repliesModerationOption":{"@id":"mz:repliesModerationOption","@type":"mz:repliesModerationOptionType"},"repliesModerationOptionType":{"@id":"mz:repliesModerationOptionType","@type":"rdfs:Class"},"sc":"http://schema.org#","streetAddress":"sc:streetAddress","uuid":"sc:identifier"}],"endpoints":{"sharedInbox":"https://mobilizon.org/inbox"},"followers":"https://mobilizon.org/@tcit/followers","following":"https://mobilizon.org/@tcit/following","icon":{"mediaType":null,"type":"Image","url":"https://mobilizon.org/media/3a5f18c058a8193b1febfaf561f94ae8b91f85ac64c01ddf5ad7b251fb43baf5.jpg?name=profil.jpg"},"id":"https://mobilizon.org/@tcit","inbox":"https://mobilizon.org/@tcit/inbox","manuallyApprovesFollowers":false,"name":"Thomas Citharel","outbox":"https://mobilizon.org/@tcit/outbox","preferredUsername":"tcit","publicKey":{"id":"https://mobilizon.org/@tcit#main-key","owner":"https://mobilizon.org/@tcit","publicKeyPem":"-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAtzuZFviv5f12SuA0wZFMuwKS8RIlT3IjPCMLRDhiorZeV3UJ1lik\nDYO6mEh22KDXYgJtNVSYGF0Q5LJivgcvuvU+VQ048iTB1B2x0rHMr47KPByPjfVb\nKDeHt6fkHcLY0JK8UkIxW542wXAg4jX5w3gJi3pgTQrCT8VNyPbH1CaA0uW//9jc\nqzZQVFzpfdJoVOM9E3Urc/u58HC4xOptlM7+B/594ZI9drYwy5m+ZxHwlQUYCva4\n34dvwsfOGxkQyIrzXoep80EnWnFpYCLMcCiz+sEhPYxqLgNE+Cmn/6pv7SIscz6p\neVlQXIchdw+J4yl07paJDkFc6CNTCmaIHQIDAQAB\n-----END RSA PUBLIC KEY-----\n\n"},"summary":"Main profile","type":"Person","url":"https://mobilizon.org/@tcit"}
\ No newline at end of file diff --git a/test/moderation_log_test.exs b/test/moderation_log_test.exs index 4240f6a65..f2168b735 100644 --- a/test/moderation_log_test.exs +++ b/test/moderation_log_test.exs @@ -214,7 +214,7 @@ defmodule Pleroma.ModerationLogTest do {:ok, _} = ModerationLog.insert_log(%{ actor: moderator, - action: "report_response", + action: "report_note", subject: report, text: "look at this" }) @@ -222,7 +222,7 @@ defmodule Pleroma.ModerationLogTest do log = Repo.one(ModerationLog) assert log.data["message"] == - "@#{moderator.nickname} responded with 'look at this' to report ##{report.id}" + "@#{moderator.nickname} added note 'look at this' to report ##{report.id}" end test "logging status sensitivity update", %{moderator: moderator} do diff --git a/test/notification_test.exs b/test/notification_test.exs index 80a69d4df..c9b352097 100644 --- a/test/notification_test.exs +++ b/test/notification_test.exs @@ -15,6 +15,18 @@ defmodule Pleroma.NotificationTest do alias Pleroma.Web.Streamer describe "create_notifications" do + test "creates a notification for an emoji reaction" do + user = insert(:user) + other_user = insert(:user) + + {:ok, activity} = CommonAPI.post(user, %{"status" => "yeah"}) + {:ok, activity, _object} = CommonAPI.react_with_emoji(activity.id, other_user, "☕") + + {:ok, [notification]} = Notification.create_notifications(activity) + + assert notification.user_id == user.id + end + test "notifies someone when they are directly addressed" do user = insert(:user) other_user = insert(:user) @@ -101,7 +113,7 @@ defmodule Pleroma.NotificationTest do assert Notification.create_notification(activity, user) end - test "it creates a notificatin for the user if the user mutes the activity author" do + test "it creates a notification for the user if the user mutes the activity author" do muter = insert(:user) muted = insert(:user) {:ok, _} = User.mute(muter, muted) @@ -139,7 +151,10 @@ defmodule Pleroma.NotificationTest do test "it disables notifications from followers" do follower = insert(:user) - followed = insert(:user, notification_settings: %{"followers" => false}) + + followed = + insert(:user, notification_settings: %Pleroma.User.NotificationSetting{followers: false}) + User.follow(follower, followed) {:ok, activity} = CommonAPI.post(follower, %{"status" => "hey @#{followed.nickname}"}) refute Notification.create_notification(activity, followed) @@ -147,13 +162,20 @@ defmodule Pleroma.NotificationTest do test "it disables notifications from non-followers" do follower = insert(:user) - followed = insert(:user, notification_settings: %{"non_followers" => false}) + + followed = + insert(:user, + notification_settings: %Pleroma.User.NotificationSetting{non_followers: false} + ) + {:ok, activity} = CommonAPI.post(follower, %{"status" => "hey @#{followed.nickname}"}) refute Notification.create_notification(activity, followed) end test "it disables notifications from people the user follows" do - follower = insert(:user, notification_settings: %{"follows" => false}) + follower = + insert(:user, notification_settings: %Pleroma.User.NotificationSetting{follows: false}) + followed = insert(:user) User.follow(follower, followed) follower = Repo.get(User, follower.id) @@ -162,7 +184,9 @@ defmodule Pleroma.NotificationTest do end test "it disables notifications from people the user does not follow" do - follower = insert(:user, notification_settings: %{"non_follows" => false}) + follower = + insert(:user, notification_settings: %Pleroma.User.NotificationSetting{non_follows: false}) + followed = insert(:user) {:ok, activity} = CommonAPI.post(followed, %{"status" => "hey @#{follower.nickname}"}) refute Notification.create_notification(activity, follower) @@ -743,7 +767,7 @@ defmodule Pleroma.NotificationTest do {:ok, _activity} = CommonAPI.post(blocked, %{"status" => "hey @#{user.nickname}"}) - assert length(Notification.for_user(user, %{with_muted: true})) == 0 + assert Enum.empty?(Notification.for_user(user, %{with_muted: true})) end test "it doesn't return notifications from a domain-blocked user when with_muted is set" do @@ -753,7 +777,7 @@ defmodule Pleroma.NotificationTest do {:ok, _activity} = CommonAPI.post(blocked, %{"status" => "hey @#{user.nickname}"}) - assert length(Notification.for_user(user, %{with_muted: true})) == 0 + assert Enum.empty?(Notification.for_user(user, %{with_muted: true})) end test "it returns notifications from muted threads when with_muted is set" do diff --git a/test/object/fetcher_test.exs b/test/object/fetcher_test.exs index 9ae6b015d..2aad7a588 100644 --- a/test/object/fetcher_test.exs +++ b/test/object/fetcher_test.exs @@ -77,6 +77,15 @@ defmodule Pleroma.Object.FetcherTest do assert object end + test "it can fetch Mobilizon events" do + {:ok, object} = + Fetcher.fetch_object_from_id( + "https://mobilizon.org/events/252d5816-00a3-4a89-a66f-15bf65c33e39" + ) + + assert object + end + test "it can fetch wedistribute articles" do {:ok, object} = Fetcher.fetch_object_from_id("https://wedistribute.org/wp-json/pterotype/v1/object/85810") diff --git a/test/object_test.exs b/test/object_test.exs index 9247a6d84..9b4e6f0bf 100644 --- a/test/object_test.exs +++ b/test/object_test.exs @@ -4,12 +4,14 @@ defmodule Pleroma.ObjectTest do use Pleroma.DataCase + use Oban.Testing, repo: Pleroma.Repo import ExUnit.CaptureLog import Pleroma.Factory import Tesla.Mock alias Pleroma.Activity alias Pleroma.Object alias Pleroma.Repo + alias Pleroma.Tests.ObanHelpers alias Pleroma.Web.CommonAPI setup do @@ -71,6 +73,112 @@ defmodule Pleroma.ObjectTest do end end + describe "delete attachments" do + clear_config([Pleroma.Upload]) + + test "in subdirectories" do + Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) + + file = %Plug.Upload{ + content_type: "image/jpg", + path: Path.absname("test/fixtures/image.jpg"), + filename: "an_image.jpg" + } + + user = insert(:user) + + {:ok, %Object{} = attachment} = + Pleroma.Web.ActivityPub.ActivityPub.upload(file, actor: user.ap_id) + + %{data: %{"attachment" => [%{"url" => [%{"href" => href}]}]}} = + note = insert(:note, %{user: user, data: %{"attachment" => [attachment.data]}}) + + uploads_dir = Pleroma.Config.get!([Pleroma.Uploaders.Local, :uploads]) + + path = href |> Path.dirname() |> Path.basename() + + assert {:ok, ["an_image.jpg"]} == File.ls("#{uploads_dir}/#{path}") + + Object.delete(note) + + ObanHelpers.perform(all_enqueued(worker: Pleroma.Workers.AttachmentsCleanupWorker)) + + assert Object.get_by_id(attachment.id) == nil + + assert {:ok, []} == File.ls("#{uploads_dir}/#{path}") + end + + test "with dedupe enabled" do + Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) + Pleroma.Config.put([Pleroma.Upload, :filters], [Pleroma.Upload.Filter.Dedupe]) + + uploads_dir = Pleroma.Config.get!([Pleroma.Uploaders.Local, :uploads]) + + File.mkdir_p!(uploads_dir) + + file = %Plug.Upload{ + content_type: "image/jpg", + path: Path.absname("test/fixtures/image.jpg"), + filename: "an_image.jpg" + } + + user = insert(:user) + + {:ok, %Object{} = attachment} = + Pleroma.Web.ActivityPub.ActivityPub.upload(file, actor: user.ap_id) + + %{data: %{"attachment" => [%{"url" => [%{"href" => href}]}]}} = + note = insert(:note, %{user: user, data: %{"attachment" => [attachment.data]}}) + + filename = Path.basename(href) + + assert {:ok, files} = File.ls(uploads_dir) + assert filename in files + + Object.delete(note) + + ObanHelpers.perform(all_enqueued(worker: Pleroma.Workers.AttachmentsCleanupWorker)) + + assert Object.get_by_id(attachment.id) == nil + assert {:ok, files} = File.ls(uploads_dir) + refute filename in files + end + + test "with objects that have legacy data.url attribute" do + Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) + + file = %Plug.Upload{ + content_type: "image/jpg", + path: Path.absname("test/fixtures/image.jpg"), + filename: "an_image.jpg" + } + + user = insert(:user) + + {:ok, %Object{} = attachment} = + Pleroma.Web.ActivityPub.ActivityPub.upload(file, actor: user.ap_id) + + {:ok, %Object{}} = Object.create(%{url: "https://google.com", actor: user.ap_id}) + + %{data: %{"attachment" => [%{"url" => [%{"href" => href}]}]}} = + note = insert(:note, %{user: user, data: %{"attachment" => [attachment.data]}}) + + uploads_dir = Pleroma.Config.get!([Pleroma.Uploaders.Local, :uploads]) + + path = href |> Path.dirname() |> Path.basename() + + assert {:ok, ["an_image.jpg"]} == File.ls("#{uploads_dir}/#{path}") + + Object.delete(note) + + ObanHelpers.perform(all_enqueued(worker: Pleroma.Workers.AttachmentsCleanupWorker)) + + assert Object.get_by_id(attachment.id) == nil + + assert {:ok, []} == File.ls("#{uploads_dir}/#{path}") + end + end + describe "normalizer" do test "fetches unknown objects by default" do %Object{} = diff --git a/test/plugs/oauth_scopes_plug_test.exs b/test/plugs/oauth_scopes_plug_test.exs index be6d1340b..ce426677b 100644 --- a/test/plugs/oauth_scopes_plug_test.exs +++ b/test/plugs/oauth_scopes_plug_test.exs @@ -16,34 +16,6 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do :ok end - describe "when `assigns[:token]` is nil, " do - test "with :skip_instance_privacy_check option, proceeds with no op", %{conn: conn} do - conn = - conn - |> assign(:user, insert(:user)) - |> OAuthScopesPlug.call(%{scopes: ["read"], skip_instance_privacy_check: true}) - - refute conn.halted - assert conn.assigns[:user] - - refute called(EnsurePublicOrAuthenticatedPlug.call(conn, :_)) - end - - test "without :skip_instance_privacy_check option, calls EnsurePublicOrAuthenticatedPlug", %{ - conn: conn - } do - conn = - conn - |> assign(:user, insert(:user)) - |> OAuthScopesPlug.call(%{scopes: ["read"]}) - - refute conn.halted - assert conn.assigns[:user] - - assert called(EnsurePublicOrAuthenticatedPlug.call(conn, :_)) - end - end - test "if `token.scopes` fulfills specified 'any of' conditions, " <> "proceeds with no op", %{conn: conn} do @@ -75,64 +47,56 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do end describe "with `fallback: :proceed_unauthenticated` option, " do - test "if `token.scopes` doesn't fulfill specified 'any of' conditions, " <> - "clears `assigns[:user]` and calls EnsurePublicOrAuthenticatedPlug", + test "if `token.scopes` doesn't fulfill specified conditions, " <> + "clears :user and :token assigns and calls EnsurePublicOrAuthenticatedPlug", %{conn: conn} do - token = insert(:oauth_token, scopes: ["read", "write"]) |> Repo.preload(:user) - - conn = - conn - |> assign(:user, token.user) - |> assign(:token, token) - |> OAuthScopesPlug.call(%{scopes: ["follow"], fallback: :proceed_unauthenticated}) - - refute conn.halted - refute conn.assigns[:user] - - assert called(EnsurePublicOrAuthenticatedPlug.call(conn, :_)) - end - - test "if `token.scopes` doesn't fulfill specified 'all of' conditions, " <> - "clears `assigns[:user] and calls EnsurePublicOrAuthenticatedPlug", - %{conn: conn} do - token = insert(:oauth_token, scopes: ["read", "write"]) |> Repo.preload(:user) - - conn = - conn - |> assign(:user, token.user) - |> assign(:token, token) - |> OAuthScopesPlug.call(%{ - scopes: ["read", "follow"], - op: :&, - fallback: :proceed_unauthenticated - }) - - refute conn.halted - refute conn.assigns[:user] - - assert called(EnsurePublicOrAuthenticatedPlug.call(conn, :_)) + user = insert(:user) + token1 = insert(:oauth_token, scopes: ["read", "write"], user: user) + + for token <- [token1, nil], op <- [:|, :&] do + ret_conn = + conn + |> assign(:user, user) + |> assign(:token, token) + |> OAuthScopesPlug.call(%{ + scopes: ["follow"], + op: op, + fallback: :proceed_unauthenticated + }) + + refute ret_conn.halted + refute ret_conn.assigns[:user] + refute ret_conn.assigns[:token] + + assert called(EnsurePublicOrAuthenticatedPlug.call(ret_conn, :_)) + end end test "with :skip_instance_privacy_check option, " <> "if `token.scopes` doesn't fulfill specified conditions, " <> - "clears `assigns[:user]` and does not call EnsurePublicOrAuthenticatedPlug", + "clears :user and :token assigns and does NOT call EnsurePublicOrAuthenticatedPlug", %{conn: conn} do - token = insert(:oauth_token, scopes: ["read:statuses", "write"]) |> Repo.preload(:user) - - conn = - conn - |> assign(:user, token.user) - |> assign(:token, token) - |> OAuthScopesPlug.call(%{ - scopes: ["read"], - fallback: :proceed_unauthenticated, - skip_instance_privacy_check: true - }) - - refute conn.halted - refute conn.assigns[:user] - - refute called(EnsurePublicOrAuthenticatedPlug.call(conn, :_)) + user = insert(:user) + token1 = insert(:oauth_token, scopes: ["read:statuses", "write"], user: user) + + for token <- [token1, nil], op <- [:|, :&] do + ret_conn = + conn + |> assign(:user, user) + |> assign(:token, token) + |> OAuthScopesPlug.call(%{ + scopes: ["read"], + op: op, + fallback: :proceed_unauthenticated, + skip_instance_privacy_check: true + }) + + refute ret_conn.halted + refute ret_conn.assigns[:user] + refute ret_conn.assigns[:token] + + refute called(EnsurePublicOrAuthenticatedPlug.call(ret_conn, :_)) + end end end @@ -140,39 +104,42 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do test "if `token.scopes` does not fulfill specified 'any of' conditions, " <> "returns 403 and halts", %{conn: conn} do - token = insert(:oauth_token, scopes: ["read", "write"]) - any_of_scopes = ["follow"] + for token <- [insert(:oauth_token, scopes: ["read", "write"]), nil] do + any_of_scopes = ["follow", "push"] - conn = - conn - |> assign(:token, token) - |> OAuthScopesPlug.call(%{scopes: any_of_scopes}) + ret_conn = + conn + |> assign(:token, token) + |> OAuthScopesPlug.call(%{scopes: any_of_scopes}) - assert conn.halted - assert 403 == conn.status + assert ret_conn.halted + assert 403 == ret_conn.status - expected_error = "Insufficient permissions: #{Enum.join(any_of_scopes, ", ")}." - assert Jason.encode!(%{error: expected_error}) == conn.resp_body + expected_error = "Insufficient permissions: #{Enum.join(any_of_scopes, " | ")}." + assert Jason.encode!(%{error: expected_error}) == ret_conn.resp_body + end end test "if `token.scopes` does not fulfill specified 'all of' conditions, " <> "returns 403 and halts", %{conn: conn} do - token = insert(:oauth_token, scopes: ["read", "write"]) - all_of_scopes = ["write", "follow"] + for token <- [insert(:oauth_token, scopes: ["read", "write"]), nil] do + token_scopes = (token && token.scopes) || [] + all_of_scopes = ["write", "follow"] - conn = - conn - |> assign(:token, token) - |> OAuthScopesPlug.call(%{scopes: all_of_scopes, op: :&}) + conn = + conn + |> assign(:token, token) + |> OAuthScopesPlug.call(%{scopes: all_of_scopes, op: :&}) - assert conn.halted - assert 403 == conn.status + assert conn.halted + assert 403 == conn.status - expected_error = - "Insufficient permissions: #{Enum.join(all_of_scopes -- token.scopes, ", ")}." + expected_error = + "Insufficient permissions: #{Enum.join(all_of_scopes -- token_scopes, " & ")}." - assert Jason.encode!(%{error: expected_error}) == conn.resp_body + assert Jason.encode!(%{error: expected_error}) == conn.resp_body + end end end @@ -224,4 +191,42 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do assert f.(["admin:read"], ["write", "admin"]) == ["admin:read"] end end + + describe "transform_scopes/2" do + clear_config([:auth, :enforce_oauth_admin_scope_usage]) + + setup do + {:ok, %{f: &OAuthScopesPlug.transform_scopes/2}} + end + + test "with :admin option, prefixes all requested scopes with `admin:` " <> + "and [optionally] keeps only prefixed scopes, " <> + "depending on `[:auth, :enforce_oauth_admin_scope_usage]` setting", + %{f: f} do + Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], false) + + assert f.(["read"], %{admin: true}) == ["admin:read", "read"] + + assert f.(["read", "write"], %{admin: true}) == [ + "admin:read", + "read", + "admin:write", + "write" + ] + + Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], true) + + assert f.(["read:accounts"], %{admin: true}) == ["admin:read:accounts"] + + assert f.(["read", "write:reports"], %{admin: true}) == [ + "admin:read", + "admin:write:reports" + ] + end + + test "with no supported options, returns unmodified scopes", %{f: f} do + assert f.(["read"], %{}) == ["read"] + assert f.(["read", "write"], %{}) == ["read", "write"] + end + end end diff --git a/test/plugs/rate_limiter_test.exs b/test/plugs/rate_limiter_test.exs index 49f63c424..78f1ea9e4 100644 --- a/test/plugs/rate_limiter_test.exs +++ b/test/plugs/rate_limiter_test.exs @@ -145,9 +145,9 @@ defmodule Pleroma.Plugs.RateLimiterTest do test "can have limits seperate from unauthenticated connections" do limiter_name = :test_authenticated - scale = 1000 + scale = 50 limit = 5 - Pleroma.Config.put([:rate_limit, limiter_name], [{1, 10}, {scale, limit}]) + Pleroma.Config.put([:rate_limit, limiter_name], [{1000, 1}, {scale, limit}]) opts = RateLimiter.init(name: limiter_name) @@ -164,16 +164,6 @@ defmodule Pleroma.Plugs.RateLimiterTest do assert %{"error" => "Throttled"} = Phoenix.ConnTest.json_response(conn, :too_many_requests) assert conn.halted - - Process.sleep(1550) - - conn = conn(:get, "/") |> assign(:user, user) - conn = RateLimiter.call(conn, opts) - assert {1, 4} = RateLimiter.inspect_bucket(conn, limiter_name, opts) - - refute conn.status == Plug.Conn.Status.code(:too_many_requests) - refute conn.resp_body - refute conn.halted end test "diffrerent users are counted independently" do diff --git a/test/plugs/user_is_admin_plug_test.exs b/test/plugs/user_is_admin_plug_test.exs index 136dcc54e..bc6fcd73c 100644 --- a/test/plugs/user_is_admin_plug_test.exs +++ b/test/plugs/user_is_admin_plug_test.exs @@ -8,36 +8,116 @@ defmodule Pleroma.Plugs.UserIsAdminPlugTest do alias Pleroma.Plugs.UserIsAdminPlug import Pleroma.Factory - test "accepts a user that is admin" do - user = insert(:user, is_admin: true) + describe "unless [:auth, :enforce_oauth_admin_scope_usage]," do + clear_config([:auth, :enforce_oauth_admin_scope_usage]) do + Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], false) + end - conn = - build_conn() - |> assign(:user, user) + test "accepts a user that is an admin" do + user = insert(:user, is_admin: true) - ret_conn = - conn - |> UserIsAdminPlug.call(%{}) + conn = assign(build_conn(), :user, user) - assert conn == ret_conn - end + ret_conn = UserIsAdminPlug.call(conn, %{}) + + assert conn == ret_conn + end + + test "denies a user that isn't an admin" do + user = insert(:user) - test "denies a user that isn't admin" do - user = insert(:user) + conn = + build_conn() + |> assign(:user, user) + |> UserIsAdminPlug.call(%{}) - conn = - build_conn() - |> assign(:user, user) - |> UserIsAdminPlug.call(%{}) + assert conn.status == 403 + end - assert conn.status == 403 + test "denies when a user isn't set" do + conn = UserIsAdminPlug.call(build_conn(), %{}) + + assert conn.status == 403 + end end - test "denies when a user isn't set" do - conn = - build_conn() - |> UserIsAdminPlug.call(%{}) + describe "with [:auth, :enforce_oauth_admin_scope_usage]," do + clear_config([:auth, :enforce_oauth_admin_scope_usage]) do + Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], true) + end + + setup do + admin_user = insert(:user, is_admin: true) + non_admin_user = insert(:user, is_admin: false) + blank_user = nil + + {:ok, %{users: [admin_user, non_admin_user, blank_user]}} + end + + test "if token has any of admin scopes, accepts a user that is an admin", %{conn: conn} do + user = insert(:user, is_admin: true) + token = insert(:oauth_token, user: user, scopes: ["admin:something"]) + + conn = + conn + |> assign(:user, user) + |> assign(:token, token) + + ret_conn = UserIsAdminPlug.call(conn, %{}) + + assert conn == ret_conn + end + + test "if token has any of admin scopes, denies a user that isn't an admin", %{conn: conn} do + user = insert(:user, is_admin: false) + token = insert(:oauth_token, user: user, scopes: ["admin:something"]) + + conn = + conn + |> assign(:user, user) + |> assign(:token, token) + |> UserIsAdminPlug.call(%{}) + + assert conn.status == 403 + end + + test "if token has any of admin scopes, denies when a user isn't set", %{conn: conn} do + token = insert(:oauth_token, scopes: ["admin:something"]) + + conn = + conn + |> assign(:user, nil) + |> assign(:token, token) + |> UserIsAdminPlug.call(%{}) + + assert conn.status == 403 + end + + test "if token lacks admin scopes, denies users regardless of is_admin flag", + %{users: users} do + for user <- users do + token = insert(:oauth_token, user: user) + + conn = + build_conn() + |> assign(:user, user) + |> assign(:token, token) + |> UserIsAdminPlug.call(%{}) + + assert conn.status == 403 + end + end + + test "if token is missing, denies users regardless of is_admin flag", %{users: users} do + for user <- users do + conn = + build_conn() + |> assign(:user, user) + |> assign(:token, nil) + |> UserIsAdminPlug.call(%{}) - assert conn.status == 403 + assert conn.status == 403 + end + end end end diff --git a/test/repo_test.exs b/test/repo_test.exs index 85b64d4d1..5526b0327 100644 --- a/test/repo_test.exs +++ b/test/repo_test.exs @@ -4,7 +4,10 @@ defmodule Pleroma.RepoTest do use Pleroma.DataCase + import ExUnit.CaptureLog import Pleroma.Factory + import Mock + alias Pleroma.User describe "find_resource/1" do @@ -46,4 +49,44 @@ defmodule Pleroma.RepoTest do assert Repo.get_assoc(token, :user) == {:error, :not_found} end end + + describe "check_migrations_applied!" do + setup_with_mocks([ + {Ecto.Migrator, [], + [ + with_repo: fn repo, fun -> passthrough([repo, fun]) end, + migrations: fn Pleroma.Repo -> + [ + {:up, 20_191_128_153_944, "fix_missing_following_count"}, + {:up, 20_191_203_043_610, "create_report_notes"}, + {:down, 20_191_220_174_645, "add_scopes_to_pleroma_feo_auth_records"} + ] + end + ]} + ]) do + :ok + end + + test "raises if it detects unapplied migrations" do + assert_raise Pleroma.Repo.UnappliedMigrationsError, fn -> + capture_log(&Repo.check_migrations_applied!/0) + end + end + + test "doesn't do anything if disabled" do + disable_migration_check = + Pleroma.Config.get([:i_am_aware_this_may_cause_data_loss, :disable_migration_check]) + + Pleroma.Config.put([:i_am_aware_this_may_cause_data_loss, :disable_migration_check], true) + + on_exit(fn -> + Pleroma.Config.put( + [:i_am_aware_this_may_cause_data_loss, :disable_migration_check], + disable_migration_check + ) + end) + + assert :ok == Repo.check_migrations_applied!() + end + end end diff --git a/test/runtime_test.exs b/test/runtime_test.exs new file mode 100644 index 000000000..f7b6f23d4 --- /dev/null +++ b/test/runtime_test.exs @@ -0,0 +1,11 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.RuntimeTest do + use ExUnit.Case, async: true + + test "it loads custom runtime modules" do + assert Code.ensure_compiled?(RuntimeModule) + end +end diff --git a/test/support/builders/user_builder.ex b/test/support/builders/user_builder.ex index 6da16f71a..fcfea666f 100644 --- a/test/support/builders/user_builder.ex +++ b/test/support/builders/user_builder.ex @@ -10,7 +10,8 @@ defmodule Pleroma.Builders.UserBuilder do password_hash: Comeonin.Pbkdf2.hashpwsalt("test"), bio: "A tester.", ap_id: "some id", - last_digest_emailed_at: NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second) + last_digest_emailed_at: NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second), + notification_settings: %Pleroma.User.NotificationSetting{} } Map.merge(user, data) diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex index 9897f72ce..22e72fc09 100644 --- a/test/support/conn_case.ex +++ b/test/support/conn_case.ex @@ -28,6 +28,26 @@ defmodule Pleroma.Web.ConnCase do # The default endpoint for testing @endpoint Pleroma.Web.Endpoint + + # Sets up OAuth access with specified scopes + defp oauth_access(scopes, opts \\ []) do + user = + Keyword.get_lazy(opts, :user, fn -> + Pleroma.Factory.insert(:user) + end) + + token = + Keyword.get_lazy(opts, :oauth_token, fn -> + Pleroma.Factory.insert(:oauth_token, user: user, scopes: scopes) + end) + + conn = + build_conn() + |> assign(:user, user) + |> assign(:token, token) + + %{user: user, token: token, conn: conn} + end end end diff --git a/test/support/factory.ex b/test/support/factory.ex index 35ba523a1..780235cb9 100644 --- a/test/support/factory.ex +++ b/test/support/factory.ex @@ -31,7 +31,8 @@ defmodule Pleroma.Factory do nickname: sequence(:nickname, &"nick#{&1}"), password_hash: Comeonin.Pbkdf2.hashpwsalt("test"), bio: sequence(:bio, &"Tester Number #{&1}"), - last_digest_emailed_at: NaiveDateTime.utc_now() + last_digest_emailed_at: NaiveDateTime.utc_now(), + notification_settings: %Pleroma.User.NotificationSetting{} } %{ @@ -295,7 +296,7 @@ defmodule Pleroma.Factory do %Pleroma.Web.OAuth.App{ client_name: "Some client", redirect_uris: "https://example.com/callback", - scopes: ["read", "write", "follow", "push"], + scopes: ["read", "write", "follow", "push", "admin"], website: "https://example.com", client_id: Ecto.UUID.generate(), client_secret: "aaa;/&bbb" @@ -309,19 +310,37 @@ defmodule Pleroma.Factory do } end - def oauth_token_factory do - oauth_app = insert(:oauth_app) + def oauth_token_factory(attrs \\ %{}) do + scopes = Map.get(attrs, :scopes, ["read"]) + oauth_app = Map.get_lazy(attrs, :app, fn -> insert(:oauth_app, scopes: scopes) end) + user = Map.get_lazy(attrs, :user, fn -> build(:user) end) + + valid_until = + Map.get(attrs, :valid_until, NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)) %Pleroma.Web.OAuth.Token{ token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(), - scopes: ["read"], refresh_token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(), - user: build(:user), - app_id: oauth_app.id, - valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10) + scopes: scopes, + user: user, + app: oauth_app, + valid_until: valid_until } end + def oauth_admin_token_factory(attrs \\ %{}) do + user = Map.get_lazy(attrs, :user, fn -> build(:user, is_admin: true) end) + + scopes = + attrs + |> Map.get(:scopes, ["admin"]) + |> Kernel.++(["admin"]) + |> Enum.uniq() + + attrs = Map.merge(attrs, %{user: user, scopes: scopes}) + oauth_token_factory(attrs) + end + def oauth_authorization_factory do %Pleroma.Web.OAuth.Authorization{ token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false), @@ -375,9 +394,15 @@ defmodule Pleroma.Factory do end def config_factory do - %Pleroma.Web.AdminAPI.Config{ - key: sequence(:key, &"some_key_#{&1}"), - group: "pleroma", + %Pleroma.ConfigDB{ + key: + sequence(:key, fn key -> + # Atom dynamic registration hack in tests + "some_key_#{key}" + |> String.to_atom() + |> inspect() + end), + group: ":pleroma", value: sequence( :value, diff --git a/test/support/helpers.ex b/test/support/helpers.ex index af2b2eddf..9f817622d 100644 --- a/test/support/helpers.ex +++ b/test/support/helpers.ex @@ -6,6 +6,7 @@ defmodule Pleroma.Tests.Helpers do @moduledoc """ Helpers for use in tests. """ + alias Pleroma.Config defmacro clear_config(config_path) do quote do @@ -17,9 +18,9 @@ defmodule Pleroma.Tests.Helpers do defmacro clear_config(config_path, do: yield) do quote do setup do - initial_setting = Pleroma.Config.get(unquote(config_path)) + initial_setting = Config.get(unquote(config_path)) unquote(yield) - on_exit(fn -> Pleroma.Config.put(unquote(config_path), initial_setting) end) + on_exit(fn -> Config.put(unquote(config_path), initial_setting) end) :ok end end @@ -35,9 +36,9 @@ defmodule Pleroma.Tests.Helpers do defmacro clear_config_all(config_path, do: yield) do quote do setup_all do - initial_setting = Pleroma.Config.get(unquote(config_path)) + initial_setting = Config.get(unquote(config_path)) unquote(yield) - on_exit(fn -> Pleroma.Config.put(unquote(config_path), initial_setting) end) + on_exit(fn -> Config.put(unquote(config_path), initial_setting) end) :ok end end @@ -94,10 +95,10 @@ defmodule Pleroma.Tests.Helpers do defmacro guards_config(config_path) do quote do - initial_setting = Pleroma.Config.get(config_path) + initial_setting = Config.get(config_path) - Pleroma.Config.put(config_path, true) - on_exit(fn -> Pleroma.Config.put(config_path, initial_setting) end) + Config.put(config_path, true) + on_exit(fn -> Config.put(config_path, initial_setting) end) end end end diff --git a/test/support/http_request_mock.ex b/test/support/http_request_mock.ex index e3a621f49..f43de700d 100644 --- a/test/support/http_request_mock.ex +++ b/test/support/http_request_mock.ex @@ -308,6 +308,24 @@ defmodule HttpRequestMock do }} end + def get("https://mobilizon.org/events/252d5816-00a3-4a89-a66f-15bf65c33e39", _, _, + Accept: "application/activity+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/tesla_mock/mobilizon.org-event.json") + }} + end + + def get("https://mobilizon.org/@tcit", _, _, Accept: "application/activity+json") do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/tesla_mock/mobilizon.org-user.json") + }} + end + def get("https://baptiste.gelez.xyz/@/BaptisteGelez", _, _, _) do {:ok, %Tesla.Env{ diff --git a/test/tasks/config_test.exs b/test/tasks/config_test.exs index 9cd47380c..d79d34276 100644 --- a/test/tasks/config_test.exs +++ b/test/tasks/config_test.exs @@ -4,63 +4,193 @@ defmodule Mix.Tasks.Pleroma.ConfigTest do use Pleroma.DataCase + + alias Pleroma.ConfigDB alias Pleroma.Repo - alias Pleroma.Web.AdminAPI.Config setup_all do Mix.shell(Mix.Shell.Process) - temp_file = "config/temp.exported_from_db.secret.exs" on_exit(fn -> Mix.shell(Mix.Shell.IO) Application.delete_env(:pleroma, :first_setting) Application.delete_env(:pleroma, :second_setting) - :ok = File.rm(temp_file) end) - {:ok, temp_file: temp_file} + :ok end - clear_config_all([:instance, :dynamic_configuration]) do - Pleroma.Config.put([:instance, :dynamic_configuration], true) + clear_config_all(:configurable_from_database) do + Pleroma.Config.put(:configurable_from_database, true) end - test "settings are migrated to db" do - assert Repo.all(Config) == [] + test "error if file with custom settings doesn't exist" do + Mix.Tasks.Pleroma.Config.migrate_to_db("config/not_existance_config_file.exs") + + assert_receive {:mix_shell, :info, + [ + "To migrate settings, you must define custom settings in config/not_existance_config_file.exs." + ]}, + 15 + end + + describe "migrate_to_db/1" do + setup do + initial = Application.get_env(:quack, :level) + on_exit(fn -> Application.put_env(:quack, :level, initial) end) + end + + test "settings are migrated to db" do + assert Repo.all(ConfigDB) == [] - Application.put_env(:pleroma, :first_setting, key: "value", key2: [Pleroma.Repo]) - Application.put_env(:pleroma, :second_setting, key: "value2", key2: [Pleroma.Activity]) + Mix.Tasks.Pleroma.Config.migrate_to_db("test/fixtures/config/temp.secret.exs") - Mix.Tasks.Pleroma.Config.run(["migrate_to_db"]) + config1 = ConfigDB.get_by_params(%{group: ":pleroma", key: ":first_setting"}) + config2 = ConfigDB.get_by_params(%{group: ":pleroma", key: ":second_setting"}) + config3 = ConfigDB.get_by_params(%{group: ":quack", key: ":level"}) + refute ConfigDB.get_by_params(%{group: ":pleroma", key: "Pleroma.Repo"}) - first_db = Config.get_by_params(%{group: "pleroma", key: ":first_setting"}) - second_db = Config.get_by_params(%{group: "pleroma", key: ":second_setting"}) - refute Config.get_by_params(%{group: "pleroma", key: "Pleroma.Repo"}) + assert ConfigDB.from_binary(config1.value) == [key: "value", key2: [Repo]] + assert ConfigDB.from_binary(config2.value) == [key: "value2", key2: ["Activity"]] + assert ConfigDB.from_binary(config3.value) == :info + end - assert Config.from_binary(first_db.value) == [key: "value", key2: [Pleroma.Repo]] - assert Config.from_binary(second_db.value) == [key: "value2", key2: [Pleroma.Activity]] + test "config table is truncated before migration" do + ConfigDB.create(%{ + group: ":pleroma", + key: ":first_setting", + value: [key: "value", key2: ["Activity"]] + }) + + assert Repo.aggregate(ConfigDB, :count, :id) == 1 + + Mix.Tasks.Pleroma.Config.migrate_to_db("test/fixtures/config/temp.secret.exs") + + config = ConfigDB.get_by_params(%{group: ":pleroma", key: ":first_setting"}) + assert ConfigDB.from_binary(config.value) == [key: "value", key2: [Repo]] + end end - test "settings are migrated to file and deleted from db", %{temp_file: temp_file} do - Config.create(%{ - group: "pleroma", - key: ":setting_first", - value: [key: "value", key2: [Pleroma.Activity]] - }) + describe "with deletion temp file" do + setup do + temp_file = "config/temp.exported_from_db.secret.exs" + + on_exit(fn -> + :ok = File.rm(temp_file) + end) + + {:ok, temp_file: temp_file} + end + + test "settings are migrated to file and deleted from db", %{temp_file: temp_file} do + ConfigDB.create(%{ + group: ":pleroma", + key: ":setting_first", + value: [key: "value", key2: ["Activity"]] + }) + + ConfigDB.create(%{ + group: ":pleroma", + key: ":setting_second", + value: [key: "value2", key2: [Repo]] + }) + + ConfigDB.create(%{group: ":quack", key: ":level", value: :info}) + + Mix.Tasks.Pleroma.Config.run(["migrate_from_db", "--env", "temp", "-d"]) + + assert Repo.all(ConfigDB) == [] + + file = File.read!(temp_file) + assert file =~ "config :pleroma, :setting_first," + assert file =~ "config :pleroma, :setting_second," + assert file =~ "config :quack, :level, :info" + end + + test "load a settings with large values and pass to file", %{temp_file: temp_file} do + ConfigDB.create(%{ + group: ":pleroma", + key: ":instance", + value: [ + name: "Pleroma", + email: "example@example.com", + notify_email: "noreply@example.com", + description: "A Pleroma instance, an alternative fediverse server", + limit: 5_000, + chat_limit: 5_000, + remote_limit: 100_000, + upload_limit: 16_000_000, + avatar_upload_limit: 2_000_000, + background_upload_limit: 4_000_000, + banner_upload_limit: 4_000_000, + poll_limits: %{ + max_options: 20, + max_option_chars: 200, + min_expiration: 0, + max_expiration: 365 * 24 * 60 * 60 + }, + registrations_open: true, + federating: true, + federation_incoming_replies_max_depth: 100, + federation_reachability_timeout_days: 7, + federation_publisher_modules: [Pleroma.Web.ActivityPub.Publisher], + allow_relay: true, + rewrite_policy: Pleroma.Web.ActivityPub.MRF.NoOpPolicy, + public: true, + quarantined_instances: [], + managed_config: true, + static_dir: "instance/static/", + allowed_post_formats: ["text/plain", "text/html", "text/markdown", "text/bbcode"], + mrf_transparency: true, + mrf_transparency_exclusions: [], + autofollowed_nicknames: [], + max_pinned_statuses: 1, + no_attachment_links: true, + welcome_user_nickname: nil, + welcome_message: nil, + max_report_comment_size: 1000, + safe_dm_mentions: false, + healthcheck: false, + remote_post_retention_days: 90, + skip_thread_containment: true, + limit_to_local_content: :unauthenticated, + user_bio_length: 5000, + user_name_length: 100, + max_account_fields: 10, + max_remote_account_fields: 20, + account_field_name_length: 512, + account_field_value_length: 2048, + external_user_synchronization: true, + extended_nickname_format: true, + multi_factor_authentication: [ + totp: [ + # digits 6 or 8 + digits: 6, + period: 30 + ], + backup_codes: [ + number: 2, + length: 6 + ] + ] + ] + }) - Config.create(%{ - group: "pleroma", - key: ":setting_second", - value: [key: "valu2", key2: [Pleroma.Repo]] - }) + Mix.Tasks.Pleroma.Config.run(["migrate_from_db", "--env", "temp", "-d"]) - Mix.Tasks.Pleroma.Config.run(["migrate_from_db", "temp", "true"]) + assert Repo.all(ConfigDB) == [] + assert File.exists?(temp_file) + {:ok, file} = File.read(temp_file) - assert Repo.all(Config) == [] - assert File.exists?(temp_file) - {:ok, file} = File.read(temp_file) + header = + if Code.ensure_loaded?(Config.Reader) do + "import Config" + else + "use Mix.Config" + end - assert file =~ "config :pleroma, :setting_first," - assert file =~ "config :pleroma, :setting_second," + assert file == + "#{header}\n\nconfig :pleroma, :instance,\n name: \"Pleroma\",\n email: \"example@example.com\",\n notify_email: \"noreply@example.com\",\n description: \"A Pleroma instance, an alternative fediverse server\",\n limit: 5000,\n chat_limit: 5000,\n remote_limit: 100_000,\n upload_limit: 16_000_000,\n avatar_upload_limit: 2_000_000,\n background_upload_limit: 4_000_000,\n banner_upload_limit: 4_000_000,\n poll_limits: %{\n max_expiration: 31_536_000,\n max_option_chars: 200,\n max_options: 20,\n min_expiration: 0\n },\n registrations_open: true,\n federating: true,\n federation_incoming_replies_max_depth: 100,\n federation_reachability_timeout_days: 7,\n federation_publisher_modules: [Pleroma.Web.ActivityPub.Publisher],\n allow_relay: true,\n rewrite_policy: Pleroma.Web.ActivityPub.MRF.NoOpPolicy,\n public: true,\n quarantined_instances: [],\n managed_config: true,\n static_dir: \"instance/static/\",\n allowed_post_formats: [\"text/plain\", \"text/html\", \"text/markdown\", \"text/bbcode\"],\n mrf_transparency: true,\n mrf_transparency_exclusions: [],\n autofollowed_nicknames: [],\n max_pinned_statuses: 1,\n no_attachment_links: true,\n welcome_user_nickname: nil,\n welcome_message: nil,\n max_report_comment_size: 1000,\n safe_dm_mentions: false,\n healthcheck: false,\n remote_post_retention_days: 90,\n skip_thread_containment: true,\n limit_to_local_content: :unauthenticated,\n user_bio_length: 5000,\n user_name_length: 100,\n max_account_fields: 10,\n max_remote_account_fields: 20,\n account_field_name_length: 512,\n account_field_value_length: 2048,\n external_user_synchronization: true,\n extended_nickname_format: true,\n multi_factor_authentication: [\n totp: [digits: 6, period: 30],\n backup_codes: [number: 2, length: 6]\n ]\n" + end end end diff --git a/test/tasks/instance_test.exs b/test/tasks/instance_test.exs index 6d7eed4c1..d69275726 100644 --- a/test/tasks/instance_test.exs +++ b/test/tasks/instance_test.exs @@ -78,7 +78,7 @@ defmodule Pleroma.InstanceTest do assert generated_config =~ "database: \"dbname\"" assert generated_config =~ "username: \"dbuser\"" assert generated_config =~ "password: \"dbpass\"" - assert generated_config =~ "dynamic_configuration: true" + assert generated_config =~ "configurable_from_database: true" assert generated_config =~ "http: [ip: {127, 0, 0, 1}, port: 4000]" assert File.read!(tmp_path() <> "setup.psql") == generated_setup_psql() end diff --git a/test/uploaders/local_test.exs b/test/uploaders/local_test.exs index fc442d0f1..1963dac23 100644 --- a/test/uploaders/local_test.exs +++ b/test/uploaders/local_test.exs @@ -29,4 +29,25 @@ defmodule Pleroma.Uploaders.LocalTest do |> File.exists?() end end + + describe "delete_file/1" do + test "deletes local file" do + file_path = "local_upload/files/image.jpg" + + file = %Pleroma.Upload{ + name: "image.jpg", + content_type: "image/jpg", + path: file_path, + tempfile: Path.absname("test/fixtures/image_tmp.jpg") + } + + :ok = Local.put_file(file) + local_path = Path.join([Local.upload_path(), file_path]) + assert File.exists?(local_path) + + Local.delete_file(file_path) + + refute File.exists?(local_path) + end + end end diff --git a/test/uploaders/mdii_test.exs b/test/uploaders/mdii_test.exs deleted file mode 100644 index d432d40f0..000000000 --- a/test/uploaders/mdii_test.exs +++ /dev/null @@ -1,50 +0,0 @@ -# Pleroma: A lightweight social networking server -# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> -# SPDX-License-Identifier: AGPL-3.0-only - -defmodule Pleroma.Uploaders.MDIITest do - use Pleroma.DataCase - alias Pleroma.Uploaders.MDII - import Tesla.Mock - - describe "get_file/1" do - test "it returns path to local folder for files" do - assert MDII.get_file("") == {:ok, {:static_dir, "test/uploads"}} - end - end - - describe "put_file/1" do - setup do - file_upload = %Pleroma.Upload{ - name: "mdii-image.jpg", - content_type: "image/jpg", - path: "test_folder/mdii-image.jpg", - tempfile: Path.absname("test/fixtures/image_tmp.jpg") - } - - [file_upload: file_upload] - end - - test "save file", %{file_upload: file_upload} do - mock(fn - %{method: :post, url: "https://mdii.sakura.ne.jp/mdii-post.cgi?jpg"} -> - %Tesla.Env{status: 200, body: "mdii-image"} - end) - - assert MDII.put_file(file_upload) == - {:ok, {:url, "https://mdii.sakura.ne.jp/mdii-image.jpg"}} - end - - test "save file to local if MDII isn`t available", %{file_upload: file_upload} do - mock(fn - %{method: :post, url: "https://mdii.sakura.ne.jp/mdii-post.cgi?jpg"} -> - %Tesla.Env{status: 500} - end) - - assert MDII.put_file(file_upload) == :ok - - assert Path.join([Pleroma.Uploaders.Local.upload_path(), file_upload.path]) - |> File.exists?() - end - end -end diff --git a/test/uploaders/s3_test.exs b/test/uploaders/s3_test.exs index 171316340..ab7795c3b 100644 --- a/test/uploaders/s3_test.exs +++ b/test/uploaders/s3_test.exs @@ -79,4 +79,11 @@ defmodule Pleroma.Uploaders.S3Test do end end end + + describe "delete_file/1" do + test_with_mock "deletes file", ExAws, request: fn _req -> {:ok, %{status_code: 204}} end do + assert :ok = S3.delete_file("image.jpg") + assert_called(ExAws.request(:_)) + end + end end diff --git a/test/user/notification_setting_test.exs b/test/user/notification_setting_test.exs new file mode 100644 index 000000000..4744d7b4a --- /dev/null +++ b/test/user/notification_setting_test.exs @@ -0,0 +1,21 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.User.NotificationSettingTest do + use Pleroma.DataCase + + alias Pleroma.User.NotificationSetting + + describe "changeset/2" do + test "sets valid privacy option" do + changeset = + NotificationSetting.changeset( + %NotificationSetting{}, + %{"privacy_option" => true} + ) + + assert %Ecto.Changeset{valid?: true} = changeset + end + end +end diff --git a/test/user_search_test.exs b/test/user_search_test.exs index 98841dbbd..821858476 100644 --- a/test/user_search_test.exs +++ b/test/user_search_test.exs @@ -174,6 +174,7 @@ defmodule Pleroma.UserSearchTest do |> Map.put(:search_rank, nil) |> Map.put(:search_type, nil) |> Map.put(:last_digest_emailed_at, nil) + |> Map.put(:notification_settings, nil) assert user == expected end diff --git a/test/user_test.exs b/test/user_test.exs index bfa8faafa..158f98e66 100644 --- a/test/user_test.exs +++ b/test/user_test.exs @@ -17,6 +17,7 @@ defmodule Pleroma.UserTest do import Mock import Pleroma.Factory + import ExUnit.CaptureLog setup_all do Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) @@ -26,6 +27,42 @@ defmodule Pleroma.UserTest do clear_config([:instance, :account_activation_required]) describe "service actors" do + test "returns updated invisible actor" do + uri = "#{Pleroma.Web.Endpoint.url()}/relay" + followers_uri = "#{uri}/followers" + + insert( + :user, + %{ + nickname: "relay", + invisible: false, + local: true, + ap_id: uri, + follower_address: followers_uri + } + ) + + actor = User.get_or_create_service_actor_by_ap_id(uri, "relay") + assert actor.invisible + end + + test "returns relay user" do + uri = "#{Pleroma.Web.Endpoint.url()}/relay" + followers_uri = "#{uri}/followers" + + assert %User{ + nickname: "relay", + invisible: true, + local: true, + ap_id: ^uri, + follower_address: ^followers_uri + } = User.get_or_create_service_actor_by_ap_id(uri, "relay") + + assert capture_log(fn -> + refute User.get_or_create_service_actor_by_ap_id("/relay", "relay") + end) =~ "Cannot create service actor:" + end + test "returns invisible actor" do uri = "#{Pleroma.Web.Endpoint.url()}/internal/fetch-test" followers_uri = "#{uri}/followers" @@ -914,6 +951,16 @@ defmodule Pleroma.UserTest do refute User.blocks?(user, collateral_user) end + + test "follows take precedence over domain blocks" do + user = insert(:user) + good_eggo = insert(:user, %{ap_id: "https://meanies.social/user/cuteposter"}) + + {:ok, user} = User.block_domain(user, "meanies.social") + {:ok, user} = User.follow(user, good_eggo) + + refute User.blocks?(user, good_eggo) + end end describe "blocks_import" do @@ -1239,23 +1286,35 @@ defmodule Pleroma.UserTest do end end - test "auth_active?/1 works correctly" do - Pleroma.Config.put([:instance, :account_activation_required], true) + describe "account_status/1" do + clear_config([:instance, :account_activation_required]) - local_user = insert(:user, local: true, confirmation_pending: true) - confirmed_user = insert(:user, local: true, confirmation_pending: false) - remote_user = insert(:user, local: false) + test "return confirmation_pending for unconfirm user" do + Pleroma.Config.put([:instance, :account_activation_required], true) + user = insert(:user, confirmation_pending: true) + assert User.account_status(user) == :confirmation_pending + end - refute User.auth_active?(local_user) - assert User.auth_active?(confirmed_user) - assert User.auth_active?(remote_user) + test "return active for confirmed user" do + Pleroma.Config.put([:instance, :account_activation_required], true) + user = insert(:user, confirmation_pending: false) + assert User.account_status(user) == :active + end - # also shows unactive for deactivated users + test "return active for remote user" do + user = insert(:user, local: false) + assert User.account_status(user) == :active + end - deactivated_but_confirmed = - insert(:user, local: true, confirmation_pending: false, deactivated: true) + test "returns :password_reset_pending for user with reset password" do + user = insert(:user, password_reset_pending: true) + assert User.account_status(user) == :password_reset_pending + end - refute User.auth_active?(deactivated_but_confirmed) + test "returns :deactivated for deactivated user" do + user = insert(:user, local: true, confirmation_pending: false, deactivated: true) + assert User.account_status(user) == :deactivated + end end describe "superuser?/1" do diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs index 97844a407..ff4604a52 100644 --- a/test/web/activity_pub/activity_pub_test.exs +++ b/test/web/activity_pub/activity_pub_test.exs @@ -608,6 +608,39 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do refute repeat_activity in activities end + test "does return activities from followed users on blocked domains" do + domain = "meanies.social" + domain_user = insert(:user, %{ap_id: "https://#{domain}/@pundit"}) + blocker = insert(:user) + + {:ok, blocker} = User.follow(blocker, domain_user) + {:ok, blocker} = User.block_domain(blocker, domain) + + assert User.following?(blocker, domain_user) + assert User.blocks_domain?(blocker, domain_user) + refute User.blocks?(blocker, domain_user) + + note = insert(:note, %{data: %{"actor" => domain_user.ap_id}}) + activity = insert(:note_activity, %{note: note}) + + activities = + ActivityPub.fetch_activities([], %{"blocking_user" => blocker, "skip_preload" => true}) + + assert activity in activities + + # And check that if the guy we DO follow boosts someone else from their domain, + # that should be hidden + another_user = insert(:user, %{ap_id: "https://#{domain}/@meanie2"}) + bad_note = insert(:note, %{data: %{"actor" => another_user.ap_id}}) + bad_activity = insert(:note_activity, %{note: bad_note}) + {:ok, repeat_activity, _} = CommonAPI.repeat(bad_activity.id, domain_user) + + activities = + ActivityPub.fetch_activities([], %{"blocking_user" => blocker, "skip_preload" => true}) + + refute repeat_activity in activities + end + test "doesn't return muted activities" do activity_one = insert(:note_activity) activity_two = insert(:note_activity) @@ -834,6 +867,8 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do test "adds an emoji reaction activity to the db" do user = insert(:user) reactor = insert(:user) + third_user = insert(:user) + fourth_user = insert(:user) {:ok, activity} = CommonAPI.post(user, %{"status" => "YASSSS queen slay"}) assert object = Object.normalize(activity) @@ -848,7 +883,21 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do assert reaction_activity.data["to"] == [User.ap_followers(reactor), activity.data["actor"]] assert reaction_activity.data["context"] == object.data["context"] assert object.data["reaction_count"] == 1 - assert object.data["reactions"]["🔥"] == [reactor.ap_id] + assert object.data["reactions"] == [["🔥", [reactor.ap_id]]] + + {:ok, _reaction_activity, object} = ActivityPub.react_with_emoji(third_user, object, "☕") + + assert object.data["reaction_count"] == 2 + assert object.data["reactions"] == [["🔥", [reactor.ap_id]], ["☕", [third_user.ap_id]]] + + {:ok, _reaction_activity, object} = ActivityPub.react_with_emoji(fourth_user, object, "🔥") + + assert object.data["reaction_count"] == 3 + + assert object.data["reactions"] == [ + ["🔥", [fourth_user.ap_id, reactor.ap_id]], + ["☕", [third_user.ap_id]] + ] end end @@ -886,7 +935,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do object = Object.get_by_ap_id(object.data["id"]) assert object.data["reaction_count"] == 0 - assert object.data["reactions"] == %{} + assert object.data["reactions"] == [] end end @@ -1590,6 +1639,73 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do assert follow_info.following_count == 32 assert follow_info.hide_follows == true end + + test "doesn't crash when follower and following counters are hidden" do + mock(fn env -> + case env.url do + "http://localhost:4001/users/masto_hidden_counters/following" -> + json(%{ + "@context" => "https://www.w3.org/ns/activitystreams", + "id" => "http://localhost:4001/users/masto_hidden_counters/followers" + }) + + "http://localhost:4001/users/masto_hidden_counters/following?page=1" -> + %Tesla.Env{status: 403, body: ""} + + "http://localhost:4001/users/masto_hidden_counters/followers" -> + json(%{ + "@context" => "https://www.w3.org/ns/activitystreams", + "id" => "http://localhost:4001/users/masto_hidden_counters/following" + }) + + "http://localhost:4001/users/masto_hidden_counters/followers?page=1" -> + %Tesla.Env{status: 403, body: ""} + end + end) + + user = + insert(:user, + local: false, + follower_address: "http://localhost:4001/users/masto_hidden_counters/followers", + following_address: "http://localhost:4001/users/masto_hidden_counters/following" + ) + + {:ok, follow_info} = ActivityPub.fetch_follow_information_for_user(user) + + assert follow_info.hide_followers == true + assert follow_info.follower_count == 0 + assert follow_info.hide_follows == true + assert follow_info.following_count == 0 + end + end + + describe "fetch_favourites/3" do + test "returns a favourite activities sorted by adds to favorite" do + user = insert(:user) + other_user = insert(:user) + user1 = insert(:user) + user2 = insert(:user) + {:ok, a1} = CommonAPI.post(user1, %{"status" => "bla"}) + {:ok, _a2} = CommonAPI.post(user2, %{"status" => "traps are happy"}) + {:ok, a3} = CommonAPI.post(user2, %{"status" => "Trees Are "}) + {:ok, a4} = CommonAPI.post(user2, %{"status" => "Agent Smith "}) + {:ok, a5} = CommonAPI.post(user1, %{"status" => "Red or Blue "}) + + {:ok, _, _} = CommonAPI.favorite(a4.id, user) + {:ok, _, _} = CommonAPI.favorite(a3.id, other_user) + {:ok, _, _} = CommonAPI.favorite(a3.id, user) + {:ok, _, _} = CommonAPI.favorite(a5.id, other_user) + {:ok, _, _} = CommonAPI.favorite(a5.id, user) + {:ok, _, _} = CommonAPI.favorite(a4.id, other_user) + {:ok, _, _} = CommonAPI.favorite(a1.id, user) + {:ok, _, _} = CommonAPI.favorite(a1.id, other_user) + result = ActivityPub.fetch_favourites(user) + + assert Enum.map(result, & &1.id) == [a1.id, a5.id, a3.id, a4.id] + + result = ActivityPub.fetch_favourites(user, %{"limit" => 2}) + assert Enum.map(result, & &1.id) == [a1.id, a5.id] + end end describe "Move activity" do diff --git a/test/web/activity_pub/publisher_test.exs b/test/web/activity_pub/publisher_test.exs index e885e5a5a..015af19ab 100644 --- a/test/web/activity_pub/publisher_test.exs +++ b/test/web/activity_pub/publisher_test.exs @@ -23,6 +23,27 @@ defmodule Pleroma.Web.ActivityPub.PublisherTest do :ok end + describe "gather_webfinger_links/1" do + test "it returns links" do + user = insert(:user) + + expected_links = [ + %{"href" => user.ap_id, "rel" => "self", "type" => "application/activity+json"}, + %{ + "href" => user.ap_id, + "rel" => "self", + "type" => "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"" + }, + %{ + "rel" => "http://ostatus.org/schema/1.0/subscribe", + "template" => "#{Pleroma.Web.base_url()}/ostatus_subscribe?acct={uri}" + } + ] + + assert expected_links == Publisher.gather_webfinger_links(user) + end + end + describe "determine_inbox/2" do test "it returns sharedInbox for messages involving as:Public in to" do user = diff --git a/test/web/activity_pub/transmogrifier/follow_handling_test.exs b/test/web/activity_pub/transmogrifier/follow_handling_test.exs index 7d6d0814d..1c88b05c2 100644 --- a/test/web/activity_pub/transmogrifier/follow_handling_test.exs +++ b/test/web/activity_pub/transmogrifier/follow_handling_test.exs @@ -78,7 +78,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.FollowHandlingTest do ) |> Repo.all() - assert length(accepts) == 0 + assert Enum.empty?(accepts) end test "it works for follow requests when you are already followed, creating a new accept activity" do diff --git a/test/web/activity_pub/utils_test.exs b/test/web/activity_pub/utils_test.exs index 586eb1d2f..211fa6c95 100644 --- a/test/web/activity_pub/utils_test.exs +++ b/test/web/activity_pub/utils_test.exs @@ -636,4 +636,17 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do assert updated_object.data["announcement_count"] == 1 end end + + describe "get_cached_emoji_reactions/1" do + test "returns the data or an emtpy list" do + object = insert(:note) + assert Utils.get_cached_emoji_reactions(object) == [] + + object = insert(:note, data: %{"reactions" => [["x", ["lain"]]]}) + assert Utils.get_cached_emoji_reactions(object) == [["x", ["lain"]]] + + object = insert(:note, data: %{"reactions" => %{}}) + assert Utils.get_cached_emoji_reactions(object) == [] + end + end end diff --git a/test/web/activity_pub/views/user_view_test.exs b/test/web/activity_pub/views/user_view_test.exs index 3299be2d5..8374b8d23 100644 --- a/test/web/activity_pub/views/user_view_test.exs +++ b/test/web/activity_pub/views/user_view_test.exs @@ -126,7 +126,7 @@ defmodule Pleroma.Web.ActivityPub.UserViewTest do {:ok, _other_user, user, _activity} = CommonAPI.follow(other_user, user) assert %{"totalItems" => 1} = UserView.render("followers.json", %{user: user}) user = Map.merge(user, %{hide_followers_count: true, hide_followers: true}) - assert %{"totalItems" => 0} = UserView.render("followers.json", %{user: user}) + refute UserView.render("followers.json", %{user: user}) |> Map.has_key?("totalItems") end test "sets correct totalItems when followers are hidden but the follower counter is not" do diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs index 4148f04bc..5c767219a 100644 --- a/test/web/admin_api/admin_api_controller_test.exs +++ b/test/web/admin_api/admin_api_controller_test.exs @@ -7,9 +7,11 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do use Oban.Testing, repo: Pleroma.Repo alias Pleroma.Activity + alias Pleroma.ConfigDB alias Pleroma.HTML alias Pleroma.ModerationLog alias Pleroma.Repo + alias Pleroma.ReportNote alias Pleroma.Tests.ObanHelpers alias Pleroma.User alias Pleroma.UserInviteToken @@ -25,14 +27,129 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do :ok end + setup do + admin = insert(:user, is_admin: true) + token = insert(:oauth_admin_token, user: admin) + + conn = + build_conn() + |> assign(:user, admin) + |> assign(:token, token) + + {:ok, %{admin: admin, token: token, conn: conn}} + end + + describe "with [:auth, :enforce_oauth_admin_scope_usage]," do + clear_config([:auth, :enforce_oauth_admin_scope_usage]) do + Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], true) + end + + test "GET /api/pleroma/admin/users/:nickname requires admin:read:accounts or broader scope", + %{admin: admin} do + user = insert(:user) + url = "/api/pleroma/admin/users/#{user.nickname}" + + good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"]) + good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"]) + good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"]) + + bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts"]) + bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"]) + bad_token3 = nil + + for good_token <- [good_token1, good_token2, good_token3] do + conn = + build_conn() + |> assign(:user, admin) + |> assign(:token, good_token) + |> get(url) + + assert json_response(conn, 200) + end + + for good_token <- [good_token1, good_token2, good_token3] do + conn = + build_conn() + |> assign(:user, nil) + |> assign(:token, good_token) + |> get(url) + + assert json_response(conn, :forbidden) + end + + for bad_token <- [bad_token1, bad_token2, bad_token3] do + conn = + build_conn() + |> assign(:user, admin) + |> assign(:token, bad_token) + |> get(url) + + assert json_response(conn, :forbidden) + end + end + end + + describe "unless [:auth, :enforce_oauth_admin_scope_usage]," do + clear_config([:auth, :enforce_oauth_admin_scope_usage]) do + Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], false) + end + + test "GET /api/pleroma/admin/users/:nickname requires " <> + "read:accounts or admin:read:accounts or broader scope", + %{admin: admin} do + user = insert(:user) + url = "/api/pleroma/admin/users/#{user.nickname}" + + good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"]) + good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"]) + good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"]) + good_token4 = insert(:oauth_token, user: admin, scopes: ["read:accounts"]) + good_token5 = insert(:oauth_token, user: admin, scopes: ["read"]) + + good_tokens = [good_token1, good_token2, good_token3, good_token4, good_token5] + + bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts:partial"]) + bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"]) + bad_token3 = nil + + for good_token <- good_tokens do + conn = + build_conn() + |> assign(:user, admin) + |> assign(:token, good_token) + |> get(url) + + assert json_response(conn, 200) + end + + for good_token <- good_tokens do + conn = + build_conn() + |> assign(:user, nil) + |> assign(:token, good_token) + |> get(url) + + assert json_response(conn, :forbidden) + end + + for bad_token <- [bad_token1, bad_token2, bad_token3] do + conn = + build_conn() + |> assign(:user, admin) + |> assign(:token, bad_token) + |> get(url) + + assert json_response(conn, :forbidden) + end + end + end + describe "DELETE /api/pleroma/admin/users" do - test "single user" do - admin = insert(:user, is_admin: true) + test "single user", %{admin: admin, conn: conn} do user = insert(:user) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> delete("/api/pleroma/admin/users?nickname=#{user.nickname}") @@ -44,14 +161,12 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do assert json_response(conn, 200) == user.nickname end - test "multiple users" do - admin = insert(:user, is_admin: true) + test "multiple users", %{admin: admin, conn: conn} do user_one = insert(:user) user_two = insert(:user) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> delete("/api/pleroma/admin/users", %{ nicknames: [user_one.nickname, user_two.nickname] @@ -68,12 +183,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "/api/pleroma/admin/users" do - test "Create" do - admin = insert(:user, is_admin: true) - + test "Create", %{conn: conn} do conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> post("/api/pleroma/admin/users", %{ "users" => [ @@ -98,13 +210,11 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do assert ["lain", "lain2"] -- Enum.map(log_entry.data["subjects"], & &1["nickname"]) == [] end - test "Cannot create user with exisiting email" do - admin = insert(:user, is_admin: true) + test "Cannot create user with existing email", %{conn: conn} do user = insert(:user) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> post("/api/pleroma/admin/users", %{ "users" => [ @@ -129,13 +239,11 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do ] end - test "Cannot create user with exisiting nickname" do - admin = insert(:user, is_admin: true) + test "Cannot create user with existing nickname", %{conn: conn} do user = insert(:user) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> post("/api/pleroma/admin/users", %{ "users" => [ @@ -160,13 +268,11 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do ] end - test "Multiple user creation works in transaction" do - admin = insert(:user, is_admin: true) + test "Multiple user creation works in transaction", %{conn: conn} do user = insert(:user) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> post("/api/pleroma/admin/users", %{ "users" => [ @@ -210,13 +316,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do describe "/api/pleroma/admin/users/:nickname" do test "Show", %{conn: conn} do - admin = insert(:user, is_admin: true) user = insert(:user) - conn = - conn - |> assign(:user, admin) - |> get("/api/pleroma/admin/users/#{user.nickname}") + conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}") expected = %{ "deactivated" => false, @@ -234,26 +336,20 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end test "when the user doesn't exist", %{conn: conn} do - admin = insert(:user, is_admin: true) user = build(:user) - conn = - conn - |> assign(:user, admin) - |> get("/api/pleroma/admin/users/#{user.nickname}") + conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}") assert "Not found" == json_response(conn, 404) end end describe "/api/pleroma/admin/users/follow" do - test "allows to force-follow another user" do - admin = insert(:user, is_admin: true) + test "allows to force-follow another user", %{admin: admin, conn: conn} do user = insert(:user) follower = insert(:user) - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> post("/api/pleroma/admin/users/follow", %{ "follower" => follower.nickname, @@ -273,15 +369,13 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "/api/pleroma/admin/users/unfollow" do - test "allows to force-unfollow another user" do - admin = insert(:user, is_admin: true) + test "allows to force-unfollow another user", %{admin: admin, conn: conn} do user = insert(:user) follower = insert(:user) User.follow(follower, user) - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> post("/api/pleroma/admin/users/unfollow", %{ "follower" => follower.nickname, @@ -301,23 +395,20 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "PUT /api/pleroma/admin/users/tag" do - setup do - admin = insert(:user, is_admin: true) + setup %{conn: conn} do user1 = insert(:user, %{tags: ["x"]}) user2 = insert(:user, %{tags: ["y"]}) user3 = insert(:user, %{tags: ["unchanged"]}) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> put( - "/api/pleroma/admin/users/tag?nicknames[]=#{user1.nickname}&nicknames[]=#{ - user2.nickname - }&tags[]=foo&tags[]=bar" + "/api/pleroma/admin/users/tag?nicknames[]=#{user1.nickname}&nicknames[]=" <> + "#{user2.nickname}&tags[]=foo&tags[]=bar" ) - %{conn: conn, admin: admin, user1: user1, user2: user2, user3: user3} + %{conn: conn, user1: user1, user2: user2, user3: user3} end test "it appends specified tags to users with specified nicknames", %{ @@ -350,23 +441,20 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "DELETE /api/pleroma/admin/users/tag" do - setup do - admin = insert(:user, is_admin: true) + setup %{conn: conn} do user1 = insert(:user, %{tags: ["x"]}) user2 = insert(:user, %{tags: ["y", "z"]}) user3 = insert(:user, %{tags: ["unchanged"]}) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> delete( - "/api/pleroma/admin/users/tag?nicknames[]=#{user1.nickname}&nicknames[]=#{ - user2.nickname - }&tags[]=x&tags[]=z" + "/api/pleroma/admin/users/tag?nicknames[]=#{user1.nickname}&nicknames[]=" <> + "#{user2.nickname}&tags[]=x&tags[]=z" ) - %{conn: conn, admin: admin, user1: user1, user2: user2, user3: user3} + %{conn: conn, user1: user1, user2: user2, user3: user3} end test "it removes specified tags from users with specified nicknames", %{ @@ -399,12 +487,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "/api/pleroma/admin/users/:nickname/permission_group" do - test "GET is giving user_info" do - admin = insert(:user, is_admin: true) - + test "GET is giving user_info", %{admin: admin, conn: conn} do conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> get("/api/pleroma/admin/users/#{admin.nickname}/permission_group/") @@ -414,13 +499,11 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do } end - test "/:right POST, can add to a permission group" do - admin = insert(:user, is_admin: true) + test "/:right POST, can add to a permission group", %{admin: admin, conn: conn} do user = insert(:user) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> post("/api/pleroma/admin/users/#{user.nickname}/permission_group/admin") @@ -434,22 +517,18 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do "@#{admin.nickname} made @#{user.nickname} admin" end - test "/:right POST, can add to a permission group (multiple)" do - admin = insert(:user, is_admin: true) + test "/:right POST, can add to a permission group (multiple)", %{admin: admin, conn: conn} do user_one = insert(:user) user_two = insert(:user) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> post("/api/pleroma/admin/users/permission_group/admin", %{ nicknames: [user_one.nickname, user_two.nickname] }) - assert json_response(conn, 200) == %{ - "is_admin" => true - } + assert json_response(conn, 200) == %{"is_admin" => true} log_entry = Repo.one(ModerationLog) @@ -457,19 +536,15 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do "@#{admin.nickname} made @#{user_one.nickname}, @#{user_two.nickname} admin" end - test "/:right DELETE, can remove from a permission group" do - admin = insert(:user, is_admin: true) + test "/:right DELETE, can remove from a permission group", %{admin: admin, conn: conn} do user = insert(:user, is_admin: true) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> delete("/api/pleroma/admin/users/#{user.nickname}/permission_group/admin") - assert json_response(conn, 200) == %{ - "is_admin" => false - } + assert json_response(conn, 200) == %{"is_admin" => false} log_entry = Repo.one(ModerationLog) @@ -477,22 +552,21 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do "@#{admin.nickname} revoked admin role from @#{user.nickname}" end - test "/:right DELETE, can remove from a permission group (multiple)" do - admin = insert(:user, is_admin: true) + test "/:right DELETE, can remove from a permission group (multiple)", %{ + admin: admin, + conn: conn + } do user_one = insert(:user, is_admin: true) user_two = insert(:user, is_admin: true) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> delete("/api/pleroma/admin/users/permission_group/admin", %{ nicknames: [user_one.nickname, user_two.nickname] }) - assert json_response(conn, 200) == %{ - "is_admin" => false - } + assert json_response(conn, 200) == %{"is_admin" => false} log_entry = Repo.one(ModerationLog) @@ -504,10 +578,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "POST /api/pleroma/admin/email_invite, with valid config" do - setup do - [user: insert(:user, is_admin: true)] - end - clear_config([:instance, :registrations_open]) do Pleroma.Config.put([:instance, :registrations_open], false) end @@ -516,20 +586,19 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do Pleroma.Config.put([:instance, :invites_enabled], true) end - test "sends invitation and returns 204", %{conn: conn, user: user} do + test "sends invitation and returns 204", %{admin: admin, conn: conn} do recipient_email = "foo@bar.com" recipient_name = "J. D." conn = - conn - |> assign(:user, user) - |> post( + post( + conn, "/api/pleroma/admin/users/email_invite?email=#{recipient_email}&name=#{recipient_name}" ) assert json_response(conn, :no_content) - token_record = List.last(Pleroma.Repo.all(Pleroma.UserInviteToken)) + token_record = List.last(Repo.all(Pleroma.UserInviteToken)) assert token_record refute token_record.used @@ -538,7 +607,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do email = Pleroma.Emails.UserEmail.user_invitation_email( - user, + admin, token_record, recipient_email, recipient_name @@ -551,12 +620,14 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do ) end - test "it returns 403 if requested by a non-admin", %{conn: conn} do + test "it returns 403 if requested by a non-admin" do non_admin_user = insert(:user) + token = insert(:oauth_token, user: non_admin_user) conn = - conn + build_conn() |> assign(:user, non_admin_user) + |> assign(:token, token) |> post("/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD") assert json_response(conn, :forbidden) @@ -564,45 +635,33 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "POST /api/pleroma/admin/users/email_invite, with invalid config" do - setup do - [user: insert(:user, is_admin: true)] - end - clear_config([:instance, :registrations_open]) clear_config([:instance, :invites_enabled]) - test "it returns 500 if `invites_enabled` is not enabled", %{conn: conn, user: user} do + test "it returns 500 if `invites_enabled` is not enabled", %{conn: conn} do Pleroma.Config.put([:instance, :registrations_open], false) Pleroma.Config.put([:instance, :invites_enabled], false) - conn = - conn - |> assign(:user, user) - |> post("/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD") + conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD") assert json_response(conn, :internal_server_error) end - test "it returns 500 if `registrations_open` is enabled", %{conn: conn, user: user} do + test "it returns 500 if `registrations_open` is enabled", %{conn: conn} do Pleroma.Config.put([:instance, :registrations_open], true) Pleroma.Config.put([:instance, :invites_enabled], true) - conn = - conn - |> assign(:user, user) - |> post("/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD") + conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD") assert json_response(conn, :internal_server_error) end end - test "/api/pleroma/admin/users/:nickname/password_reset" do - admin = insert(:user, is_admin: true) + test "/api/pleroma/admin/users/:nickname/password_reset", %{conn: conn} do user = insert(:user) conn = - build_conn() - |> assign(:user, admin) + conn |> put_req_header("accept", "application/json") |> get("/api/pleroma/admin/users/#{user.nickname}/password_reset") @@ -612,16 +671,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "GET /api/pleroma/admin/users" do - setup do - admin = insert(:user, is_admin: true) - - conn = - build_conn() - |> assign(:user, admin) - - {:ok, conn: conn, admin: admin} - end - test "renders users array for the first page", %{conn: conn, admin: admin} do user = insert(:user, local: false, tags: ["foo", "bar"]) conn = get(conn, "/api/pleroma/admin/users?page=1") @@ -843,6 +892,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do test "only local users" do admin = insert(:user, is_admin: true, nickname: "john") + token = insert(:oauth_admin_token, user: admin) user = insert(:user, nickname: "bob") insert(:user, nickname: "bobb", local: false) @@ -850,6 +900,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do conn = build_conn() |> assign(:user, admin) + |> assign(:token, token) |> get("/api/pleroma/admin/users?query=bo&filters=local") assert json_response(conn, 200) == %{ @@ -871,16 +922,13 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do } end - test "only local users with no query", %{admin: old_admin} do + test "only local users with no query", %{conn: conn, admin: old_admin} do admin = insert(:user, is_admin: true, nickname: "john") user = insert(:user, nickname: "bob") insert(:user, nickname: "bobb", local: false) - conn = - build_conn() - |> assign(:user, admin) - |> get("/api/pleroma/admin/users?filters=local") + conn = get(conn, "/api/pleroma/admin/users?filters=local") users = [ @@ -1038,6 +1086,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do test "it works with multiple filters" do admin = insert(:user, nickname: "john", is_admin: true) + token = insert(:oauth_admin_token, user: admin) user = insert(:user, nickname: "bob", local: false, deactivated: true) insert(:user, nickname: "ken", local: true, deactivated: true) @@ -1046,6 +1095,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do conn = build_conn() |> assign(:user, admin) + |> assign(:token, token) |> get("/api/pleroma/admin/users?filters=deactivated,external") assert json_response(conn, 200) == %{ @@ -1067,13 +1117,10 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do } end - test "it omits relay user", %{admin: admin} do + test "it omits relay user", %{admin: admin, conn: conn} do assert %User{} = Relay.get_actor() - conn = - build_conn() - |> assign(:user, admin) - |> get("/api/pleroma/admin/users") + conn = get(conn, "/api/pleroma/admin/users") assert json_response(conn, 200) == %{ "count" => 1, @@ -1095,15 +1142,13 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end end - test "PATCH /api/pleroma/admin/users/activate" do - admin = insert(:user, is_admin: true) + test "PATCH /api/pleroma/admin/users/activate", %{admin: admin, conn: conn} do user_one = insert(:user, deactivated: true) user_two = insert(:user, deactivated: true) conn = - build_conn() - |> assign(:user, admin) - |> patch( + patch( + conn, "/api/pleroma/admin/users/activate", %{nicknames: [user_one.nickname, user_two.nickname]} ) @@ -1117,15 +1162,13 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do "@#{admin.nickname} activated users: @#{user_one.nickname}, @#{user_two.nickname}" end - test "PATCH /api/pleroma/admin/users/deactivate" do - admin = insert(:user, is_admin: true) + test "PATCH /api/pleroma/admin/users/deactivate", %{admin: admin, conn: conn} do user_one = insert(:user, deactivated: false) user_two = insert(:user, deactivated: false) conn = - build_conn() - |> assign(:user, admin) - |> patch( + patch( + conn, "/api/pleroma/admin/users/deactivate", %{nicknames: [user_one.nickname, user_two.nickname]} ) @@ -1139,14 +1182,10 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do "@#{admin.nickname} deactivated users: @#{user_one.nickname}, @#{user_two.nickname}" end - test "PATCH /api/pleroma/admin/users/:nickname/toggle_activation" do - admin = insert(:user, is_admin: true) + test "PATCH /api/pleroma/admin/users/:nickname/toggle_activation", %{admin: admin, conn: conn} do user = insert(:user) - conn = - build_conn() - |> assign(:user, admin) - |> patch("/api/pleroma/admin/users/#{user.nickname}/toggle_activation") + conn = patch(conn, "/api/pleroma/admin/users/#{user.nickname}/toggle_activation") assert json_response(conn, 200) == %{ @@ -1168,16 +1207,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "POST /api/pleroma/admin/users/invite_token" do - setup do - admin = insert(:user, is_admin: true) - - conn = - build_conn() - |> assign(:user, admin) - - {:ok, conn: conn} - end - test "without options", %{conn: conn} do conn = post(conn, "/api/pleroma/admin/users/invite_token") @@ -1232,16 +1261,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "GET /api/pleroma/admin/users/invites" do - setup do - admin = insert(:user, is_admin: true) - - conn = - build_conn() - |> assign(:user, admin) - - {:ok, conn: conn} - end - test "no invites", %{conn: conn} do conn = get(conn, "/api/pleroma/admin/users/invites") @@ -1270,14 +1289,10 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "POST /api/pleroma/admin/users/revoke_invite" do - test "with token" do - admin = insert(:user, is_admin: true) + test "with token", %{conn: conn} do {:ok, invite} = UserInviteToken.create_invite() - conn = - build_conn() - |> assign(:user, admin) - |> post("/api/pleroma/admin/users/revoke_invite", %{"token" => invite.token}) + conn = post(conn, "/api/pleroma/admin/users/revoke_invite", %{"token" => invite.token}) assert json_response(conn, 200) == %{ "expires_at" => nil, @@ -1290,25 +1305,14 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do } end - test "with invalid token" do - admin = insert(:user, is_admin: true) - - conn = - build_conn() - |> assign(:user, admin) - |> post("/api/pleroma/admin/users/revoke_invite", %{"token" => "foo"}) + test "with invalid token", %{conn: conn} do + conn = post(conn, "/api/pleroma/admin/users/revoke_invite", %{"token" => "foo"}) assert json_response(conn, :not_found) == "Not found" end end describe "GET /api/pleroma/admin/reports/:id" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) - - %{conn: assign(conn, :user, admin)} - end - test "returns report by its id", %{conn: conn} do [reporter, target_user] = insert_pair(:user) activity = insert(:note_activity, user: target_user) @@ -1336,8 +1340,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "PATCH /api/pleroma/admin/reports" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) + setup do [reporter, target_user] = insert_pair(:user) activity = insert(:note_activity, user: target_user) @@ -1356,13 +1359,35 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do }) %{ - conn: assign(conn, :user, admin), id: report_id, - admin: admin, second_report_id: second_report_id } end + test "requires admin:write:reports scope", %{conn: conn, id: id, admin: admin} do + read_token = insert(:oauth_token, user: admin, scopes: ["admin:read"]) + write_token = insert(:oauth_token, user: admin, scopes: ["admin:write:reports"]) + + response = + conn + |> assign(:token, read_token) + |> patch("/api/pleroma/admin/reports", %{ + "reports" => [%{"state" => "resolved", "id" => id}] + }) + |> json_response(403) + + assert response == %{ + "error" => "Insufficient permissions: admin:write:reports." + } + + conn + |> assign(:token, write_token) + |> patch("/api/pleroma/admin/reports", %{ + "reports" => [%{"state" => "resolved", "id" => id}] + }) + |> json_response(:no_content) + end + test "mark report as resolved", %{conn: conn, id: id, admin: admin} do conn |> patch("/api/pleroma/admin/reports", %{ @@ -1454,12 +1479,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "GET /api/pleroma/admin/reports" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) - - %{conn: assign(conn, :user, admin)} - end - test "returns empty response when no reports created", %{conn: conn} do response = conn @@ -1554,27 +1573,27 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do test "returns 403 when requested by a non-admin" do user = insert(:user) + token = insert(:oauth_token, user: user) conn = build_conn() |> assign(:user, user) + |> assign(:token, token) |> get("/api/pleroma/admin/reports") - assert json_response(conn, :forbidden) == %{"error" => "User is not admin."} + assert json_response(conn, :forbidden) == + %{"error" => "User is not an admin or OAuth admin scope is not granted."} end test "returns 403 when requested by anonymous" do - conn = - build_conn() - |> get("/api/pleroma/admin/reports") + conn = get(build_conn(), "/api/pleroma/admin/reports") assert json_response(conn, :forbidden) == %{"error" => "Invalid credentials."} end end describe "GET /api/pleroma/admin/grouped_reports" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) + setup do [reporter, target_user] = insert_pair(:user) date1 = (DateTime.to_unix(DateTime.utc_now()) + 1000) |> DateTime.from_unix!() @@ -1609,7 +1628,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do }) %{ - conn: assign(conn, :user, admin), first_status: Activity.get_by_ap_id_with_object(first_status.data["id"]), second_status: Activity.get_by_ap_id_with_object(second_status.data["id"]), third_status: Activity.get_by_ap_id_with_object(third_status.data["id"]), @@ -1776,67 +1794,11 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end end - describe "POST /api/pleroma/admin/reports/:id/respond" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) - - %{conn: assign(conn, :user, admin), admin: admin} - end - - test "returns created dm", %{conn: conn, admin: admin} do - [reporter, target_user] = insert_pair(:user) - activity = insert(:note_activity, user: target_user) - - {:ok, %{id: report_id}} = - CommonAPI.report(reporter, %{ - "account_id" => target_user.id, - "comment" => "I feel offended", - "status_ids" => [activity.id] - }) - - response = - conn - |> post("/api/pleroma/admin/reports/#{report_id}/respond", %{ - "status" => "I will check it out" - }) - |> json_response(:ok) - - recipients = Enum.map(response["mentions"], & &1["username"]) - - assert reporter.nickname in recipients - assert response["content"] == "I will check it out" - assert response["visibility"] == "direct" - - log_entry = Repo.one(ModerationLog) - - assert ModerationLog.get_log_entry_message(log_entry) == - "@#{admin.nickname} responded with 'I will check it out' to report ##{ - response["id"] - }" - end - - test "returns 400 when status is missing", %{conn: conn} do - conn = post(conn, "/api/pleroma/admin/reports/test/respond") - - assert json_response(conn, :bad_request) == "Invalid parameters" - end - - test "returns 404 when report id is invalid", %{conn: conn} do - conn = - post(conn, "/api/pleroma/admin/reports/test/respond", %{ - "status" => "foo" - }) - - assert json_response(conn, :not_found) == "Not found" - end - end - describe "PUT /api/pleroma/admin/statuses/:id" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) + setup do activity = insert(:note_activity) - %{conn: assign(conn, :user, admin), id: activity.id, admin: admin} + %{id: activity.id} end test "toggle sensitive flag", %{conn: conn, id: id, admin: admin} do @@ -1889,20 +1851,17 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end test "returns 400 when visibility is unknown", %{conn: conn, id: id} do - conn = - conn - |> put("/api/pleroma/admin/statuses/#{id}", %{"visibility" => "test"}) + conn = put(conn, "/api/pleroma/admin/statuses/#{id}", %{"visibility" => "test"}) assert json_response(conn, :bad_request) == "Unsupported visibility" end end describe "DELETE /api/pleroma/admin/statuses/:id" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) + setup do activity = insert(:note_activity) - %{conn: assign(conn, :user, admin), id: activity.id, admin: admin} + %{id: activity.id} end test "deletes status", %{conn: conn, id: id, admin: admin} do @@ -1919,40 +1878,49 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end test "returns error when status is not exist", %{conn: conn} do - conn = - conn - |> delete("/api/pleroma/admin/statuses/test") + conn = delete(conn, "/api/pleroma/admin/statuses/test") assert json_response(conn, :bad_request) == "Could not delete" end end describe "GET /api/pleroma/admin/config" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) + clear_config(:configurable_from_database) do + Pleroma.Config.put(:configurable_from_database, true) + end - %{conn: assign(conn, :user, admin)} + test "when configuration from database is off", %{conn: conn} do + initial = Pleroma.Config.get(:configurable_from_database) + Pleroma.Config.put(:configurable_from_database, false) + on_exit(fn -> Pleroma.Config.put(:configurable_from_database, initial) end) + conn = get(conn, "/api/pleroma/admin/config") + + assert json_response(conn, 400) == + "To use this endpoint you need to enable configuration from database." end test "without any settings in db", %{conn: conn} do conn = get(conn, "/api/pleroma/admin/config") - assert json_response(conn, 200) == %{"configs" => []} + assert json_response(conn, 400) == + "To use configuration from database migrate your settings to database." end - test "with settings in db", %{conn: conn} do + test "with settings only in db", %{conn: conn} do config1 = insert(:config) config2 = insert(:config) - conn = get(conn, "/api/pleroma/admin/config") + conn = get(conn, "/api/pleroma/admin/config", %{"only_db" => true}) %{ "configs" => [ %{ + "group" => ":pleroma", "key" => key1, "value" => _ }, %{ + "group" => ":pleroma", "key" => key2, "value" => _ } @@ -1962,13 +1930,107 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do assert key1 == config1.key assert key2 == config2.key end + + test "db is added to settings that are in db", %{conn: conn} do + _config = insert(:config, key: ":instance", value: ConfigDB.to_binary(name: "Some name")) + + %{"configs" => configs} = + conn + |> get("/api/pleroma/admin/config") + |> json_response(200) + + [instance_config] = + Enum.filter(configs, fn %{"group" => group, "key" => key} -> + group == ":pleroma" and key == ":instance" + end) + + assert instance_config["db"] == [":name"] + end + + test "merged default setting with db settings", %{conn: conn} do + config1 = insert(:config) + config2 = insert(:config) + + config3 = + insert(:config, + value: ConfigDB.to_binary(k1: :v1, k2: :v2) + ) + + %{"configs" => configs} = + conn + |> get("/api/pleroma/admin/config") + |> json_response(200) + + assert length(configs) > 3 + + received_configs = + Enum.filter(configs, fn %{"group" => group, "key" => key} -> + group == ":pleroma" and key in [config1.key, config2.key, config3.key] + end) + + assert length(received_configs) == 3 + + db_keys = + config3.value + |> ConfigDB.from_binary() + |> Keyword.keys() + |> ConfigDB.convert() + + Enum.each(received_configs, fn %{"value" => value, "db" => db} -> + assert db in [[config1.key], [config2.key], db_keys] + + assert value in [ + ConfigDB.from_binary_with_convert(config1.value), + ConfigDB.from_binary_with_convert(config2.value), + ConfigDB.from_binary_with_convert(config3.value) + ] + end) + end + + test "subkeys with full update right merge", %{conn: conn} do + config1 = + insert(:config, + key: ":emoji", + value: ConfigDB.to_binary(groups: [a: 1, b: 2], key: [a: 1]) + ) + + config2 = + insert(:config, + key: ":assets", + value: ConfigDB.to_binary(mascots: [a: 1, b: 2], key: [a: 1]) + ) + + %{"configs" => configs} = + conn + |> get("/api/pleroma/admin/config") + |> json_response(200) + + vals = + Enum.filter(configs, fn %{"group" => group, "key" => key} -> + group == ":pleroma" and key in [config1.key, config2.key] + end) + + emoji = Enum.find(vals, fn %{"key" => key} -> key == ":emoji" end) + assets = Enum.find(vals, fn %{"key" => key} -> key == ":assets" end) + + emoji_val = ConfigDB.transform_with_out_binary(emoji["value"]) + assets_val = ConfigDB.transform_with_out_binary(assets["value"]) + + assert emoji_val[:groups] == [a: 1, b: 2] + assert assets_val[:mascots] == [a: 1, b: 2] + end end - describe "POST /api/pleroma/admin/config" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) + test "POST /api/pleroma/admin/config error", %{conn: conn} do + conn = post(conn, "/api/pleroma/admin/config", %{"configs" => []}) - temp_file = "config/test.exported_from_db.secret.exs" + assert json_response(conn, 400) == + "To use this endpoint you need to enable configuration from database." + end + + describe "POST /api/pleroma/admin/config" do + setup do + http = Application.get_env(:pleroma, :http) on_exit(fn -> Application.delete_env(:pleroma, :key1) @@ -1979,30 +2041,33 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do Application.delete_env(:pleroma, :keyaa2) Application.delete_env(:pleroma, Pleroma.Web.Endpoint.NotReal) Application.delete_env(:pleroma, Pleroma.Captcha.NotReal) - :ok = File.rm(temp_file) + Application.put_env(:pleroma, :http, http) + Application.put_env(:tesla, :adapter, Tesla.Mock) + :ok = File.rm("config/test.exported_from_db.secret.exs") end) - - %{conn: assign(conn, :user, admin)} end - clear_config([:instance, :dynamic_configuration]) do - Pleroma.Config.put([:instance, :dynamic_configuration], true) + clear_config(:configurable_from_database) do + Pleroma.Config.put(:configurable_from_database, true) end @tag capture_log: true test "create new config setting in db", %{conn: conn} do + ueberauth = Application.get_env(:ueberauth, Ueberauth) + on_exit(fn -> Application.put_env(:ueberauth, Ueberauth, ueberauth) end) + conn = post(conn, "/api/pleroma/admin/config", %{ configs: [ - %{group: "pleroma", key: "key1", value: "value1"}, + %{group: ":pleroma", key: ":key1", value: "value1"}, %{ - group: "ueberauth", - key: "Ueberauth.Strategy.Twitter.OAuth", + group: ":ueberauth", + key: "Ueberauth", value: [%{"tuple" => [":consumer_secret", "aaaa"]}] }, %{ - group: "pleroma", - key: "key2", + group: ":pleroma", + key: ":key2", value: %{ ":nested_1" => "nested_value1", ":nested_2" => [ @@ -2012,21 +2077,21 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do } }, %{ - group: "pleroma", - key: "key3", + group: ":pleroma", + key: ":key3", value: [ %{"nested_3" => ":nested_3", "nested_33" => "nested_33"}, %{"nested_4" => true} ] }, %{ - group: "pleroma", - key: "key4", + group: ":pleroma", + key: ":key4", value: %{":nested_5" => ":upload", "endpoint" => "https://example.com"} }, %{ - group: "idna", - key: "key5", + group: ":idna", + key: ":key5", value: %{"tuple" => ["string", "Pleroma.Captcha.NotReal", []]} } ] @@ -2035,43 +2100,49 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do assert json_response(conn, 200) == %{ "configs" => [ %{ - "group" => "pleroma", - "key" => "key1", - "value" => "value1" + "group" => ":pleroma", + "key" => ":key1", + "value" => "value1", + "db" => [":key1"] }, %{ - "group" => "ueberauth", - "key" => "Ueberauth.Strategy.Twitter.OAuth", - "value" => [%{"tuple" => [":consumer_secret", "aaaa"]}] + "group" => ":ueberauth", + "key" => "Ueberauth", + "value" => [%{"tuple" => [":consumer_secret", "aaaa"]}], + "db" => [":consumer_secret"] }, %{ - "group" => "pleroma", - "key" => "key2", + "group" => ":pleroma", + "key" => ":key2", "value" => %{ ":nested_1" => "nested_value1", ":nested_2" => [ %{":nested_22" => "nested_value222"}, %{":nested_33" => %{":nested_44" => "nested_444"}} ] - } + }, + "db" => [":key2"] }, %{ - "group" => "pleroma", - "key" => "key3", + "group" => ":pleroma", + "key" => ":key3", "value" => [ %{"nested_3" => ":nested_3", "nested_33" => "nested_33"}, %{"nested_4" => true} - ] + ], + "db" => [":key3"] }, %{ - "group" => "pleroma", - "key" => "key4", - "value" => %{"endpoint" => "https://example.com", ":nested_5" => ":upload"} + "group" => ":pleroma", + "key" => ":key4", + "value" => %{"endpoint" => "https://example.com", ":nested_5" => ":upload"}, + "db" => [":key4"] }, %{ - "group" => "idna", - "key" => "key5", - "value" => %{"tuple" => ["string", "Pleroma.Captcha.NotReal", []]} + "group" => ":idna", + "key" => ":key5", + "value" => %{"tuple" => ["string", "Pleroma.Captcha.NotReal", []]}, + "db" => [":key5"] } ] } @@ -2099,25 +2170,203 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do assert Application.get_env(:idna, :key5) == {"string", Pleroma.Captcha.NotReal, []} end - test "update config setting & delete", %{conn: conn} do - config1 = insert(:config, key: "keyaa1") - config2 = insert(:config, key: "keyaa2") + test "save config setting without key", %{conn: conn} do + level = Application.get_env(:quack, :level) + meta = Application.get_env(:quack, :meta) + webhook_url = Application.get_env(:quack, :webhook_url) - insert(:config, - group: "ueberauth", - key: "Ueberauth.Strategy.Microsoft.OAuth", - value: :erlang.term_to_binary([]) - ) + on_exit(fn -> + Application.put_env(:quack, :level, level) + Application.put_env(:quack, :meta, meta) + Application.put_env(:quack, :webhook_url, webhook_url) + end) + + conn = + post(conn, "/api/pleroma/admin/config", %{ + configs: [ + %{ + group: ":quack", + key: ":level", + value: ":info" + }, + %{ + group: ":quack", + key: ":meta", + value: [":none"] + }, + %{ + group: ":quack", + key: ":webhook_url", + value: "https://hooks.slack.com/services/KEY" + } + ] + }) + + assert json_response(conn, 200) == %{ + "configs" => [ + %{ + "group" => ":quack", + "key" => ":level", + "value" => ":info", + "db" => [":level"] + }, + %{ + "group" => ":quack", + "key" => ":meta", + "value" => [":none"], + "db" => [":meta"] + }, + %{ + "group" => ":quack", + "key" => ":webhook_url", + "value" => "https://hooks.slack.com/services/KEY", + "db" => [":webhook_url"] + } + ] + } + + assert Application.get_env(:quack, :level) == :info + assert Application.get_env(:quack, :meta) == [:none] + assert Application.get_env(:quack, :webhook_url) == "https://hooks.slack.com/services/KEY" + end + + test "saving config with partial update", %{conn: conn} do + config = insert(:config, key: ":key1", value: :erlang.term_to_binary(key1: 1, key2: 2)) + + conn = + post(conn, "/api/pleroma/admin/config", %{ + configs: [ + %{group: config.group, key: config.key, value: [%{"tuple" => [":key3", 3]}]} + ] + }) + + assert json_response(conn, 200) == %{ + "configs" => [ + %{ + "group" => ":pleroma", + "key" => ":key1", + "value" => [ + %{"tuple" => [":key1", 1]}, + %{"tuple" => [":key2", 2]}, + %{"tuple" => [":key3", 3]} + ], + "db" => [":key1", ":key2", ":key3"] + } + ] + } + end + + test "saving config with nested merge", %{conn: conn} do + config = + insert(:config, key: ":key1", value: :erlang.term_to_binary(key1: 1, key2: [k1: 1, k2: 2])) + + conn = + post(conn, "/api/pleroma/admin/config", %{ + configs: [ + %{ + group: config.group, + key: config.key, + value: [ + %{"tuple" => [":key3", 3]}, + %{ + "tuple" => [ + ":key2", + [ + %{"tuple" => [":k2", 1]}, + %{"tuple" => [":k3", 3]} + ] + ] + } + ] + } + ] + }) + + assert json_response(conn, 200) == %{ + "configs" => [ + %{ + "group" => ":pleroma", + "key" => ":key1", + "value" => [ + %{"tuple" => [":key1", 1]}, + %{"tuple" => [":key3", 3]}, + %{ + "tuple" => [ + ":key2", + [ + %{"tuple" => [":k1", 1]}, + %{"tuple" => [":k2", 1]}, + %{"tuple" => [":k3", 3]} + ] + ] + } + ], + "db" => [":key1", ":key3", ":key2"] + } + ] + } + end + + test "saving special atoms", %{conn: conn} do + conn = + post(conn, "/api/pleroma/admin/config", %{ + "configs" => [ + %{ + "group" => ":pleroma", + "key" => ":key1", + "value" => [ + %{ + "tuple" => [ + ":ssl_options", + [%{"tuple" => [":versions", [":tlsv1", ":tlsv1.1", ":tlsv1.2"]]}] + ] + } + ] + } + ] + }) + + assert json_response(conn, 200) == %{ + "configs" => [ + %{ + "group" => ":pleroma", + "key" => ":key1", + "value" => [ + %{ + "tuple" => [ + ":ssl_options", + [%{"tuple" => [":versions", [":tlsv1", ":tlsv1.1", ":tlsv1.2"]]}] + ] + } + ], + "db" => [":ssl_options"] + } + ] + } + + assert Application.get_env(:pleroma, :key1) == [ + ssl_options: [versions: [:tlsv1, :"tlsv1.1", :"tlsv1.2"]] + ] + end + + test "saving full setting if value is in full_key_update list", %{conn: conn} do + backends = Application.get_env(:logger, :backends) + on_exit(fn -> Application.put_env(:logger, :backends, backends) end) + + config = + insert(:config, + group: ":logger", + key: ":backends", + value: :erlang.term_to_binary([]) + ) conn = post(conn, "/api/pleroma/admin/config", %{ configs: [ - %{group: config1.group, key: config1.key, value: "another_value"}, - %{group: config2.group, key: config2.key, delete: "true"}, %{ - group: "ueberauth", - key: "Ueberauth.Strategy.Microsoft.OAuth", - delete: "true" + group: config.group, + key: config.key, + value: [":console", %{"tuple" => ["ExSyslogger", ":ex_syslogger"]}] } ] }) @@ -2125,23 +2374,131 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do assert json_response(conn, 200) == %{ "configs" => [ %{ - "group" => "pleroma", + "group" => ":logger", + "key" => ":backends", + "value" => [ + ":console", + %{"tuple" => ["ExSyslogger", ":ex_syslogger"]} + ], + "db" => [":backends"] + } + ] + } + + assert Application.get_env(:logger, :backends) == [ + :console, + {ExSyslogger, :ex_syslogger} + ] + + ExUnit.CaptureLog.capture_log(fn -> + require Logger + Logger.warn("Ooops...") + end) =~ "Ooops..." + end + + test "saving full setting if value is not keyword", %{conn: conn} do + config = + insert(:config, + group: ":tesla", + key: ":adapter", + value: :erlang.term_to_binary(Tesla.Adapter.Hackey) + ) + + conn = + post(conn, "/api/pleroma/admin/config", %{ + configs: [ + %{group: config.group, key: config.key, value: "Tesla.Adapter.Httpc"} + ] + }) + + assert json_response(conn, 200) == %{ + "configs" => [ + %{ + "group" => ":tesla", + "key" => ":adapter", + "value" => "Tesla.Adapter.Httpc", + "db" => [":adapter"] + } + ] + } + end + + test "update config setting & delete with fallback to default value", %{ + conn: conn, + admin: admin, + token: token + } do + ueberauth = Application.get_env(:ueberauth, Ueberauth) + config1 = insert(:config, key: ":keyaa1") + config2 = insert(:config, key: ":keyaa2") + + config3 = + insert(:config, + group: ":ueberauth", + key: "Ueberauth" + ) + + conn = + post(conn, "/api/pleroma/admin/config", %{ + configs: [ + %{group: config1.group, key: config1.key, value: "another_value"}, + %{group: config2.group, key: config2.key, value: "another_value"} + ] + }) + + assert json_response(conn, 200) == %{ + "configs" => [ + %{ + "group" => ":pleroma", "key" => config1.key, - "value" => "another_value" + "value" => "another_value", + "db" => [":keyaa1"] + }, + %{ + "group" => ":pleroma", + "key" => config2.key, + "value" => "another_value", + "db" => [":keyaa2"] } ] } assert Application.get_env(:pleroma, :keyaa1) == "another_value" - refute Application.get_env(:pleroma, :keyaa2) + assert Application.get_env(:pleroma, :keyaa2) == "another_value" + assert Application.get_env(:ueberauth, Ueberauth) == ConfigDB.from_binary(config3.value) + + conn = + build_conn() + |> assign(:user, admin) + |> assign(:token, token) + |> post("/api/pleroma/admin/config", %{ + configs: [ + %{group: config2.group, key: config2.key, delete: true}, + %{ + group: ":ueberauth", + key: "Ueberauth", + delete: true + } + ] + }) + + assert json_response(conn, 200) == %{ + "configs" => [] + } + + assert Application.get_env(:ueberauth, Ueberauth) == ueberauth + refute Keyword.has_key?(Application.get_all_env(:pleroma), :keyaa2) end test "common config example", %{conn: conn} do + adapter = Application.get_env(:tesla, :adapter) + on_exit(fn -> Application.put_env(:tesla, :adapter, adapter) end) + conn = post(conn, "/api/pleroma/admin/config", %{ configs: [ %{ - "group" => "pleroma", + "group" => ":pleroma", "key" => "Pleroma.Captcha.NotReal", "value" => [ %{"tuple" => [":enabled", false]}, @@ -2153,16 +2510,25 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do %{"tuple" => [":regex1", "~r/https:\/\/example.com/"]}, %{"tuple" => [":regex2", "~r/https:\/\/example.com/u"]}, %{"tuple" => [":regex3", "~r/https:\/\/example.com/i"]}, - %{"tuple" => [":regex4", "~r/https:\/\/example.com/s"]} + %{"tuple" => [":regex4", "~r/https:\/\/example.com/s"]}, + %{"tuple" => [":name", "Pleroma"]} ] + }, + %{ + "group" => ":tesla", + "key" => ":adapter", + "value" => "Tesla.Adapter.Httpc" } ] }) + assert Application.get_env(:tesla, :adapter) == Tesla.Adapter.Httpc + assert Pleroma.Config.get([Pleroma.Captcha.NotReal, :name]) == "Pleroma" + assert json_response(conn, 200) == %{ "configs" => [ %{ - "group" => "pleroma", + "group" => ":pleroma", "key" => "Pleroma.Captcha.NotReal", "value" => [ %{"tuple" => [":enabled", false]}, @@ -2174,8 +2540,28 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do %{"tuple" => [":regex1", "~r/https:\\/\\/example.com/"]}, %{"tuple" => [":regex2", "~r/https:\\/\\/example.com/u"]}, %{"tuple" => [":regex3", "~r/https:\\/\\/example.com/i"]}, - %{"tuple" => [":regex4", "~r/https:\\/\\/example.com/s"]} + %{"tuple" => [":regex4", "~r/https:\\/\\/example.com/s"]}, + %{"tuple" => [":name", "Pleroma"]} + ], + "db" => [ + ":enabled", + ":method", + ":seconds_valid", + ":path", + ":key1", + ":partial_chain", + ":regex1", + ":regex2", + ":regex3", + ":regex4", + ":name" ] + }, + %{ + "group" => ":tesla", + "key" => ":adapter", + "value" => "Tesla.Adapter.Httpc", + "db" => [":adapter"] } ] } @@ -2186,7 +2572,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do post(conn, "/api/pleroma/admin/config", %{ configs: [ %{ - "group" => "pleroma", + "group" => ":pleroma", "key" => "Pleroma.Web.Endpoint.NotReal", "value" => [ %{ @@ -2250,7 +2636,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do assert json_response(conn, 200) == %{ "configs" => [ %{ - "group" => "pleroma", + "group" => ":pleroma", "key" => "Pleroma.Web.Endpoint.NotReal", "value" => [ %{ @@ -2306,7 +2692,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do ] ] } - ] + ], + "db" => [":http"] } ] } @@ -2317,7 +2704,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do post(conn, "/api/pleroma/admin/config", %{ configs: [ %{ - "group" => "pleroma", + "group" => ":pleroma", "key" => ":key1", "value" => [ %{"tuple" => [":key2", "some_val"]}, @@ -2347,7 +2734,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do %{ "configs" => [ %{ - "group" => "pleroma", + "group" => ":pleroma", "key" => ":key1", "value" => [ %{"tuple" => [":key2", "some_val"]}, @@ -2368,7 +2755,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do } ] } - ] + ], + "db" => [":key2", ":key3"] } ] } @@ -2379,7 +2767,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do post(conn, "/api/pleroma/admin/config", %{ configs: [ %{ - "group" => "pleroma", + "group" => ":pleroma", "key" => ":key1", "value" => %{"key" => "some_val"} } @@ -2390,83 +2778,21 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do %{ "configs" => [ %{ - "group" => "pleroma", + "group" => ":pleroma", "key" => ":key1", - "value" => %{"key" => "some_val"} + "value" => %{"key" => "some_val"}, + "db" => [":key1"] } ] } end - test "dispatch setting", %{conn: conn} do - conn = - post(conn, "/api/pleroma/admin/config", %{ - configs: [ - %{ - "group" => "pleroma", - "key" => "Pleroma.Web.Endpoint.NotReal", - "value" => [ - %{ - "tuple" => [ - ":http", - [ - %{"tuple" => [":ip", %{"tuple" => [127, 0, 0, 1]}]}, - %{"tuple" => [":dispatch", ["{:_, - [ - {\"/api/v1/streaming\", Pleroma.Web.MastodonAPI.WebsocketHandler, []}, - {\"/websocket\", Phoenix.Endpoint.CowboyWebSocket, - {Phoenix.Transports.WebSocket, - {Pleroma.Web.Endpoint, Pleroma.Web.UserSocket, [path: \"/websocket\"]}}}, - {:_, Phoenix.Endpoint.Cowboy2Handler, {Pleroma.Web.Endpoint, []}} - ]}"]]} - ] - ] - } - ] - } - ] - }) - - dispatch_string = - "{:_, [{\"/api/v1/streaming\", Pleroma.Web.MastodonAPI.WebsocketHandler, []}, " <> - "{\"/websocket\", Phoenix.Endpoint.CowboyWebSocket, {Phoenix.Transports.WebSocket, " <> - "{Pleroma.Web.Endpoint, Pleroma.Web.UserSocket, [path: \"/websocket\"]}}}, " <> - "{:_, Phoenix.Endpoint.Cowboy2Handler, {Pleroma.Web.Endpoint, []}}]}" - - assert json_response(conn, 200) == %{ - "configs" => [ - %{ - "group" => "pleroma", - "key" => "Pleroma.Web.Endpoint.NotReal", - "value" => [ - %{ - "tuple" => [ - ":http", - [ - %{"tuple" => [":ip", %{"tuple" => [127, 0, 0, 1]}]}, - %{ - "tuple" => [ - ":dispatch", - [ - dispatch_string - ] - ] - } - ] - ] - } - ] - } - ] - } - end - test "queues key as atom", %{conn: conn} do conn = post(conn, "/api/pleroma/admin/config", %{ configs: [ %{ - "group" => "oban", + "group" => ":oban", "key" => ":queues", "value" => [ %{"tuple" => [":federator_incoming", 50]}, @@ -2484,7 +2810,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do assert json_response(conn, 200) == %{ "configs" => [ %{ - "group" => "oban", + "group" => ":oban", "key" => ":queues", "value" => [ %{"tuple" => [":federator_incoming", 50]}, @@ -2494,6 +2820,15 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do %{"tuple" => [":transmogrifier", 20]}, %{"tuple" => [":scheduled_activities", 10]}, %{"tuple" => [":background", 5]} + ], + "db" => [ + ":federator_incoming", + ":federator_outgoing", + ":web_push", + ":mailer", + ":transmogrifier", + ":scheduled_activities", + ":background" ] } ] @@ -2503,7 +2838,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do test "delete part of settings by atom subkeys", %{conn: conn} do config = insert(:config, - key: "keyaa1", + key: ":keyaa1", value: :erlang.term_to_binary(subkey1: "val1", subkey2: "val2", subkey3: "val3") ) @@ -2514,68 +2849,160 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do group: config.group, key: config.key, subkeys: [":subkey1", ":subkey3"], - delete: "true" + delete: true } ] }) - assert( - json_response(conn, 200) == %{ - "configs" => [ + assert json_response(conn, 200) == %{ + "configs" => [ + %{ + "group" => ":pleroma", + "key" => ":keyaa1", + "value" => [%{"tuple" => [":subkey2", "val2"]}], + "db" => [":subkey2"] + } + ] + } + end + + test "proxy tuple localhost", %{conn: conn} do + conn = + post(conn, "/api/pleroma/admin/config", %{ + configs: [ %{ - "group" => "pleroma", - "key" => "keyaa1", - "value" => [%{"tuple" => [":subkey2", "val2"]}] + group: ":pleroma", + key: ":http", + value: [ + %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "localhost", 1234]}]}, + %{"tuple" => [":send_user_agent", false]} + ] } ] - } - ) + }) + + assert json_response(conn, 200) == %{ + "configs" => [ + %{ + "group" => ":pleroma", + "key" => ":http", + "value" => [ + %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "localhost", 1234]}]}, + %{"tuple" => [":send_user_agent", false]} + ], + "db" => [":proxy_url", ":send_user_agent"] + } + ] + } end - end - describe "config mix tasks run" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) + test "proxy tuple domain", %{conn: conn} do + conn = + post(conn, "/api/pleroma/admin/config", %{ + configs: [ + %{ + group: ":pleroma", + key: ":http", + value: [ + %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "domain.com", 1234]}]}, + %{"tuple" => [":send_user_agent", false]} + ] + } + ] + }) + + assert json_response(conn, 200) == %{ + "configs" => [ + %{ + "group" => ":pleroma", + "key" => ":http", + "value" => [ + %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "domain.com", 1234]}]}, + %{"tuple" => [":send_user_agent", false]} + ], + "db" => [":proxy_url", ":send_user_agent"] + } + ] + } + end + + test "proxy tuple ip", %{conn: conn} do + conn = + post(conn, "/api/pleroma/admin/config", %{ + configs: [ + %{ + group: ":pleroma", + key: ":http", + value: [ + %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "127.0.0.1", 1234]}]}, + %{"tuple" => [":send_user_agent", false]} + ] + } + ] + }) - temp_file = "config/test.exported_from_db.secret.exs" + assert json_response(conn, 200) == %{ + "configs" => [ + %{ + "group" => ":pleroma", + "key" => ":http", + "value" => [ + %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "127.0.0.1", 1234]}]}, + %{"tuple" => [":send_user_agent", false]} + ], + "db" => [":proxy_url", ":send_user_agent"] + } + ] + } + end + end + describe "config mix tasks run" do + setup do Mix.shell(Mix.Shell.Quiet) on_exit(fn -> Mix.shell(Mix.Shell.IO) - :ok = File.rm(temp_file) end) - %{conn: assign(conn, :user, admin), admin: admin} + :ok end - clear_config([:instance, :dynamic_configuration]) do - Pleroma.Config.put([:instance, :dynamic_configuration], true) + clear_config(:configurable_from_database) do + Pleroma.Config.put(:configurable_from_database, true) end clear_config([:feed, :post_title]) do Pleroma.Config.put([:feed, :post_title], %{max_length: 100, omission: "…"}) end - test "transfer settings to DB and to file", %{conn: conn, admin: admin} do - assert Pleroma.Repo.all(Pleroma.Web.AdminAPI.Config) == [] - conn = get(conn, "/api/pleroma/admin/config/migrate_to_db") - assert json_response(conn, 200) == %{} - assert Pleroma.Repo.all(Pleroma.Web.AdminAPI.Config) > 0 + test "transfer settings to DB and to file", %{conn: conn} do + assert Repo.all(Pleroma.ConfigDB) == [] + Mix.Tasks.Pleroma.Config.migrate_to_db("test/fixtures/config/temp.secret.exs") + assert Repo.aggregate(Pleroma.ConfigDB, :count, :id) > 0 - conn = - build_conn() - |> assign(:user, admin) - |> get("/api/pleroma/admin/config/migrate_from_db") + conn = get(conn, "/api/pleroma/admin/config/migrate_from_db") assert json_response(conn, 200) == %{} - assert Pleroma.Repo.all(Pleroma.Web.AdminAPI.Config) == [] + assert Repo.all(Pleroma.ConfigDB) == [] + end + + test "returns error if configuration from database is off", %{conn: conn} do + initial = Pleroma.Config.get(:configurable_from_database) + on_exit(fn -> Pleroma.Config.put(:configurable_from_database, initial) end) + Pleroma.Config.put(:configurable_from_database, false) + + conn = get(conn, "/api/pleroma/admin/config/migrate_from_db") + + assert json_response(conn, 400) == + "To use this endpoint you need to enable configuration from database." + + assert Repo.all(Pleroma.ConfigDB) == [] end end describe "GET /api/pleroma/admin/users/:nickname/statuses" do setup do - admin = insert(:user, is_admin: true) user = insert(:user) date1 = (DateTime.to_unix(DateTime.utc_now()) + 2000) |> DateTime.from_unix!() @@ -2586,11 +3013,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do insert(:note_activity, user: user, published: date2) insert(:note_activity, user: user, published: date3) - conn = - build_conn() - |> assign(:user, admin) - - {:ok, conn: conn, user: user} + %{user: user} end test "renders user's statuses", %{conn: conn, user: user} do @@ -2631,11 +3054,10 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "GET /api/pleroma/admin/moderation_log" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) + setup do moderator = insert(:user, is_moderator: true) - %{conn: assign(conn, :user, admin), admin: admin, moderator: moderator} + %{moderator: moderator} end test "returns the log", %{conn: conn, admin: admin} do @@ -2840,20 +3262,12 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "PATCH /users/:nickname/force_password_reset" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) + test "sets password_reset_pending to true", %{conn: conn} do user = insert(:user) - - %{conn: assign(conn, :user, admin), admin: admin, user: user} - end - - test "sets password_reset_pending to true", %{admin: admin, user: user} do assert user.password_reset_pending == false conn = - build_conn() - |> assign(:user, admin) - |> patch("/api/pleroma/admin/users/force_password_reset", %{nicknames: [user.nickname]}) + patch(conn, "/api/pleroma/admin/users/force_password_reset", %{nicknames: [user.nickname]}) assert json_response(conn, 204) == "" @@ -2864,17 +3278,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "relays" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) - - %{conn: assign(conn, :user, admin), admin: admin} - end - - test "POST /relay", %{admin: admin} do + test "POST /relay", %{conn: conn, admin: admin} do conn = - build_conn() - |> assign(:user, admin) - |> post("/api/pleroma/admin/relay", %{ + post(conn, "/api/pleroma/admin/relay", %{ relay_url: "http://mastodon.example.org/users/admin" }) @@ -2886,7 +3292,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do "@#{admin.nickname} followed relay: http://mastodon.example.org/users/admin" end - test "GET /relay", %{admin: admin} do + test "GET /relay", %{conn: conn} do relay_user = Pleroma.Web.ActivityPub.Relay.get_actor() ["http://mastodon.example.org/users/admin", "https://mstdn.io/users/mayuutann"] @@ -2895,25 +3301,18 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do User.follow(relay_user, user) end) - conn = - build_conn() - |> assign(:user, admin) - |> get("/api/pleroma/admin/relay") + conn = get(conn, "/api/pleroma/admin/relay") assert json_response(conn, 200)["relays"] -- ["mastodon.example.org", "mstdn.io"] == [] end - test "DELETE /relay", %{admin: admin} do - build_conn() - |> assign(:user, admin) - |> post("/api/pleroma/admin/relay", %{ + test "DELETE /relay", %{conn: conn, admin: admin} do + post(conn, "/api/pleroma/admin/relay", %{ relay_url: "http://mastodon.example.org/users/admin" }) conn = - build_conn() - |> assign(:user, admin) - |> delete("/api/pleroma/admin/relay", %{ + delete(conn, "/api/pleroma/admin/relay", %{ relay_url: "http://mastodon.example.org/users/admin" }) @@ -2930,63 +3329,48 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "instances" do - test "GET /instances/:instance/statuses" do - admin = insert(:user, is_admin: true) + test "GET /instances/:instance/statuses", %{conn: conn} do user = insert(:user, local: false, nickname: "archaeme@archae.me") user2 = insert(:user, local: false, nickname: "test@test.com") insert_pair(:note_activity, user: user) insert(:note_activity, user: user2) - conn = - build_conn() - |> assign(:user, admin) - |> get("/api/pleroma/admin/instances/archae.me/statuses") + ret_conn = get(conn, "/api/pleroma/admin/instances/archae.me/statuses") - response = json_response(conn, 200) + response = json_response(ret_conn, 200) assert length(response) == 2 - conn = - build_conn() - |> assign(:user, admin) - |> get("/api/pleroma/admin/instances/test.com/statuses") + ret_conn = get(conn, "/api/pleroma/admin/instances/test.com/statuses") - response = json_response(conn, 200) + response = json_response(ret_conn, 200) assert length(response) == 1 - conn = - build_conn() - |> assign(:user, admin) - |> get("/api/pleroma/admin/instances/nonexistent.com/statuses") + ret_conn = get(conn, "/api/pleroma/admin/instances/nonexistent.com/statuses") - response = json_response(conn, 200) + response = json_response(ret_conn, 200) - assert length(response) == 0 + assert Enum.empty?(response) end end describe "PATCH /confirm_email" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) - - %{conn: assign(conn, :user, admin), admin: admin} - end - - test "it confirms emails of two users", %{admin: admin} do + test "it confirms emails of two users", %{conn: conn, admin: admin} do [first_user, second_user] = insert_pair(:user, confirmation_pending: true) assert first_user.confirmation_pending == true assert second_user.confirmation_pending == true - build_conn() - |> assign(:user, admin) - |> patch("/api/pleroma/admin/users/confirm_email", %{ - nicknames: [ - first_user.nickname, - second_user.nickname - ] - }) + ret_conn = + patch(conn, "/api/pleroma/admin/users/confirm_email", %{ + nicknames: [ + first_user.nickname, + second_user.nickname + ] + }) + + assert ret_conn.status == 200 assert first_user.confirmation_pending == true assert second_user.confirmation_pending == true @@ -3001,23 +3385,18 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end describe "PATCH /resend_confirmation_email" do - setup %{conn: conn} do - admin = insert(:user, is_admin: true) - - %{conn: assign(conn, :user, admin), admin: admin} - end - - test "it resend emails for two users", %{admin: admin} do + test "it resend emails for two users", %{conn: conn, admin: admin} do [first_user, second_user] = insert_pair(:user, confirmation_pending: true) - build_conn() - |> assign(:user, admin) - |> patch("/api/pleroma/admin/users/resend_confirmation_email", %{ - nicknames: [ - first_user.nickname, - second_user.nickname - ] - }) + ret_conn = + patch(conn, "/api/pleroma/admin/users/resend_confirmation_email", %{ + nicknames: [ + first_user.nickname, + second_user.nickname + ] + }) + + assert ret_conn.status == 200 log_entry = Repo.one(ModerationLog) @@ -3027,6 +3406,81 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do }" end end + + describe "POST /reports/:id/notes" do + setup %{conn: conn, admin: admin} do + [reporter, target_user] = insert_pair(:user) + activity = insert(:note_activity, user: target_user) + + {:ok, %{id: report_id}} = + CommonAPI.report(reporter, %{ + "account_id" => target_user.id, + "comment" => "I feel offended", + "status_ids" => [activity.id] + }) + + post(conn, "/api/pleroma/admin/reports/#{report_id}/notes", %{ + content: "this is disgusting!" + }) + + post(conn, "/api/pleroma/admin/reports/#{report_id}/notes", %{ + content: "this is disgusting2!" + }) + + %{ + admin_id: admin.id, + report_id: report_id + } + end + + test "it creates report note", %{admin_id: admin_id, report_id: report_id} do + [note, _] = Repo.all(ReportNote) + + assert %{ + activity_id: ^report_id, + content: "this is disgusting!", + user_id: ^admin_id + } = note + end + + test "it returns reports with notes", %{conn: conn, admin: admin} do + conn = get(conn, "/api/pleroma/admin/reports") + + response = json_response(conn, 200) + notes = hd(response["reports"])["notes"] + [note, _] = notes + + assert note["user"]["nickname"] == admin.nickname + assert note["content"] == "this is disgusting!" + assert note["created_at"] + assert response["total"] == 1 + end + + test "it deletes the note", %{conn: conn, report_id: report_id} do + assert ReportNote |> Repo.all() |> length() == 2 + + [note, _] = Repo.all(ReportNote) + + delete(conn, "/api/pleroma/admin/reports/#{report_id}/notes/#{note.id}") + + assert ReportNote |> Repo.all() |> length() == 1 + end + end + + test "GET /api/pleroma/admin/config/descriptions", %{conn: conn} do + admin = insert(:user, is_admin: true) + + conn = + assign(conn, :user, admin) + |> get("/api/pleroma/admin/config/descriptions") + + assert [child | _others] = json_response(conn, 200) + + assert child["children"] + assert child["key"] + assert String.starts_with?(child["group"], ":") + assert child["description"] + end end # Needed for testing diff --git a/test/web/admin_api/config_test.exs b/test/web/admin_api/config_test.exs deleted file mode 100644 index 204446b79..000000000 --- a/test/web/admin_api/config_test.exs +++ /dev/null @@ -1,497 +0,0 @@ -# Pleroma: A lightweight social networking server -# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> -# SPDX-License-Identifier: AGPL-3.0-only - -defmodule Pleroma.Web.AdminAPI.ConfigTest do - use Pleroma.DataCase, async: true - import Pleroma.Factory - alias Pleroma.Web.AdminAPI.Config - - test "get_by_key/1" do - config = insert(:config) - insert(:config) - - assert config == Config.get_by_params(%{group: config.group, key: config.key}) - end - - test "create/1" do - {:ok, config} = Config.create(%{group: "pleroma", key: "some_key", value: "some_value"}) - assert config == Config.get_by_params(%{group: "pleroma", key: "some_key"}) - end - - test "update/1" do - config = insert(:config) - {:ok, updated} = Config.update(config, %{value: "some_value"}) - loaded = Config.get_by_params(%{group: config.group, key: config.key}) - assert loaded == updated - end - - test "update_or_create/1" do - config = insert(:config) - key2 = "another_key" - - params = [ - %{group: "pleroma", key: key2, value: "another_value"}, - %{group: config.group, key: config.key, value: "new_value"} - ] - - assert Repo.all(Config) |> length() == 1 - - Enum.each(params, &Config.update_or_create(&1)) - - assert Repo.all(Config) |> length() == 2 - - config1 = Config.get_by_params(%{group: config.group, key: config.key}) - config2 = Config.get_by_params(%{group: "pleroma", key: key2}) - - assert config1.value == Config.transform("new_value") - assert config2.value == Config.transform("another_value") - end - - test "delete/1" do - config = insert(:config) - {:ok, _} = Config.delete(%{key: config.key, group: config.group}) - refute Config.get_by_params(%{key: config.key, group: config.group}) - end - - describe "transform/1" do - test "string" do - binary = Config.transform("value as string") - assert binary == :erlang.term_to_binary("value as string") - assert Config.from_binary(binary) == "value as string" - end - - test "boolean" do - binary = Config.transform(false) - assert binary == :erlang.term_to_binary(false) - assert Config.from_binary(binary) == false - end - - test "nil" do - binary = Config.transform(nil) - assert binary == :erlang.term_to_binary(nil) - assert Config.from_binary(binary) == nil - end - - test "integer" do - binary = Config.transform(150) - assert binary == :erlang.term_to_binary(150) - assert Config.from_binary(binary) == 150 - end - - test "atom" do - binary = Config.transform(":atom") - assert binary == :erlang.term_to_binary(:atom) - assert Config.from_binary(binary) == :atom - end - - test "pleroma module" do - binary = Config.transform("Pleroma.Bookmark") - assert binary == :erlang.term_to_binary(Pleroma.Bookmark) - assert Config.from_binary(binary) == Pleroma.Bookmark - end - - test "phoenix module" do - binary = Config.transform("Phoenix.Socket.V1.JSONSerializer") - assert binary == :erlang.term_to_binary(Phoenix.Socket.V1.JSONSerializer) - assert Config.from_binary(binary) == Phoenix.Socket.V1.JSONSerializer - end - - test "sigil" do - binary = Config.transform("~r/comp[lL][aA][iI][nN]er/") - assert binary == :erlang.term_to_binary(~r/comp[lL][aA][iI][nN]er/) - assert Config.from_binary(binary) == ~r/comp[lL][aA][iI][nN]er/ - end - - test "link sigil" do - binary = Config.transform("~r/https:\/\/example.com/") - assert binary == :erlang.term_to_binary(~r/https:\/\/example.com/) - assert Config.from_binary(binary) == ~r/https:\/\/example.com/ - end - - test "link sigil with u modifier" do - binary = Config.transform("~r/https:\/\/example.com/u") - assert binary == :erlang.term_to_binary(~r/https:\/\/example.com/u) - assert Config.from_binary(binary) == ~r/https:\/\/example.com/u - end - - test "link sigil with i modifier" do - binary = Config.transform("~r/https:\/\/example.com/i") - assert binary == :erlang.term_to_binary(~r/https:\/\/example.com/i) - assert Config.from_binary(binary) == ~r/https:\/\/example.com/i - end - - test "link sigil with s modifier" do - binary = Config.transform("~r/https:\/\/example.com/s") - assert binary == :erlang.term_to_binary(~r/https:\/\/example.com/s) - assert Config.from_binary(binary) == ~r/https:\/\/example.com/s - end - - test "2 child tuple" do - binary = Config.transform(%{"tuple" => ["v1", ":v2"]}) - assert binary == :erlang.term_to_binary({"v1", :v2}) - assert Config.from_binary(binary) == {"v1", :v2} - end - - test "tuple with n childs" do - binary = - Config.transform(%{ - "tuple" => [ - "v1", - ":v2", - "Pleroma.Bookmark", - 150, - false, - "Phoenix.Socket.V1.JSONSerializer" - ] - }) - - assert binary == - :erlang.term_to_binary( - {"v1", :v2, Pleroma.Bookmark, 150, false, Phoenix.Socket.V1.JSONSerializer} - ) - - assert Config.from_binary(binary) == - {"v1", :v2, Pleroma.Bookmark, 150, false, Phoenix.Socket.V1.JSONSerializer} - end - - test "tuple with dispatch key" do - binary = Config.transform(%{"tuple" => [":dispatch", ["{:_, - [ - {\"/api/v1/streaming\", Pleroma.Web.MastodonAPI.WebsocketHandler, []}, - {\"/websocket\", Phoenix.Endpoint.CowboyWebSocket, - {Phoenix.Transports.WebSocket, - {Pleroma.Web.Endpoint, Pleroma.Web.UserSocket, [path: \"/websocket\"]}}}, - {:_, Phoenix.Endpoint.Cowboy2Handler, {Pleroma.Web.Endpoint, []}} - ]}"]]}) - - assert binary == - :erlang.term_to_binary( - {:dispatch, - [ - {:_, - [ - {"/api/v1/streaming", Pleroma.Web.MastodonAPI.WebsocketHandler, []}, - {"/websocket", Phoenix.Endpoint.CowboyWebSocket, - {Phoenix.Transports.WebSocket, - {Pleroma.Web.Endpoint, Pleroma.Web.UserSocket, [path: "/websocket"]}}}, - {:_, Phoenix.Endpoint.Cowboy2Handler, {Pleroma.Web.Endpoint, []}} - ]} - ]} - ) - - assert Config.from_binary(binary) == - {:dispatch, - [ - {:_, - [ - {"/api/v1/streaming", Pleroma.Web.MastodonAPI.WebsocketHandler, []}, - {"/websocket", Phoenix.Endpoint.CowboyWebSocket, - {Phoenix.Transports.WebSocket, - {Pleroma.Web.Endpoint, Pleroma.Web.UserSocket, [path: "/websocket"]}}}, - {:_, Phoenix.Endpoint.Cowboy2Handler, {Pleroma.Web.Endpoint, []}} - ]} - ]} - end - - test "map with string key" do - binary = Config.transform(%{"key" => "value"}) - assert binary == :erlang.term_to_binary(%{"key" => "value"}) - assert Config.from_binary(binary) == %{"key" => "value"} - end - - test "map with atom key" do - binary = Config.transform(%{":key" => "value"}) - assert binary == :erlang.term_to_binary(%{key: "value"}) - assert Config.from_binary(binary) == %{key: "value"} - end - - test "list of strings" do - binary = Config.transform(["v1", "v2", "v3"]) - assert binary == :erlang.term_to_binary(["v1", "v2", "v3"]) - assert Config.from_binary(binary) == ["v1", "v2", "v3"] - end - - test "list of modules" do - binary = Config.transform(["Pleroma.Repo", "Pleroma.Activity"]) - assert binary == :erlang.term_to_binary([Pleroma.Repo, Pleroma.Activity]) - assert Config.from_binary(binary) == [Pleroma.Repo, Pleroma.Activity] - end - - test "list of atoms" do - binary = Config.transform([":v1", ":v2", ":v3"]) - assert binary == :erlang.term_to_binary([:v1, :v2, :v3]) - assert Config.from_binary(binary) == [:v1, :v2, :v3] - end - - test "list of mixed values" do - binary = - Config.transform([ - "v1", - ":v2", - "Pleroma.Repo", - "Phoenix.Socket.V1.JSONSerializer", - 15, - false - ]) - - assert binary == - :erlang.term_to_binary([ - "v1", - :v2, - Pleroma.Repo, - Phoenix.Socket.V1.JSONSerializer, - 15, - false - ]) - - assert Config.from_binary(binary) == [ - "v1", - :v2, - Pleroma.Repo, - Phoenix.Socket.V1.JSONSerializer, - 15, - false - ] - end - - test "simple keyword" do - binary = Config.transform([%{"tuple" => [":key", "value"]}]) - assert binary == :erlang.term_to_binary([{:key, "value"}]) - assert Config.from_binary(binary) == [{:key, "value"}] - assert Config.from_binary(binary) == [key: "value"] - end - - test "keyword with partial_chain key" do - binary = - Config.transform([%{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]}]) - - assert binary == :erlang.term_to_binary(partial_chain: &:hackney_connect.partial_chain/1) - assert Config.from_binary(binary) == [partial_chain: &:hackney_connect.partial_chain/1] - end - - test "keyword" do - binary = - Config.transform([ - %{"tuple" => [":types", "Pleroma.PostgresTypes"]}, - %{"tuple" => [":telemetry_event", ["Pleroma.Repo.Instrumenter"]]}, - %{"tuple" => [":migration_lock", nil]}, - %{"tuple" => [":key1", 150]}, - %{"tuple" => [":key2", "string"]} - ]) - - assert binary == - :erlang.term_to_binary( - types: Pleroma.PostgresTypes, - telemetry_event: [Pleroma.Repo.Instrumenter], - migration_lock: nil, - key1: 150, - key2: "string" - ) - - assert Config.from_binary(binary) == [ - types: Pleroma.PostgresTypes, - telemetry_event: [Pleroma.Repo.Instrumenter], - migration_lock: nil, - key1: 150, - key2: "string" - ] - end - - test "complex keyword with nested mixed childs" do - binary = - Config.transform([ - %{"tuple" => [":uploader", "Pleroma.Uploaders.Local"]}, - %{"tuple" => [":filters", ["Pleroma.Upload.Filter.Dedupe"]]}, - %{"tuple" => [":link_name", true]}, - %{"tuple" => [":proxy_remote", false]}, - %{"tuple" => [":common_map", %{":key" => "value"}]}, - %{ - "tuple" => [ - ":proxy_opts", - [ - %{"tuple" => [":redirect_on_failure", false]}, - %{"tuple" => [":max_body_length", 1_048_576]}, - %{ - "tuple" => [ - ":http", - [%{"tuple" => [":follow_redirect", true]}, %{"tuple" => [":pool", ":upload"]}] - ] - } - ] - ] - } - ]) - - assert binary == - :erlang.term_to_binary( - uploader: Pleroma.Uploaders.Local, - filters: [Pleroma.Upload.Filter.Dedupe], - link_name: true, - proxy_remote: false, - common_map: %{key: "value"}, - proxy_opts: [ - redirect_on_failure: false, - max_body_length: 1_048_576, - http: [ - follow_redirect: true, - pool: :upload - ] - ] - ) - - assert Config.from_binary(binary) == - [ - uploader: Pleroma.Uploaders.Local, - filters: [Pleroma.Upload.Filter.Dedupe], - link_name: true, - proxy_remote: false, - common_map: %{key: "value"}, - proxy_opts: [ - redirect_on_failure: false, - max_body_length: 1_048_576, - http: [ - follow_redirect: true, - pool: :upload - ] - ] - ] - end - - test "common keyword" do - binary = - Config.transform([ - %{"tuple" => [":level", ":warn"]}, - %{"tuple" => [":meta", [":all"]]}, - %{"tuple" => [":path", ""]}, - %{"tuple" => [":val", nil]}, - %{"tuple" => [":webhook_url", "https://hooks.slack.com/services/YOUR-KEY-HERE"]} - ]) - - assert binary == - :erlang.term_to_binary( - level: :warn, - meta: [:all], - path: "", - val: nil, - webhook_url: "https://hooks.slack.com/services/YOUR-KEY-HERE" - ) - - assert Config.from_binary(binary) == [ - level: :warn, - meta: [:all], - path: "", - val: nil, - webhook_url: "https://hooks.slack.com/services/YOUR-KEY-HERE" - ] - end - - test "complex keyword with sigil" do - binary = - Config.transform([ - %{"tuple" => [":federated_timeline_removal", []]}, - %{"tuple" => [":reject", ["~r/comp[lL][aA][iI][nN]er/"]]}, - %{"tuple" => [":replace", []]} - ]) - - assert binary == - :erlang.term_to_binary( - federated_timeline_removal: [], - reject: [~r/comp[lL][aA][iI][nN]er/], - replace: [] - ) - - assert Config.from_binary(binary) == - [federated_timeline_removal: [], reject: [~r/comp[lL][aA][iI][nN]er/], replace: []] - end - - test "complex keyword with tuples with more than 2 values" do - binary = - Config.transform([ - %{ - "tuple" => [ - ":http", - [ - %{ - "tuple" => [ - ":key1", - [ - %{ - "tuple" => [ - ":_", - [ - %{ - "tuple" => [ - "/api/v1/streaming", - "Pleroma.Web.MastodonAPI.WebsocketHandler", - [] - ] - }, - %{ - "tuple" => [ - "/websocket", - "Phoenix.Endpoint.CowboyWebSocket", - %{ - "tuple" => [ - "Phoenix.Transports.WebSocket", - %{ - "tuple" => [ - "Pleroma.Web.Endpoint", - "Pleroma.Web.UserSocket", - [] - ] - } - ] - } - ] - }, - %{ - "tuple" => [ - ":_", - "Phoenix.Endpoint.Cowboy2Handler", - %{"tuple" => ["Pleroma.Web.Endpoint", []]} - ] - } - ] - ] - } - ] - ] - } - ] - ] - } - ]) - - assert binary == - :erlang.term_to_binary( - http: [ - key1: [ - _: [ - {"/api/v1/streaming", Pleroma.Web.MastodonAPI.WebsocketHandler, []}, - {"/websocket", Phoenix.Endpoint.CowboyWebSocket, - {Phoenix.Transports.WebSocket, - {Pleroma.Web.Endpoint, Pleroma.Web.UserSocket, []}}}, - {:_, Phoenix.Endpoint.Cowboy2Handler, {Pleroma.Web.Endpoint, []}} - ] - ] - ] - ) - - assert Config.from_binary(binary) == [ - http: [ - key1: [ - {:_, - [ - {"/api/v1/streaming", Pleroma.Web.MastodonAPI.WebsocketHandler, []}, - {"/websocket", Phoenix.Endpoint.CowboyWebSocket, - {Phoenix.Transports.WebSocket, - {Pleroma.Web.Endpoint, Pleroma.Web.UserSocket, []}}}, - {:_, Phoenix.Endpoint.Cowboy2Handler, {Pleroma.Web.Endpoint, []}} - ]} - ] - ] - ] - end - end -end diff --git a/test/web/admin_api/views/report_view_test.exs b/test/web/admin_api/views/report_view_test.exs index ef4a806e4..a0c6eab3c 100644 --- a/test/web/admin_api/views/report_view_test.exs +++ b/test/web/admin_api/views/report_view_test.exs @@ -30,6 +30,7 @@ defmodule Pleroma.Web.AdminAPI.ReportViewTest do Pleroma.Web.AdminAPI.AccountView.render("show.json", %{user: other_user}) ), statuses: [], + notes: [], state: "open", id: activity.id } @@ -65,6 +66,7 @@ defmodule Pleroma.Web.AdminAPI.ReportViewTest do ), statuses: [StatusView.render("show.json", %{activity: activity})], state: "open", + notes: [], id: report_activity.id } diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs index b5d6d4055..f8963e42e 100644 --- a/test/web/common_api/common_api_test.exs +++ b/test/web/common_api/common_api_test.exs @@ -284,22 +284,22 @@ defmodule Pleroma.Web.CommonAPITest do {:ok, %Activity{}, _} = CommonAPI.favorite(activity.id, user) end - test "retweeting a status twice returns an error" do + test "retweeting a status twice returns the status" do user = insert(:user) other_user = insert(:user) {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"}) - {:ok, %Activity{}, _object} = CommonAPI.repeat(activity.id, user) - {:error, _} = CommonAPI.repeat(activity.id, user) + {:ok, %Activity{} = activity, object} = CommonAPI.repeat(activity.id, user) + {:ok, ^activity, ^object} = CommonAPI.repeat(activity.id, user) end - test "favoriting a status twice returns an error" do + test "favoriting a status twice returns the status" do user = insert(:user) other_user = insert(:user) {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"}) - {:ok, %Activity{}, _object} = CommonAPI.favorite(activity.id, user) - {:error, _} = CommonAPI.favorite(activity.id, user) + {:ok, %Activity{} = activity, object} = CommonAPI.favorite(activity.id, user) + {:ok, ^activity, ^object} = CommonAPI.favorite(activity.id, user) end end diff --git a/test/web/common_api/common_api_utils_test.exs b/test/web/common_api/common_api_utils_test.exs index 2588898d0..4b761e039 100644 --- a/test/web/common_api/common_api_utils_test.exs +++ b/test/web/common_api/common_api_utils_test.exs @@ -307,7 +307,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do {to, cc} = Utils.get_to_and_cc(user, mentions, nil, "private", nil) assert length(to) == 2 - assert length(cc) == 0 + assert Enum.empty?(cc) assert mentioned_user.ap_id in to assert user.follower_address in to @@ -323,7 +323,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do {to, cc} = Utils.get_to_and_cc(user, mentions, activity, "private", nil) assert length(to) == 3 - assert length(cc) == 0 + assert Enum.empty?(cc) assert mentioned_user.ap_id in to assert third_user.ap_id in to @@ -338,7 +338,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do {to, cc} = Utils.get_to_and_cc(user, mentions, nil, "direct", nil) assert length(to) == 1 - assert length(cc) == 0 + assert Enum.empty?(cc) assert mentioned_user.ap_id in to end @@ -353,7 +353,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do {to, cc} = Utils.get_to_and_cc(user, mentions, activity, "direct", nil) assert length(to) == 2 - assert length(cc) == 0 + assert Enum.empty?(cc) assert mentioned_user.ap_id in to assert third_user.ap_id in to diff --git a/test/web/masto_fe_controller_test.exs b/test/web/masto_fe_controller_test.exs index b5dbd4a25..f9870a852 100644 --- a/test/web/masto_fe_controller_test.exs +++ b/test/web/masto_fe_controller_test.exs @@ -18,6 +18,7 @@ defmodule Pleroma.Web.MastodonAPI.MastoFEController do conn = conn |> assign(:user, user) + |> assign(:token, insert(:oauth_token, user: user, scopes: ["write:accounts"])) |> put("/api/web/settings", %{"data" => %{"programming" => "socks"}}) assert _result = json_response(conn, 200) @@ -63,12 +64,12 @@ defmodule Pleroma.Web.MastodonAPI.MastoFEController do end test "does not redirect logged in users to the login page", %{conn: conn, path: path} do - token = insert(:oauth_token) + token = insert(:oauth_token, scopes: ["read"]) conn = conn |> assign(:user, token.user) - |> put_session(:oauth_token, token.token) + |> assign(:token, token) |> get(path) assert conn.status == 200 diff --git a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs index 77cfce4fa..09bdc46e0 100644 --- a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs +++ b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs @@ -12,13 +12,11 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do clear_config([:instance, :max_account_fields]) describe "updating credentials" do - test "sets user settings in a generic way", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["write:accounts"]) + test "sets user settings in a generic way", %{conn: conn} do res_conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{ + patch(conn, "/api/v1/accounts/update_credentials", %{ "pleroma_settings_store" => %{ pleroma_fe: %{ theme: "bla" @@ -26,10 +24,10 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do } }) - assert user = json_response(res_conn, 200) - assert user["pleroma"]["settings_store"] == %{"pleroma_fe" => %{"theme" => "bla"}} + assert user_data = json_response(res_conn, 200) + assert user_data["pleroma"]["settings_store"] == %{"pleroma_fe" => %{"theme" => "bla"}} - user = Repo.get(User, user["id"]) + user = Repo.get(User, user_data["id"]) res_conn = conn @@ -42,15 +40,15 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do } }) - assert user = json_response(res_conn, 200) + assert user_data = json_response(res_conn, 200) - assert user["pleroma"]["settings_store"] == + assert user_data["pleroma"]["settings_store"] == %{ "pleroma_fe" => %{"theme" => "bla"}, "masto_fe" => %{"theme" => "bla"} } - user = Repo.get(User, user["id"]) + user = Repo.get(User, user_data["id"]) res_conn = conn @@ -63,9 +61,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do } }) - assert user = json_response(res_conn, 200) + assert user_data = json_response(res_conn, 200) - assert user["pleroma"]["settings_store"] == + assert user_data["pleroma"]["settings_store"] == %{ "pleroma_fe" => %{"theme" => "bla"}, "masto_fe" => %{"theme" => "blub"} @@ -73,97 +71,67 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do end test "updates the user's bio", %{conn: conn} do - user = insert(:user) user2 = insert(:user) conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{ + patch(conn, "/api/v1/accounts/update_credentials", %{ "note" => "I drink #cofe with @#{user2.nickname}" }) - assert user = json_response(conn, 200) + assert user_data = json_response(conn, 200) - assert user["note"] == + assert user_data["note"] == ~s(I drink <a class="hashtag" data-tag="cofe" href="http://localhost:4001/tag/cofe">#cofe</a> with <span class="h-card"><a data-user="#{ user2.id }" class="u-url mention" href="#{user2.ap_id}" rel="ugc">@<span>#{user2.nickname}</span></a></span>) end test "updates the user's locking status", %{conn: conn} do - user = insert(:user) + conn = patch(conn, "/api/v1/accounts/update_credentials", %{locked: "true"}) - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{locked: "true"}) - - assert user = json_response(conn, 200) - assert user["locked"] == true + assert user_data = json_response(conn, 200) + assert user_data["locked"] == true end - test "updates the user's allow_following_move", %{conn: conn} do - user = insert(:user) - + test "updates the user's allow_following_move", %{user: user, conn: conn} do assert user.allow_following_move == true - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{allow_following_move: "false"}) + conn = patch(conn, "/api/v1/accounts/update_credentials", %{allow_following_move: "false"}) assert refresh_record(user).allow_following_move == false - assert user = json_response(conn, 200) - assert user["pleroma"]["allow_following_move"] == false + assert user_data = json_response(conn, 200) + assert user_data["pleroma"]["allow_following_move"] == false end test "updates the user's default scope", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{default_scope: "cofe"}) + conn = patch(conn, "/api/v1/accounts/update_credentials", %{default_scope: "cofe"}) - assert user = json_response(conn, 200) - assert user["source"]["privacy"] == "cofe" + assert user_data = json_response(conn, 200) + assert user_data["source"]["privacy"] == "cofe" end test "updates the user's hide_followers status", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{hide_followers: "true"}) + conn = patch(conn, "/api/v1/accounts/update_credentials", %{hide_followers: "true"}) - assert user = json_response(conn, 200) - assert user["pleroma"]["hide_followers"] == true + assert user_data = json_response(conn, 200) + assert user_data["pleroma"]["hide_followers"] == true end test "updates the user's hide_followers_count and hide_follows_count", %{conn: conn} do - user = insert(:user) - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{ + patch(conn, "/api/v1/accounts/update_credentials", %{ hide_followers_count: "true", hide_follows_count: "true" }) - assert user = json_response(conn, 200) - assert user["pleroma"]["hide_followers_count"] == true - assert user["pleroma"]["hide_follows_count"] == true + assert user_data = json_response(conn, 200) + assert user_data["pleroma"]["hide_followers_count"] == true + assert user_data["pleroma"]["hide_follows_count"] == true end - test "updates the user's skip_thread_containment option", %{conn: conn} do - user = insert(:user) - + test "updates the user's skip_thread_containment option", %{user: user, conn: conn} do response = conn - |> assign(:user, user) |> patch("/api/v1/accounts/update_credentials", %{skip_thread_containment: "true"}) |> json_response(200) @@ -172,104 +140,68 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do end test "updates the user's hide_follows status", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{hide_follows: "true"}) + conn = patch(conn, "/api/v1/accounts/update_credentials", %{hide_follows: "true"}) - assert user = json_response(conn, 200) - assert user["pleroma"]["hide_follows"] == true + assert user_data = json_response(conn, 200) + assert user_data["pleroma"]["hide_follows"] == true end test "updates the user's hide_favorites status", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{hide_favorites: "true"}) + conn = patch(conn, "/api/v1/accounts/update_credentials", %{hide_favorites: "true"}) - assert user = json_response(conn, 200) - assert user["pleroma"]["hide_favorites"] == true + assert user_data = json_response(conn, 200) + assert user_data["pleroma"]["hide_favorites"] == true end test "updates the user's show_role status", %{conn: conn} do - user = insert(:user) + conn = patch(conn, "/api/v1/accounts/update_credentials", %{show_role: "false"}) - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{show_role: "false"}) - - assert user = json_response(conn, 200) - assert user["source"]["pleroma"]["show_role"] == false + assert user_data = json_response(conn, 200) + assert user_data["source"]["pleroma"]["show_role"] == false end test "updates the user's no_rich_text status", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{no_rich_text: "true"}) + conn = patch(conn, "/api/v1/accounts/update_credentials", %{no_rich_text: "true"}) - assert user = json_response(conn, 200) - assert user["source"]["pleroma"]["no_rich_text"] == true + assert user_data = json_response(conn, 200) + assert user_data["source"]["pleroma"]["no_rich_text"] == true end test "updates the user's name", %{conn: conn} do - user = insert(:user) - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{"display_name" => "markorepairs"}) + patch(conn, "/api/v1/accounts/update_credentials", %{"display_name" => "markorepairs"}) - assert user = json_response(conn, 200) - assert user["display_name"] == "markorepairs" + assert user_data = json_response(conn, 200) + assert user_data["display_name"] == "markorepairs" end - test "updates the user's avatar", %{conn: conn} do - user = insert(:user) - + test "updates the user's avatar", %{user: user, conn: conn} do new_avatar = %Plug.Upload{ content_type: "image/jpg", path: Path.absname("test/fixtures/image.jpg"), filename: "an_image.jpg" } - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{"avatar" => new_avatar}) + conn = patch(conn, "/api/v1/accounts/update_credentials", %{"avatar" => new_avatar}) assert user_response = json_response(conn, 200) assert user_response["avatar"] != User.avatar_url(user) end - test "updates the user's banner", %{conn: conn} do - user = insert(:user) - + test "updates the user's banner", %{user: user, conn: conn} do new_header = %Plug.Upload{ content_type: "image/jpg", path: Path.absname("test/fixtures/image.jpg"), filename: "an_image.jpg" } - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{"header" => new_header}) + conn = patch(conn, "/api/v1/accounts/update_credentials", %{"header" => new_header}) assert user_response = json_response(conn, 200) assert user_response["header"] != User.banner_url(user) end test "updates the user's background", %{conn: conn} do - user = insert(:user) - new_header = %Plug.Upload{ content_type: "image/jpg", path: Path.absname("test/fixtures/image.jpg"), @@ -277,9 +209,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do } conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{ + patch(conn, "/api/v1/accounts/update_credentials", %{ "pleroma_background_image" => new_header }) @@ -287,13 +217,13 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do assert user_response["pleroma"]["background_image"] end - test "requires 'write:accounts' permission", %{conn: conn} do + test "requires 'write:accounts' permission" do token1 = insert(:oauth_token, scopes: ["read"]) token2 = insert(:oauth_token, scopes: ["write", "follow"]) for token <- [token1, token2] do conn = - conn + build_conn() |> put_req_header("authorization", "Bearer #{token.token}") |> patch("/api/v1/accounts/update_credentials", %{}) @@ -306,53 +236,44 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do end end - test "updates profile emojos", %{conn: conn} do - user = insert(:user) - + test "updates profile emojos", %{user: user, conn: conn} do note = "*sips :blank:*" name = "I am :firefox:" - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{ + ret_conn = + patch(conn, "/api/v1/accounts/update_credentials", %{ "note" => note, "display_name" => name }) - assert json_response(conn, 200) + assert json_response(ret_conn, 200) - conn = - conn - |> get("/api/v1/accounts/#{user.id}") + conn = get(conn, "/api/v1/accounts/#{user.id}") - assert user = json_response(conn, 200) + assert user_data = json_response(conn, 200) - assert user["note"] == note - assert user["display_name"] == name - assert [%{"shortcode" => "blank"}, %{"shortcode" => "firefox"}] = user["emojis"] + assert user_data["note"] == note + assert user_data["display_name"] == name + assert [%{"shortcode" => "blank"}, %{"shortcode" => "firefox"}] = user_data["emojis"] end test "update fields", %{conn: conn} do - user = insert(:user) - fields = [ %{"name" => "<a href=\"http://google.com\">foo</a>", "value" => "<script>bar</script>"}, %{"name" => "link", "value" => "cofe.io"} ] - account = + account_data = conn - |> assign(:user, user) |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields}) |> json_response(200) - assert account["fields"] == [ + assert account_data["fields"] == [ %{"name" => "foo", "value" => "bar"}, %{"name" => "link", "value" => ~S(<a href="http://cofe.io" rel="ugc">cofe.io</a>)} ] - assert account["source"]["fields"] == [ + assert account_data["source"]["fields"] == [ %{ "name" => "<a href=\"http://google.com\">foo</a>", "value" => "<script>bar</script>" @@ -372,7 +293,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do account = conn |> put_req_header("content-type", "application/x-www-form-urlencoded") - |> assign(:user, user) |> patch("/api/v1/accounts/update_credentials", fields) |> json_response(200) @@ -398,7 +318,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do assert %{"error" => "Invalid request"} == conn - |> assign(:user, user) |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields}) |> json_response(403) @@ -408,7 +327,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do assert %{"error" => "Invalid request"} == conn - |> assign(:user, user) |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields}) |> json_response(403) @@ -421,7 +339,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do assert %{"error" => "Invalid request"} == conn - |> assign(:user, user) |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields}) |> json_response(403) @@ -432,7 +349,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do account = conn - |> assign(:user, user) |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields}) |> json_response(200) diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs index fa08ae4df..0d4860a42 100644 --- a/test/web/mastodon_api/controllers/account_controller_test.exs +++ b/test/web/mastodon_api/controllers/account_controller_test.exs @@ -87,6 +87,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do conn = build_conn() |> assign(:user, reading_user) + |> assign(:token, insert(:oauth_token, user: reading_user, scopes: ["read:accounts"])) |> get("/api/v1/accounts/#{user.nickname}") Pleroma.Config.put([:instance, :limit_to_local_content], limit_to_local) @@ -144,8 +145,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end describe "user timelines" do - test "respects blocks", %{conn: conn} do - user_one = insert(:user) + setup do: oauth_access(["read:statuses"]) + + test "respects blocks", %{user: user_one, conn: conn} do user_two = insert(:user) user_three = insert(:user) @@ -154,46 +156,35 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do {:ok, activity} = CommonAPI.post(user_two, %{"status" => "User one sux0rz"}) {:ok, repeat, _} = CommonAPI.repeat(activity.id, user_three) - resp = - conn - |> get("/api/v1/accounts/#{user_two.id}/statuses") + resp = get(conn, "/api/v1/accounts/#{user_two.id}/statuses") assert [%{"id" => id}] = json_response(resp, 200) assert id == activity.id # Even a blocked user will deliver the full user timeline, there would be - # no point in looking at a blocked users timeline otherwise - resp = - conn - |> assign(:user, user_one) - |> get("/api/v1/accounts/#{user_two.id}/statuses") + # no point in looking at a blocked users timeline otherwise + resp = get(conn, "/api/v1/accounts/#{user_two.id}/statuses") assert [%{"id" => id}] = json_response(resp, 200) assert id == activity.id - resp = - conn - |> get("/api/v1/accounts/#{user_three.id}/statuses") - + # Third user's timeline includes the repeat when viewed by unauthenticated user + resp = get(build_conn(), "/api/v1/accounts/#{user_three.id}/statuses") assert [%{"id" => id}] = json_response(resp, 200) assert id == repeat.id - # When viewing a third user's timeline, the blocked users will NOT be - # shown. - resp = - conn - |> assign(:user, user_one) - |> get("/api/v1/accounts/#{user_three.id}/statuses") + # When viewing a third user's timeline, the blocked users' statuses will NOT be shown + resp = get(conn, "/api/v1/accounts/#{user_three.id}/statuses") assert [] = json_response(resp, 200) end - test "gets a users statuses", %{conn: conn} do + test "gets users statuses", %{conn: conn} do user_one = insert(:user) user_two = insert(:user) user_three = insert(:user) - {:ok, user_three} = User.follow(user_three, user_one) + {:ok, _user_three} = User.follow(user_three, user_one) {:ok, activity} = CommonAPI.post(user_one, %{"status" => "HI!!!"}) @@ -206,9 +197,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do {:ok, private_activity} = CommonAPI.post(user_one, %{"status" => "private", "visibility" => "private"}) - resp = - conn - |> get("/api/v1/accounts/#{user_one.id}/statuses") + resp = get(conn, "/api/v1/accounts/#{user_one.id}/statuses") assert [%{"id" => id}] = json_response(resp, 200) assert id == to_string(activity.id) @@ -216,6 +205,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do resp = conn |> assign(:user, user_two) + |> assign(:token, insert(:oauth_token, user: user_two, scopes: ["read:statuses"])) |> get("/api/v1/accounts/#{user_one.id}/statuses") assert [%{"id" => id_one}, %{"id" => id_two}] = json_response(resp, 200) @@ -225,6 +215,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do resp = conn |> assign(:user, user_three) + |> assign(:token, insert(:oauth_token, user: user_three, scopes: ["read:statuses"])) |> get("/api/v1/accounts/#{user_one.id}/statuses") assert [%{"id" => id_one}, %{"id" => id_two}] = json_response(resp, 200) @@ -236,9 +227,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do note = insert(:note_activity) user = User.get_cached_by_ap_id(note.data["actor"]) - conn = - conn - |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true") + conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?pinned=true") assert json_response(conn, 200) == [] end @@ -257,63 +246,51 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do {:ok, image_post} = CommonAPI.post(user, %{"status" => "cofe", "media_ids" => [media_id]}) - conn = - conn - |> get("/api/v1/accounts/#{user.id}/statuses", %{"only_media" => "true"}) + conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"only_media" => "true"}) assert [%{"id" => id}] = json_response(conn, 200) assert id == to_string(image_post.id) - conn = - build_conn() - |> get("/api/v1/accounts/#{user.id}/statuses", %{"only_media" => "1"}) + conn = get(build_conn(), "/api/v1/accounts/#{user.id}/statuses", %{"only_media" => "1"}) assert [%{"id" => id}] = json_response(conn, 200) assert id == to_string(image_post.id) end - test "gets a user's statuses without reblogs", %{conn: conn} do - user = insert(:user) + test "gets a user's statuses without reblogs", %{user: user, conn: conn} do {:ok, post} = CommonAPI.post(user, %{"status" => "HI!!!"}) {:ok, _, _} = CommonAPI.repeat(post.id, user) - conn = - conn - |> get("/api/v1/accounts/#{user.id}/statuses", %{"exclude_reblogs" => "true"}) + conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"exclude_reblogs" => "true"}) assert [%{"id" => id}] = json_response(conn, 200) assert id == to_string(post.id) - conn = - conn - |> get("/api/v1/accounts/#{user.id}/statuses", %{"exclude_reblogs" => "1"}) + conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"exclude_reblogs" => "1"}) assert [%{"id" => id}] = json_response(conn, 200) assert id == to_string(post.id) end - test "filters user's statuses by a hashtag", %{conn: conn} do - user = insert(:user) + test "filters user's statuses by a hashtag", %{user: user, conn: conn} do {:ok, post} = CommonAPI.post(user, %{"status" => "#hashtag"}) {:ok, _post} = CommonAPI.post(user, %{"status" => "hashtag"}) - conn = - conn - |> get("/api/v1/accounts/#{user.id}/statuses", %{"tagged" => "hashtag"}) + conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"tagged" => "hashtag"}) assert [%{"id" => id}] = json_response(conn, 200) assert id == to_string(post.id) end - test "the user views their own timelines and excludes direct messages", %{conn: conn} do - user = insert(:user) + test "the user views their own timelines and excludes direct messages", %{ + user: user, + conn: conn + } do {:ok, public_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "public"}) {:ok, _direct_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"}) conn = - conn - |> assign(:user, user) - |> get("/api/v1/accounts/#{user.id}/statuses", %{"exclude_visibilities" => ["direct"]}) + get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"exclude_visibilities" => ["direct"]}) assert [%{"id" => id}] = json_response(conn, 200) assert id == to_string(public_activity.id) @@ -321,46 +298,42 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end describe "followers" do - test "getting followers", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["read:accounts"]) + + test "getting followers", %{user: user, conn: conn} do other_user = insert(:user) {:ok, user} = User.follow(user, other_user) - conn = - conn - |> get("/api/v1/accounts/#{other_user.id}/followers") + conn = get(conn, "/api/v1/accounts/#{other_user.id}/followers") assert [%{"id" => id}] = json_response(conn, 200) assert id == to_string(user.id) end - test "getting followers, hide_followers", %{conn: conn} do - user = insert(:user) + test "getting followers, hide_followers", %{user: user, conn: conn} do other_user = insert(:user, hide_followers: true) {:ok, _user} = User.follow(user, other_user) - conn = - conn - |> get("/api/v1/accounts/#{other_user.id}/followers") + conn = get(conn, "/api/v1/accounts/#{other_user.id}/followers") assert [] == json_response(conn, 200) end - test "getting followers, hide_followers, same user requesting", %{conn: conn} do + test "getting followers, hide_followers, same user requesting" do user = insert(:user) other_user = insert(:user, hide_followers: true) {:ok, _user} = User.follow(user, other_user) conn = - conn + build_conn() |> assign(:user, other_user) + |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"])) |> get("/api/v1/accounts/#{other_user.id}/followers") refute [] == json_response(conn, 200) end - test "getting followers, pagination", %{conn: conn} do - user = insert(:user) + test "getting followers, pagination", %{user: user, conn: conn} do follower1 = insert(:user) follower2 = insert(:user) follower3 = insert(:user) @@ -368,29 +341,19 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do {:ok, _} = User.follow(follower2, user) {:ok, _} = User.follow(follower3, user) - conn = - conn - |> assign(:user, user) - - res_conn = - conn - |> get("/api/v1/accounts/#{user.id}/followers?since_id=#{follower1.id}") + res_conn = get(conn, "/api/v1/accounts/#{user.id}/followers?since_id=#{follower1.id}") assert [%{"id" => id3}, %{"id" => id2}] = json_response(res_conn, 200) assert id3 == follower3.id assert id2 == follower2.id - res_conn = - conn - |> get("/api/v1/accounts/#{user.id}/followers?max_id=#{follower3.id}") + res_conn = get(conn, "/api/v1/accounts/#{user.id}/followers?max_id=#{follower3.id}") assert [%{"id" => id2}, %{"id" => id1}] = json_response(res_conn, 200) assert id2 == follower2.id assert id1 == follower1.id - res_conn = - conn - |> get("/api/v1/accounts/#{user.id}/followers?limit=1&max_id=#{follower3.id}") + res_conn = get(conn, "/api/v1/accounts/#{user.id}/followers?limit=1&max_id=#{follower3.id}") assert [%{"id" => id2}] = json_response(res_conn, 200) assert id2 == follower2.id @@ -402,46 +365,47 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end describe "following" do - test "getting following", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["read:accounts"]) + + test "getting following", %{user: user, conn: conn} do other_user = insert(:user) {:ok, user} = User.follow(user, other_user) - conn = - conn - |> get("/api/v1/accounts/#{user.id}/following") + conn = get(conn, "/api/v1/accounts/#{user.id}/following") assert [%{"id" => id}] = json_response(conn, 200) assert id == to_string(other_user.id) end - test "getting following, hide_follows", %{conn: conn} do + test "getting following, hide_follows, other user requesting" do user = insert(:user, hide_follows: true) other_user = insert(:user) {:ok, user} = User.follow(user, other_user) conn = - conn + build_conn() + |> assign(:user, other_user) + |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"])) |> get("/api/v1/accounts/#{user.id}/following") assert [] == json_response(conn, 200) end - test "getting following, hide_follows, same user requesting", %{conn: conn} do + test "getting following, hide_follows, same user requesting" do user = insert(:user, hide_follows: true) other_user = insert(:user) {:ok, user} = User.follow(user, other_user) conn = - conn + build_conn() |> assign(:user, user) + |> assign(:token, insert(:oauth_token, user: user, scopes: ["read:accounts"])) |> get("/api/v1/accounts/#{user.id}/following") refute [] == json_response(conn, 200) end - test "getting following, pagination", %{conn: conn} do - user = insert(:user) + test "getting following, pagination", %{user: user, conn: conn} do following1 = insert(:user) following2 = insert(:user) following3 = insert(:user) @@ -449,29 +413,20 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do {:ok, _} = User.follow(user, following2) {:ok, _} = User.follow(user, following3) - conn = - conn - |> assign(:user, user) - - res_conn = - conn - |> get("/api/v1/accounts/#{user.id}/following?since_id=#{following1.id}") + res_conn = get(conn, "/api/v1/accounts/#{user.id}/following?since_id=#{following1.id}") assert [%{"id" => id3}, %{"id" => id2}] = json_response(res_conn, 200) assert id3 == following3.id assert id2 == following2.id - res_conn = - conn - |> get("/api/v1/accounts/#{user.id}/following?max_id=#{following3.id}") + res_conn = get(conn, "/api/v1/accounts/#{user.id}/following?max_id=#{following3.id}") assert [%{"id" => id2}, %{"id" => id1}] = json_response(res_conn, 200) assert id2 == following2.id assert id1 == following1.id res_conn = - conn - |> get("/api/v1/accounts/#{user.id}/following?limit=1&max_id=#{following3.id}") + get(conn, "/api/v1/accounts/#{user.id}/following?limit=1&max_id=#{following3.id}") assert [%{"id" => id2}] = json_response(res_conn, 200) assert id2 == following2.id @@ -483,82 +438,52 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end describe "follow/unfollow" do + setup do: oauth_access(["follow"]) + test "following / unfollowing a user", %{conn: conn} do - user = insert(:user) other_user = insert(:user) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/accounts/#{other_user.id}/follow") - - assert %{"id" => _id, "following" => true} = json_response(conn, 200) + ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/follow") - user = User.get_cached_by_id(user.id) + assert %{"id" => _id, "following" => true} = json_response(ret_conn, 200) - conn = - build_conn() - |> assign(:user, user) - |> post("/api/v1/accounts/#{other_user.id}/unfollow") + ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/unfollow") - assert %{"id" => _id, "following" => false} = json_response(conn, 200) + assert %{"id" => _id, "following" => false} = json_response(ret_conn, 200) - user = User.get_cached_by_id(user.id) - - conn = - build_conn() - |> assign(:user, user) - |> post("/api/v1/follows", %{"uri" => other_user.nickname}) + conn = post(conn, "/api/v1/follows", %{"uri" => other_user.nickname}) assert %{"id" => id} = json_response(conn, 200) assert id == to_string(other_user.id) end test "following without reblogs" do - follower = insert(:user) + %{conn: conn} = oauth_access(["follow", "read:statuses"]) followed = insert(:user) other_user = insert(:user) - conn = - build_conn() - |> assign(:user, follower) - |> post("/api/v1/accounts/#{followed.id}/follow?reblogs=false") + ret_conn = post(conn, "/api/v1/accounts/#{followed.id}/follow?reblogs=false") - assert %{"showing_reblogs" => false} = json_response(conn, 200) + assert %{"showing_reblogs" => false} = json_response(ret_conn, 200) {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hey"}) {:ok, reblog, _} = CommonAPI.repeat(activity.id, followed) - conn = - build_conn() - |> assign(:user, User.get_cached_by_id(follower.id)) - |> get("/api/v1/timelines/home") + ret_conn = get(conn, "/api/v1/timelines/home") - assert [] == json_response(conn, 200) + assert [] == json_response(ret_conn, 200) - conn = - build_conn() - |> assign(:user, User.get_cached_by_id(follower.id)) - |> post("/api/v1/accounts/#{followed.id}/follow?reblogs=true") + ret_conn = post(conn, "/api/v1/accounts/#{followed.id}/follow?reblogs=true") - assert %{"showing_reblogs" => true} = json_response(conn, 200) + assert %{"showing_reblogs" => true} = json_response(ret_conn, 200) - conn = - build_conn() - |> assign(:user, User.get_cached_by_id(follower.id)) - |> get("/api/v1/timelines/home") + conn = get(conn, "/api/v1/timelines/home") expected_activity_id = reblog.id assert [%{"id" => ^expected_activity_id}] = json_response(conn, 200) end - test "following / unfollowing errors" do - user = insert(:user) - - conn = - build_conn() - |> assign(:user, user) - + test "following / unfollowing errors", %{user: user, conn: conn} do # self follow conn_res = post(conn, "/api/v1/accounts/#{user.id}/follow") assert %{"error" => "Record not found"} = json_response(conn_res, 404) @@ -588,47 +513,34 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end describe "mute/unmute" do + setup do: oauth_access(["write:mutes"]) + test "with notifications", %{conn: conn} do - user = insert(:user) other_user = insert(:user) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/accounts/#{other_user.id}/mute") + ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/mute") - response = json_response(conn, 200) + response = json_response(ret_conn, 200) assert %{"id" => _id, "muting" => true, "muting_notifications" => true} = response - user = User.get_cached_by_id(user.id) - conn = - build_conn() - |> assign(:user, user) - |> post("/api/v1/accounts/#{other_user.id}/unmute") + conn = post(conn, "/api/v1/accounts/#{other_user.id}/unmute") response = json_response(conn, 200) assert %{"id" => _id, "muting" => false, "muting_notifications" => false} = response end test "without notifications", %{conn: conn} do - user = insert(:user) other_user = insert(:user) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/accounts/#{other_user.id}/mute", %{"notifications" => "false"}) + ret_conn = + post(conn, "/api/v1/accounts/#{other_user.id}/mute", %{"notifications" => "false"}) - response = json_response(conn, 200) + response = json_response(ret_conn, 200) assert %{"id" => _id, "muting" => true, "muting_notifications" => false} = response - user = User.get_cached_by_id(user.id) - conn = - build_conn() - |> assign(:user, user) - |> post("/api/v1/accounts/#{other_user.id}/unmute") + conn = post(conn, "/api/v1/accounts/#{other_user.id}/unmute") response = json_response(conn, 200) assert %{"id" => _id, "muting" => false, "muting_notifications" => false} = response @@ -639,8 +551,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do setup do user = insert(:user) {:ok, activity} = CommonAPI.post(user, %{"status" => "HI!!!"}) + %{conn: conn} = oauth_access(["read:statuses"], user: user) - [user: user, activity: activity] + [conn: conn, user: user, activity: activity] end test "returns pinned statuses", %{conn: conn, user: user, activity: activity} do @@ -648,7 +561,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do result = conn - |> assign(:user, user) |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true") |> json_response(200) @@ -658,23 +570,15 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end end - test "blocking / unblocking a user", %{conn: conn} do - user = insert(:user) + test "blocking / unblocking a user" do + %{conn: conn} = oauth_access(["follow"]) other_user = insert(:user) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/accounts/#{other_user.id}/block") + ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/block") - assert %{"id" => _id, "blocking" => true} = json_response(conn, 200) + assert %{"id" => _id, "blocking" => true} = json_response(ret_conn, 200) - user = User.get_cached_by_id(user.id) - - conn = - build_conn() - |> assign(:user, user) - |> post("/api/v1/accounts/#{other_user.id}/unblock") + conn = post(conn, "/api/v1/accounts/#{other_user.id}/unblock") assert %{"id" => _id, "blocking" => false} = json_response(conn, 200) end @@ -693,8 +597,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do test "Account registration via Application", %{conn: conn} do conn = - conn - |> post("/api/v1/apps", %{ + post(conn, "/api/v1/apps", %{ client_name: "client_name", redirect_uris: "urn:ietf:wg:oauth:2.0:oob", scopes: "read, write, follow" @@ -711,8 +614,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do } = json_response(conn, 200) conn = - conn - |> post("/oauth/token", %{ + post(conn, "/oauth/token", %{ grant_type: "client_credentials", client_id: client_id, client_secret: client_secret @@ -769,13 +671,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do app_token = insert(:oauth_token, user: nil) conn = - put_req_header(conn, "authorization", "Bearer " <> app_token.token) + conn + |> put_req_header("authorization", "Bearer " <> app_token.token) |> Map.put(:remote_ip, {15, 15, 15, 15}) for i <- 1..5 do conn = - conn - |> post("/api/v1/accounts", %{ + post(conn, "/api/v1/accounts", %{ username: "#{i}lain", email: "#{i}lain@example.org", password: "PlzDontHackLain", @@ -798,8 +700,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end conn = - conn - |> post("/api/v1/accounts", %{ + post(conn, "/api/v1/accounts", %{ username: "6lain", email: "6lain@example.org", password: "PlzDontHackLain", @@ -815,9 +716,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do } do app_token = insert(:oauth_token, user: nil) - conn = - conn - |> put_req_header("authorization", "Bearer " <> app_token.token) + conn = put_req_header(conn, "authorization", "Bearer " <> app_token.token) res = post(conn, "/api/v1/accounts", valid_params) assert json_response(res, 200) @@ -836,9 +735,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end test "returns forbidden if token is invalid", %{conn: conn, valid_params: valid_params} do - conn = - conn - |> put_req_header("authorization", "Bearer " <> "invalid-token") + conn = put_req_header(conn, "authorization", "Bearer " <> "invalid-token") res = post(conn, "/api/v1/accounts", valid_params) assert json_response(res, 403) == %{"error" => "Invalid credentials"} @@ -846,15 +743,14 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end describe "GET /api/v1/accounts/:id/lists - account_lists" do - test "returns lists to which the account belongs", %{conn: conn} do - user = insert(:user) + test "returns lists to which the account belongs" do + %{user: user, conn: conn} = oauth_access(["read:lists"]) other_user = insert(:user) assert {:ok, %Pleroma.List{} = list} = Pleroma.List.create("Test List", user) {:ok, %{following: _following}} = Pleroma.List.follow(list, other_user) res = conn - |> assign(:user, user) |> get("/api/v1/accounts/#{other_user.id}/lists") |> json_response(200) @@ -863,13 +759,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end describe "verify_credentials" do - test "verify_credentials", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> get("/api/v1/accounts/verify_credentials") + test "verify_credentials" do + %{user: user, conn: conn} = oauth_access(["read:accounts"]) + conn = get(conn, "/api/v1/accounts/verify_credentials") response = json_response(conn, 200) @@ -878,25 +770,21 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do assert id == to_string(user.id) end - test "verify_credentials default scope unlisted", %{conn: conn} do + test "verify_credentials default scope unlisted" do user = insert(:user, default_scope: "unlisted") + %{conn: conn} = oauth_access(["read:accounts"], user: user) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/accounts/verify_credentials") + conn = get(conn, "/api/v1/accounts/verify_credentials") assert %{"id" => id, "source" => %{"privacy" => "unlisted"}} = json_response(conn, 200) assert id == to_string(user.id) end - test "locked accounts", %{conn: conn} do + test "locked accounts" do user = insert(:user, default_scope: "private") + %{conn: conn} = oauth_access(["read:accounts"], user: user) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/accounts/verify_credentials") + conn = get(conn, "/api/v1/accounts/verify_credentials") assert %{"id" => id, "source" => %{"privacy" => "private"}} = json_response(conn, 200) assert id == to_string(user.id) @@ -904,15 +792,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end describe "user relationships" do - test "returns the relationships for the current user", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["read:follows"]) + + test "returns the relationships for the current user", %{user: user, conn: conn} do other_user = insert(:user) - {:ok, user} = User.follow(user, other_user) + {:ok, _user} = User.follow(user, other_user) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/accounts/relationships", %{"id" => [other_user.id]}) + conn = get(conn, "/api/v1/accounts/relationships", %{"id" => [other_user.id]}) assert [relationship] = json_response(conn, 200) @@ -920,34 +806,26 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do end test "returns an empty list on a bad request", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> get("/api/v1/accounts/relationships", %{}) + conn = get(conn, "/api/v1/accounts/relationships", %{}) assert [] = json_response(conn, 200) end end - test "getting a list of mutes", %{conn: conn} do - user = insert(:user) + test "getting a list of mutes" do + %{user: user, conn: conn} = oauth_access(["read:mutes"]) other_user = insert(:user) {:ok, _user_relationships} = User.mute(user, other_user) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/mutes") + conn = get(conn, "/api/v1/mutes") other_user_id = to_string(other_user.id) assert [%{"id" => ^other_user_id}] = json_response(conn, 200) end - test "getting a list of blocks", %{conn: conn} do - user = insert(:user) + test "getting a list of blocks" do + %{user: user, conn: conn} = oauth_access(["read:blocks"]) other_user = insert(:user) {:ok, _user_relationship} = User.block(user, other_user) diff --git a/test/web/mastodon_api/controllers/conversation_controller_test.exs b/test/web/mastodon_api/controllers/conversation_controller_test.exs index 2a1223b18..4bb9781a6 100644 --- a/test/web/mastodon_api/controllers/conversation_controller_test.exs +++ b/test/web/mastodon_api/controllers/conversation_controller_test.exs @@ -10,8 +10,9 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do import Pleroma.Factory - test "returns a list of conversations", %{conn: conn} do - user_one = insert(:user) + setup do: oauth_access(["read:statuses"]) + + test "returns a list of conversations", %{user: user_one, conn: conn} do user_two = insert(:user) user_three = insert(:user) @@ -33,10 +34,7 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do "visibility" => "private" }) - res_conn = - conn - |> assign(:user, user_one) - |> get("/api/v1/conversations") + res_conn = get(conn, "/api/v1/conversations") assert response = json_response(res_conn, 200) @@ -59,8 +57,7 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do assert User.get_cached_by_id(user_one.id).unread_conversation_count == 0 end - test "filters conversations by recipients", %{conn: conn} do - user_one = insert(:user) + test "filters conversations by recipients", %{user: user_one, conn: conn} do user_two = insert(:user) user_three = insert(:user) @@ -96,7 +93,6 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do [conversation1, conversation2] = conn - |> assign(:user, user_one) |> get("/api/v1/conversations", %{"recipients" => [user_two.id]}) |> json_response(200) @@ -105,15 +101,13 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do [conversation1] = conn - |> assign(:user, user_one) |> get("/api/v1/conversations", %{"recipients" => [user_two.id, user_three.id]}) |> json_response(200) assert conversation1["last_status"]["id"] == direct3.id end - test "updates the last_status on reply", %{conn: conn} do - user_one = insert(:user) + test "updates the last_status on reply", %{user: user_one, conn: conn} do user_two = insert(:user) {:ok, direct} = @@ -131,15 +125,13 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do [%{"last_status" => res_last_status}] = conn - |> assign(:user, user_one) |> get("/api/v1/conversations") |> json_response(200) assert res_last_status["id"] == direct_reply.id end - test "the user marks a conversation as read", %{conn: conn} do - user_one = insert(:user) + test "the user marks a conversation as read", %{user: user_one, conn: conn} do user_two = insert(:user) {:ok, direct} = @@ -151,15 +143,21 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do assert User.get_cached_by_id(user_one.id).unread_conversation_count == 0 assert User.get_cached_by_id(user_two.id).unread_conversation_count == 1 - [%{"id" => direct_conversation_id, "unread" => true}] = - conn + user_two_conn = + build_conn() |> assign(:user, user_two) + |> assign( + :token, + insert(:oauth_token, user: user_two, scopes: ["read:statuses", "write:conversations"]) + ) + + [%{"id" => direct_conversation_id, "unread" => true}] = + user_two_conn |> get("/api/v1/conversations") |> json_response(200) %{"unread" => false} = - conn - |> assign(:user, user_two) + user_two_conn |> post("/api/v1/conversations/#{direct_conversation_id}/read") |> json_response(200) @@ -176,7 +174,6 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do [%{"unread" => true}] = conn - |> assign(:user, user_one) |> get("/api/v1/conversations") |> json_response(200) @@ -195,8 +192,7 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do assert User.get_cached_by_id(user_two.id).unread_conversation_count == 0 end - test "(vanilla) Mastodon frontend behaviour", %{conn: conn} do - user_one = insert(:user) + test "(vanilla) Mastodon frontend behaviour", %{user: user_one, conn: conn} do user_two = insert(:user) {:ok, direct} = @@ -205,10 +201,7 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do "visibility" => "direct" }) - res_conn = - conn - |> assign(:user, user_one) - |> get("/api/v1/statuses/#{direct.id}/context") + res_conn = get(conn, "/api/v1/statuses/#{direct.id}/context") assert %{"ancestors" => [], "descendants" => []} == json_response(res_conn, 200) end diff --git a/test/web/mastodon_api/controllers/domain_block_controller_test.exs b/test/web/mastodon_api/controllers/domain_block_controller_test.exs index 25a279cdc..55de625ba 100644 --- a/test/web/mastodon_api/controllers/domain_block_controller_test.exs +++ b/test/web/mastodon_api/controllers/domain_block_controller_test.exs @@ -9,31 +9,25 @@ defmodule Pleroma.Web.MastodonAPI.DomainBlockControllerTest do import Pleroma.Factory - test "blocking / unblocking a domain", %{conn: conn} do - user = insert(:user) + test "blocking / unblocking a domain" do + %{user: user, conn: conn} = oauth_access(["write:blocks"]) other_user = insert(:user, %{ap_id: "https://dogwhistle.zone/@pundit"}) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"}) + ret_conn = post(conn, "/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"}) - assert %{} = json_response(conn, 200) + assert %{} = json_response(ret_conn, 200) user = User.get_cached_by_ap_id(user.ap_id) assert User.blocks?(user, other_user) - conn = - build_conn() - |> assign(:user, user) - |> delete("/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"}) + ret_conn = delete(conn, "/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"}) - assert %{} = json_response(conn, 200) + assert %{} = json_response(ret_conn, 200) user = User.get_cached_by_ap_id(user.ap_id) refute User.blocks?(user, other_user) end - test "getting a list of domain blocks", %{conn: conn} do - user = insert(:user) + test "getting a list of domain blocks" do + %{user: user, conn: conn} = oauth_access(["read:blocks"]) {:ok, user} = User.block_domain(user, "bad.site") {:ok, user} = User.block_domain(user, "even.worse.site") diff --git a/test/web/mastodon_api/controllers/filter_controller_test.exs b/test/web/mastodon_api/controllers/filter_controller_test.exs index 550689788..3aea17ec7 100644 --- a/test/web/mastodon_api/controllers/filter_controller_test.exs +++ b/test/web/mastodon_api/controllers/filter_controller_test.exs @@ -7,20 +7,15 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do alias Pleroma.Web.MastodonAPI.FilterView - import Pleroma.Factory - - test "creating a filter", %{conn: conn} do - user = insert(:user) + test "creating a filter" do + %{conn: conn} = oauth_access(["write:filters"]) filter = %Pleroma.Filter{ phrase: "knights", context: ["home"] } - conn = - conn - |> assign(:user, user) - |> post("/api/v1/filters", %{"phrase" => filter.phrase, context: filter.context}) + conn = post(conn, "/api/v1/filters", %{"phrase" => filter.phrase, context: filter.context}) assert response = json_response(conn, 200) assert response["phrase"] == filter.phrase @@ -30,8 +25,8 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do assert response["id"] != "" end - test "fetching a list of filters", %{conn: conn} do - user = insert(:user) + test "fetching a list of filters" do + %{user: user, conn: conn} = oauth_access(["read:filters"]) query_one = %Pleroma.Filter{ user_id: user.id, @@ -52,7 +47,6 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do response = conn - |> assign(:user, user) |> get("/api/v1/filters") |> json_response(200) @@ -64,8 +58,8 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do ) end - test "get a filter", %{conn: conn} do - user = insert(:user) + test "get a filter" do + %{user: user, conn: conn} = oauth_access(["read:filters"]) query = %Pleroma.Filter{ user_id: user.id, @@ -76,16 +70,13 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do {:ok, filter} = Pleroma.Filter.create(query) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/filters/#{filter.filter_id}") + conn = get(conn, "/api/v1/filters/#{filter.filter_id}") assert _response = json_response(conn, 200) end - test "update a filter", %{conn: conn} do - user = insert(:user) + test "update a filter" do + %{user: user, conn: conn} = oauth_access(["write:filters"]) query = %Pleroma.Filter{ user_id: user.id, @@ -102,9 +93,7 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do } conn = - conn - |> assign(:user, user) - |> put("/api/v1/filters/#{query.filter_id}", %{ + put(conn, "/api/v1/filters/#{query.filter_id}", %{ phrase: new.phrase, context: new.context }) @@ -114,8 +103,8 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do assert response["context"] == new.context end - test "delete a filter", %{conn: conn} do - user = insert(:user) + test "delete a filter" do + %{user: user, conn: conn} = oauth_access(["write:filters"]) query = %Pleroma.Filter{ user_id: user.id, @@ -126,10 +115,7 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do {:ok, filter} = Pleroma.Filter.create(query) - conn = - conn - |> assign(:user, user) - |> delete("/api/v1/filters/#{filter.filter_id}") + conn = delete(conn, "/api/v1/filters/#{filter.filter_id}") assert response = json_response(conn, 200) assert response == %{} diff --git a/test/web/mastodon_api/controllers/follow_request_controller_test.exs b/test/web/mastodon_api/controllers/follow_request_controller_test.exs index 288cd9029..6e4a76501 100644 --- a/test/web/mastodon_api/controllers/follow_request_controller_test.exs +++ b/test/web/mastodon_api/controllers/follow_request_controller_test.exs @@ -11,8 +11,13 @@ defmodule Pleroma.Web.MastodonAPI.FollowRequestControllerTest do import Pleroma.Factory describe "locked accounts" do - test "/api/v1/follow_requests works" do + setup do user = insert(:user, locked: true) + %{conn: conn} = oauth_access(["follow"], user: user) + %{user: user, conn: conn} + end + + test "/api/v1/follow_requests works", %{user: user, conn: conn} do other_user = insert(:user) {:ok, _activity} = ActivityPub.follow(other_user, user) @@ -20,17 +25,13 @@ defmodule Pleroma.Web.MastodonAPI.FollowRequestControllerTest do assert User.following?(other_user, user) == false - conn = - build_conn() - |> assign(:user, user) - |> get("/api/v1/follow_requests") + conn = get(conn, "/api/v1/follow_requests") assert [relationship] = json_response(conn, 200) assert to_string(other_user.id) == relationship["id"] end - test "/api/v1/follow_requests/:id/authorize works" do - user = insert(:user, locked: true) + test "/api/v1/follow_requests/:id/authorize works", %{user: user, conn: conn} do other_user = insert(:user) {:ok, _activity} = ActivityPub.follow(other_user, user) @@ -41,10 +42,7 @@ defmodule Pleroma.Web.MastodonAPI.FollowRequestControllerTest do assert User.following?(other_user, user) == false - conn = - build_conn() - |> assign(:user, user) - |> post("/api/v1/follow_requests/#{other_user.id}/authorize") + conn = post(conn, "/api/v1/follow_requests/#{other_user.id}/authorize") assert relationship = json_response(conn, 200) assert to_string(other_user.id) == relationship["id"] @@ -55,18 +53,14 @@ defmodule Pleroma.Web.MastodonAPI.FollowRequestControllerTest do assert User.following?(other_user, user) == true end - test "/api/v1/follow_requests/:id/reject works" do - user = insert(:user, locked: true) + test "/api/v1/follow_requests/:id/reject works", %{user: user, conn: conn} do other_user = insert(:user) {:ok, _activity} = ActivityPub.follow(other_user, user) user = User.get_cached_by_id(user.id) - conn = - build_conn() - |> assign(:user, user) - |> post("/api/v1/follow_requests/#{other_user.id}/reject") + conn = post(conn, "/api/v1/follow_requests/#{other_user.id}/reject") assert relationship = json_response(conn, 200) assert to_string(other_user.id) == relationship["id"] diff --git a/test/web/mastodon_api/controllers/list_controller_test.exs b/test/web/mastodon_api/controllers/list_controller_test.exs index 093506309..a6effbb69 100644 --- a/test/web/mastodon_api/controllers/list_controller_test.exs +++ b/test/web/mastodon_api/controllers/list_controller_test.exs @@ -9,44 +9,35 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do import Pleroma.Factory - test "creating a list", %{conn: conn} do - user = insert(:user) + test "creating a list" do + %{conn: conn} = oauth_access(["write:lists"]) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/lists", %{"title" => "cuties"}) + conn = post(conn, "/api/v1/lists", %{"title" => "cuties"}) assert %{"title" => title} = json_response(conn, 200) assert title == "cuties" end - test "renders error for invalid params", %{conn: conn} do - user = insert(:user) + test "renders error for invalid params" do + %{conn: conn} = oauth_access(["write:lists"]) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/lists", %{"title" => nil}) + conn = post(conn, "/api/v1/lists", %{"title" => nil}) assert %{"error" => "can't be blank"} == json_response(conn, :unprocessable_entity) end - test "listing a user's lists", %{conn: conn} do - user = insert(:user) + test "listing a user's lists" do + %{conn: conn} = oauth_access(["read:lists", "write:lists"]) conn - |> assign(:user, user) |> post("/api/v1/lists", %{"title" => "cuties"}) + |> json_response(:ok) conn - |> assign(:user, user) |> post("/api/v1/lists", %{"title" => "cofe"}) + |> json_response(:ok) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/lists") + conn = get(conn, "/api/v1/lists") assert [ %{"id" => _, "title" => "cofe"}, @@ -54,41 +45,35 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do ] = json_response(conn, :ok) end - test "adding users to a list", %{conn: conn} do - user = insert(:user) + test "adding users to a list" do + %{user: user, conn: conn} = oauth_access(["write:lists"]) other_user = insert(:user) {:ok, list} = Pleroma.List.create("name", user) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]}) + conn = post(conn, "/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]}) assert %{} == json_response(conn, 200) %Pleroma.List{following: following} = Pleroma.List.get(list.id, user) assert following == [other_user.follower_address] end - test "removing users from a list", %{conn: conn} do - user = insert(:user) + test "removing users from a list" do + %{user: user, conn: conn} = oauth_access(["write:lists"]) other_user = insert(:user) third_user = insert(:user) {:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.follow(list, other_user) {:ok, list} = Pleroma.List.follow(list, third_user) - conn = - conn - |> assign(:user, user) - |> delete("/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]}) + conn = delete(conn, "/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]}) assert %{} == json_response(conn, 200) %Pleroma.List{following: following} = Pleroma.List.get(list.id, user) assert following == [third_user.follower_address] end - test "listing users in a list", %{conn: conn} do - user = insert(:user) + test "listing users in a list" do + %{user: user, conn: conn} = oauth_access(["read:lists"]) other_user = insert(:user) {:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.follow(list, other_user) @@ -102,8 +87,8 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do assert id == to_string(other_user.id) end - test "retrieving a list", %{conn: conn} do - user = insert(:user) + test "retrieving a list" do + %{user: user, conn: conn} = oauth_access(["read:lists"]) {:ok, list} = Pleroma.List.create("name", user) conn = @@ -115,32 +100,26 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do assert id == to_string(list.id) end - test "renders 404 if list is not found", %{conn: conn} do - user = insert(:user) + test "renders 404 if list is not found" do + %{conn: conn} = oauth_access(["read:lists"]) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/lists/666") + conn = get(conn, "/api/v1/lists/666") assert %{"error" => "List not found"} = json_response(conn, :not_found) end - test "renaming a list", %{conn: conn} do - user = insert(:user) + test "renaming a list" do + %{user: user, conn: conn} = oauth_access(["write:lists"]) {:ok, list} = Pleroma.List.create("name", user) - conn = - conn - |> assign(:user, user) - |> put("/api/v1/lists/#{list.id}", %{"title" => "newname"}) + conn = put(conn, "/api/v1/lists/#{list.id}", %{"title" => "newname"}) assert %{"title" => name} = json_response(conn, 200) assert name == "newname" end - test "validates title when renaming a list", %{conn: conn} do - user = insert(:user) + test "validates title when renaming a list" do + %{user: user, conn: conn} = oauth_access(["write:lists"]) {:ok, list} = Pleroma.List.create("name", user) conn = @@ -151,14 +130,11 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do assert %{"error" => "can't be blank"} == json_response(conn, :unprocessable_entity) end - test "deleting a list", %{conn: conn} do - user = insert(:user) + test "deleting a list" do + %{user: user, conn: conn} = oauth_access(["write:lists"]) {:ok, list} = Pleroma.List.create("name", user) - conn = - conn - |> assign(:user, user) - |> delete("/api/v1/lists/#{list.id}") + conn = delete(conn, "/api/v1/lists/#{list.id}") assert %{} = json_response(conn, 200) assert is_nil(Repo.get(Pleroma.List, list.id)) diff --git a/test/web/mastodon_api/controllers/media_controller_test.exs b/test/web/mastodon_api/controllers/media_controller_test.exs index 06c6a1cb3..042511ca4 100644 --- a/test/web/mastodon_api/controllers/media_controller_test.exs +++ b/test/web/mastodon_api/controllers/media_controller_test.exs @@ -9,23 +9,17 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do alias Pleroma.User alias Pleroma.Web.ActivityPub.ActivityPub - import Pleroma.Factory + setup do: oauth_access(["write:media"]) describe "media upload" do setup do - user = insert(:user) - - conn = - build_conn() - |> assign(:user, user) - image = %Plug.Upload{ content_type: "image/jpg", path: Path.absname("test/fixtures/image.jpg"), filename: "an_image.jpg" } - [conn: conn, image: image] + [image: image] end clear_config([:media_proxy]) @@ -49,9 +43,7 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do end describe "PUT /api/v1/media/:id" do - setup do - actor = insert(:user) - + setup %{user: actor} do file = %Plug.Upload{ content_type: "image/jpg", path: Path.absname("test/fixtures/image.jpg"), @@ -65,13 +57,12 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do description: "test-m" ) - [actor: actor, object: object] + [object: object] end - test "updates name of media", %{conn: conn, actor: actor, object: object} do + test "updates name of media", %{conn: conn, object: object} do media = conn - |> assign(:user, actor) |> put("/api/v1/media/#{object.id}", %{"description" => "test-media"}) |> json_response(:ok) @@ -79,10 +70,9 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do assert refresh_record(object).data["name"] == "test-media" end - test "returns error wheb request is bad", %{conn: conn, actor: actor, object: object} do + test "returns error when request is bad", %{conn: conn, object: object} do media = conn - |> assign(:user, actor) |> put("/api/v1/media/#{object.id}", %{}) |> json_response(400) diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs index f6d4ab9f0..6f0606250 100644 --- a/test/web/mastodon_api/controllers/notification_controller_test.exs +++ b/test/web/mastodon_api/controllers/notification_controller_test.exs @@ -12,8 +12,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do import Pleroma.Factory - test "list of notifications", %{conn: conn} do - user = insert(:user) + test "list of notifications" do + %{user: user, conn: conn} = oauth_access(["read:notifications"]) other_user = insert(:user) {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"}) @@ -34,18 +34,15 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do assert response == expected_response end - test "getting a single notification", %{conn: conn} do - user = insert(:user) + test "getting a single notification" do + %{user: user, conn: conn} = oauth_access(["read:notifications"]) other_user = insert(:user) {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"}) {:ok, [notification]} = Notification.create_notifications(activity) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/notifications/#{notification.id}") + conn = get(conn, "/api/v1/notifications/#{notification.id}") expected_response = "hi <span class=\"h-card\"><a data-user=\"#{user.id}\" class=\"u-url mention\" href=\"#{ @@ -56,8 +53,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do assert response == expected_response end - test "dismissing a single notification", %{conn: conn} do - user = insert(:user) + test "dismissing a single notification" do + %{user: user, conn: conn} = oauth_access(["write:notifications"]) other_user = insert(:user) {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"}) @@ -72,32 +69,26 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do assert %{} = json_response(conn, 200) end - test "clearing all notifications", %{conn: conn} do - user = insert(:user) + test "clearing all notifications" do + %{user: user, conn: conn} = oauth_access(["write:notifications", "read:notifications"]) other_user = insert(:user) {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"}) {:ok, [_notification]} = Notification.create_notifications(activity) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/notifications/clear") + ret_conn = post(conn, "/api/v1/notifications/clear") - assert %{} = json_response(conn, 200) + assert %{} = json_response(ret_conn, 200) - conn = - build_conn() - |> assign(:user, user) - |> get("/api/v1/notifications") + ret_conn = get(conn, "/api/v1/notifications") - assert all = json_response(conn, 200) + assert all = json_response(ret_conn, 200) assert all == [] end - test "paginates notifications using min_id, since_id, max_id, and limit", %{conn: conn} do - user = insert(:user) + test "paginates notifications using min_id, since_id, max_id, and limit" do + %{user: user, conn: conn} = oauth_access(["read:notifications"]) other_user = insert(:user) {:ok, activity1} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"}) @@ -137,59 +128,148 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do assert [%{"id" => ^notification3_id}, %{"id" => ^notification2_id}] = result end - test "filters notifications using exclude_visibilities", %{conn: conn} do - user = insert(:user) - other_user = insert(:user) - - {:ok, public_activity} = - CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "public"}) - - {:ok, direct_activity} = - CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "direct"}) - - {:ok, unlisted_activity} = - CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "unlisted"}) - - {:ok, private_activity} = - CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "private"}) + describe "exclude_visibilities" do + test "filters notifications for mentions" do + %{user: user, conn: conn} = oauth_access(["read:notifications"]) + other_user = insert(:user) - conn = assign(conn, :user, user) - - conn_res = - get(conn, "/api/v1/notifications", %{ - exclude_visibilities: ["public", "unlisted", "private"] - }) - - assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200) - assert id == direct_activity.id - - conn_res = - get(conn, "/api/v1/notifications", %{ - exclude_visibilities: ["public", "unlisted", "direct"] - }) - - assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200) - assert id == private_activity.id - - conn_res = - get(conn, "/api/v1/notifications", %{ - exclude_visibilities: ["public", "private", "direct"] - }) - - assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200) - assert id == unlisted_activity.id - - conn_res = - get(conn, "/api/v1/notifications", %{ - exclude_visibilities: ["unlisted", "private", "direct"] - }) + {:ok, public_activity} = + CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "public"}) + + {:ok, direct_activity} = + CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "direct"}) + + {:ok, unlisted_activity} = + CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "unlisted"}) + + {:ok, private_activity} = + CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "private"}) + + conn_res = + get(conn, "/api/v1/notifications", %{ + exclude_visibilities: ["public", "unlisted", "private"] + }) + + assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200) + assert id == direct_activity.id + + conn_res = + get(conn, "/api/v1/notifications", %{ + exclude_visibilities: ["public", "unlisted", "direct"] + }) - assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200) - assert id == public_activity.id + assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200) + assert id == private_activity.id + + conn_res = + get(conn, "/api/v1/notifications", %{ + exclude_visibilities: ["public", "private", "direct"] + }) + + assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200) + assert id == unlisted_activity.id + + conn_res = + get(conn, "/api/v1/notifications", %{ + exclude_visibilities: ["unlisted", "private", "direct"] + }) + + assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200) + assert id == public_activity.id + end + + test "filters notifications for Like activities" do + user = insert(:user) + %{user: other_user, conn: conn} = oauth_access(["read:notifications"]) + + {:ok, public_activity} = + CommonAPI.post(other_user, %{"status" => ".", "visibility" => "public"}) + + {:ok, direct_activity} = + CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "direct"}) + + {:ok, unlisted_activity} = + CommonAPI.post(other_user, %{"status" => ".", "visibility" => "unlisted"}) + + {:ok, private_activity} = + CommonAPI.post(other_user, %{"status" => ".", "visibility" => "private"}) + + {:ok, _, _} = CommonAPI.favorite(public_activity.id, user) + {:ok, _, _} = CommonAPI.favorite(direct_activity.id, user) + {:ok, _, _} = CommonAPI.favorite(unlisted_activity.id, user) + {:ok, _, _} = CommonAPI.favorite(private_activity.id, user) + + activity_ids = + conn + |> get("/api/v1/notifications", %{exclude_visibilities: ["direct"]}) + |> json_response(200) + |> Enum.map(& &1["status"]["id"]) + + assert public_activity.id in activity_ids + assert unlisted_activity.id in activity_ids + assert private_activity.id in activity_ids + refute direct_activity.id in activity_ids + + activity_ids = + conn + |> get("/api/v1/notifications", %{exclude_visibilities: ["unlisted"]}) + |> json_response(200) + |> Enum.map(& &1["status"]["id"]) + + assert public_activity.id in activity_ids + refute unlisted_activity.id in activity_ids + assert private_activity.id in activity_ids + assert direct_activity.id in activity_ids + + activity_ids = + conn + |> get("/api/v1/notifications", %{exclude_visibilities: ["private"]}) + |> json_response(200) + |> Enum.map(& &1["status"]["id"]) + + assert public_activity.id in activity_ids + assert unlisted_activity.id in activity_ids + refute private_activity.id in activity_ids + assert direct_activity.id in activity_ids + + activity_ids = + conn + |> get("/api/v1/notifications", %{exclude_visibilities: ["public"]}) + |> json_response(200) + |> Enum.map(& &1["status"]["id"]) + + refute public_activity.id in activity_ids + assert unlisted_activity.id in activity_ids + assert private_activity.id in activity_ids + assert direct_activity.id in activity_ids + end + + test "filters notifications for Announce activities" do + user = insert(:user) + %{user: other_user, conn: conn} = oauth_access(["read:notifications"]) + + {:ok, public_activity} = + CommonAPI.post(other_user, %{"status" => ".", "visibility" => "public"}) + + {:ok, unlisted_activity} = + CommonAPI.post(other_user, %{"status" => ".", "visibility" => "unlisted"}) + + {:ok, _, _} = CommonAPI.repeat(public_activity.id, user) + {:ok, _, _} = CommonAPI.repeat(unlisted_activity.id, user) + + activity_ids = + conn + |> get("/api/v1/notifications", %{exclude_visibilities: ["unlisted"]}) + |> json_response(200) + |> Enum.map(& &1["status"]["id"]) + + assert public_activity.id in activity_ids + refute unlisted_activity.id in activity_ids + end end - test "filters notifications using exclude_types", %{conn: conn} do - user = insert(:user) + test "filters notifications using exclude_types" do + %{user: user, conn: conn} = oauth_access(["read:notifications"]) other_user = insert(:user) {:ok, mention_activity} = CommonAPI.post(other_user, %{"status" => "hey @#{user.nickname}"}) @@ -203,8 +283,6 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do reblog_notification_id = get_notification_id_by_activity(reblog_activity) follow_notification_id = get_notification_id_by_activity(follow_activity) - conn = assign(conn, :user, user) - conn_res = get(conn, "/api/v1/notifications", %{exclude_types: ["mention", "favourite", "reblog"]}) @@ -226,8 +304,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do assert [%{"id" => ^reblog_notification_id}] = json_response(conn_res, 200) end - test "destroy multiple", %{conn: conn} do - user = insert(:user) + test "destroy multiple" do + %{user: user, conn: conn} = oauth_access(["read:notifications", "write:notifications"]) other_user = insert(:user) {:ok, activity1} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"}) @@ -240,8 +318,6 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do notification3_id = get_notification_id_by_activity(activity3) notification4_id = get_notification_id_by_activity(activity4) - conn = assign(conn, :user, user) - result = conn |> get("/api/v1/notifications") @@ -252,6 +328,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do conn2 = conn |> assign(:user, other_user) + |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:notifications"])) result = conn2 @@ -276,97 +353,134 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do assert [%{"id" => ^notification4_id}, %{"id" => ^notification3_id}] = result end - test "doesn't see notifications after muting user with notifications", %{conn: conn} do - user = insert(:user) + test "doesn't see notifications after muting user with notifications" do + %{user: user, conn: conn} = oauth_access(["read:notifications"]) user2 = insert(:user) {:ok, _, _, _} = CommonAPI.follow(user, user2) {:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"}) - conn = assign(conn, :user, user) + ret_conn = get(conn, "/api/v1/notifications") - conn = get(conn, "/api/v1/notifications") - - assert length(json_response(conn, 200)) == 1 + assert length(json_response(ret_conn, 200)) == 1 {:ok, _user_relationships} = User.mute(user, user2) - conn = assign(build_conn(), :user, user) conn = get(conn, "/api/v1/notifications") assert json_response(conn, 200) == [] end - test "see notifications after muting user without notifications", %{conn: conn} do - user = insert(:user) + test "see notifications after muting user without notifications" do + %{user: user, conn: conn} = oauth_access(["read:notifications"]) user2 = insert(:user) {:ok, _, _, _} = CommonAPI.follow(user, user2) {:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"}) - conn = assign(conn, :user, user) + ret_conn = get(conn, "/api/v1/notifications") - conn = get(conn, "/api/v1/notifications") - - assert length(json_response(conn, 200)) == 1 + assert length(json_response(ret_conn, 200)) == 1 {:ok, _user_relationships} = User.mute(user, user2, false) - conn = assign(build_conn(), :user, user) conn = get(conn, "/api/v1/notifications") assert length(json_response(conn, 200)) == 1 end - test "see notifications after muting user with notifications and with_muted parameter", %{ - conn: conn - } do - user = insert(:user) + test "see notifications after muting user with notifications and with_muted parameter" do + %{user: user, conn: conn} = oauth_access(["read:notifications"]) user2 = insert(:user) {:ok, _, _, _} = CommonAPI.follow(user, user2) {:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"}) - conn = assign(conn, :user, user) - - conn = get(conn, "/api/v1/notifications") + ret_conn = get(conn, "/api/v1/notifications") - assert length(json_response(conn, 200)) == 1 + assert length(json_response(ret_conn, 200)) == 1 {:ok, _user_relationships} = User.mute(user, user2) - conn = assign(build_conn(), :user, user) conn = get(conn, "/api/v1/notifications", %{"with_muted" => "true"}) assert length(json_response(conn, 200)) == 1 end - test "see move notifications with `with_move` parameter", %{ - conn: conn - } do + test "see move notifications with `with_move` parameter" do old_user = insert(:user) new_user = insert(:user, also_known_as: [old_user.ap_id]) - follower = insert(:user) + %{user: follower, conn: conn} = oauth_access(["read:notifications"]) User.follow(follower, old_user) Pleroma.Web.ActivityPub.ActivityPub.move(old_user, new_user) Pleroma.Tests.ObanHelpers.perform_all() - conn = - conn - |> assign(:user, follower) - |> get("/api/v1/notifications") + ret_conn = get(conn, "/api/v1/notifications") - assert json_response(conn, 200) == [] + assert json_response(ret_conn, 200) == [] - conn = - build_conn() - |> assign(:user, follower) - |> get("/api/v1/notifications", %{"with_move" => "true"}) + conn = get(conn, "/api/v1/notifications", %{"with_move" => "true"}) assert length(json_response(conn, 200)) == 1 end + describe "link headers" do + test "preserves parameters in link headers" do + %{user: user, conn: conn} = oauth_access(["read:notifications"]) + other_user = insert(:user) + + {:ok, activity1} = + CommonAPI.post(other_user, %{ + "status" => "hi @#{user.nickname}", + "visibility" => "public" + }) + + {:ok, activity2} = + CommonAPI.post(other_user, %{ + "status" => "hi @#{user.nickname}", + "visibility" => "public" + }) + + notification1 = Repo.get_by(Notification, activity_id: activity1.id) + notification2 = Repo.get_by(Notification, activity_id: activity2.id) + + conn = + conn + |> assign(:user, user) + |> get("/api/v1/notifications", %{media_only: true}) + + assert [link_header] = get_resp_header(conn, "link") + assert link_header =~ ~r/media_only=true/ + assert link_header =~ ~r/min_id=#{notification2.id}/ + assert link_header =~ ~r/max_id=#{notification1.id}/ + end + end + + describe "from specified user" do + test "account_id" do + %{user: user, conn: conn} = oauth_access(["read:notifications"]) + + %{id: account_id} = other_user1 = insert(:user) + other_user2 = insert(:user) + + {:ok, _activity} = CommonAPI.post(other_user1, %{"status" => "hi @#{user.nickname}"}) + {:ok, _activity} = CommonAPI.post(other_user2, %{"status" => "bye @#{user.nickname}"}) + + assert [%{"account" => %{"id" => ^account_id}}] = + conn + |> assign(:user, user) + |> get("/api/v1/notifications", %{account_id: account_id}) + |> json_response(200) + + assert %{"error" => "Account is not found"} = + conn + |> assign(:user, user) + |> get("/api/v1/notifications", %{account_id: "cofe"}) + |> json_response(404) + end + end + defp get_notification_id_by_activity(%{id: id}) do Notification |> Repo.get_by(activity_id: id) diff --git a/test/web/mastodon_api/controllers/poll_controller_test.exs b/test/web/mastodon_api/controllers/poll_controller_test.exs index 40cf3e879..5a1cea11b 100644 --- a/test/web/mastodon_api/controllers/poll_controller_test.exs +++ b/test/web/mastodon_api/controllers/poll_controller_test.exs @@ -11,9 +11,9 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do import Pleroma.Factory describe "GET /api/v1/polls/:id" do - test "returns poll entity for object id", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["read:statuses"]) + test "returns poll entity for object id", %{user: user, conn: conn} do {:ok, activity} = CommonAPI.post(user, %{ "status" => "Pleroma does", @@ -22,10 +22,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do object = Object.normalize(activity) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/polls/#{object.id}") + conn = get(conn, "/api/v1/polls/#{object.id}") response = json_response(conn, 200) id = to_string(object.id) @@ -33,11 +30,10 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do end test "does not expose polls for private statuses", %{conn: conn} do - user = insert(:user) other_user = insert(:user) {:ok, activity} = - CommonAPI.post(user, %{ + CommonAPI.post(other_user, %{ "status" => "Pleroma does", "poll" => %{"options" => ["what Mastodon't", "n't what Mastodoes"], "expires_in" => 20}, "visibility" => "private" @@ -45,22 +41,20 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do object = Object.normalize(activity) - conn = - conn - |> assign(:user, other_user) - |> get("/api/v1/polls/#{object.id}") + conn = get(conn, "/api/v1/polls/#{object.id}") assert json_response(conn, 404) end end describe "POST /api/v1/polls/:id/votes" do + setup do: oauth_access(["write:statuses"]) + test "votes are added to the poll", %{conn: conn} do - user = insert(:user) other_user = insert(:user) {:ok, activity} = - CommonAPI.post(user, %{ + CommonAPI.post(other_user, %{ "status" => "A very delicious sandwich", "poll" => %{ "options" => ["Lettuce", "Grilled Bacon", "Tomato"], @@ -71,10 +65,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do object = Object.normalize(activity) - conn = - conn - |> assign(:user, other_user) - |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1, 2]}) + conn = post(conn, "/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1, 2]}) assert json_response(conn, 200) object = Object.get_by_id(object.id) @@ -84,9 +75,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do end) end - test "author can't vote", %{conn: conn} do - user = insert(:user) - + test "author can't vote", %{user: user, conn: conn} do {:ok, activity} = CommonAPI.post(user, %{ "status" => "Am I cute?", @@ -96,7 +85,6 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do object = Object.normalize(activity) assert conn - |> assign(:user, user) |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [1]}) |> json_response(422) == %{"error" => "Poll's author can't vote"} @@ -106,11 +94,10 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do end test "does not allow multiple choices on a single-choice question", %{conn: conn} do - user = insert(:user) other_user = insert(:user) {:ok, activity} = - CommonAPI.post(user, %{ + CommonAPI.post(other_user, %{ "status" => "The glass is", "poll" => %{"options" => ["half empty", "half full"], "expires_in" => 20} }) @@ -118,7 +105,6 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do object = Object.normalize(activity) assert conn - |> assign(:user, other_user) |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1]}) |> json_response(422) == %{"error" => "Too many choices"} @@ -130,42 +116,32 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do end test "does not allow choice index to be greater than options count", %{conn: conn} do - user = insert(:user) other_user = insert(:user) {:ok, activity} = - CommonAPI.post(user, %{ + CommonAPI.post(other_user, %{ "status" => "Am I cute?", "poll" => %{"options" => ["Yes", "No"], "expires_in" => 20} }) object = Object.normalize(activity) - conn = - conn - |> assign(:user, other_user) - |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [2]}) + conn = post(conn, "/api/v1/polls/#{object.id}/votes", %{"choices" => [2]}) assert json_response(conn, 422) == %{"error" => "Invalid indices"} end test "returns 404 error when object is not exist", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> post("/api/v1/polls/1/votes", %{"choices" => [0]}) + conn = post(conn, "/api/v1/polls/1/votes", %{"choices" => [0]}) assert json_response(conn, 404) == %{"error" => "Record not found"} end test "returns 404 when poll is private and not available for user", %{conn: conn} do - user = insert(:user) other_user = insert(:user) {:ok, activity} = - CommonAPI.post(user, %{ + CommonAPI.post(other_user, %{ "status" => "Am I cute?", "poll" => %{"options" => ["Yes", "No"], "expires_in" => 20}, "visibility" => "private" @@ -173,10 +149,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do object = Object.normalize(activity) - conn = - conn - |> assign(:user, other_user) - |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0]}) + conn = post(conn, "/api/v1/polls/#{object.id}/votes", %{"choices" => [0]}) assert json_response(conn, 404) == %{"error" => "Record not found"} end diff --git a/test/web/mastodon_api/controllers/report_controller_test.exs b/test/web/mastodon_api/controllers/report_controller_test.exs index 979ca48f3..53c132ff4 100644 --- a/test/web/mastodon_api/controllers/report_controller_test.exs +++ b/test/web/mastodon_api/controllers/report_controller_test.exs @@ -9,32 +9,30 @@ defmodule Pleroma.Web.MastodonAPI.ReportControllerTest do import Pleroma.Factory + setup do: oauth_access(["write:reports"]) + setup do - reporter = insert(:user) target_user = insert(:user) {:ok, activity} = CommonAPI.post(target_user, %{"status" => "foobar"}) - [reporter: reporter, target_user: target_user, activity: activity] + [target_user: target_user, activity: activity] end - test "submit a basic report", %{conn: conn, reporter: reporter, target_user: target_user} do + test "submit a basic report", %{conn: conn, target_user: target_user} do assert %{"action_taken" => false, "id" => _} = conn - |> assign(:user, reporter) |> post("/api/v1/reports", %{"account_id" => target_user.id}) |> json_response(200) end test "submit a report with statuses and comment", %{ conn: conn, - reporter: reporter, target_user: target_user, activity: activity } do assert %{"action_taken" => false, "id" => _} = conn - |> assign(:user, reporter) |> post("/api/v1/reports", %{ "account_id" => target_user.id, "status_ids" => [activity.id], @@ -46,19 +44,16 @@ defmodule Pleroma.Web.MastodonAPI.ReportControllerTest do test "account_id is required", %{ conn: conn, - reporter: reporter, activity: activity } do assert %{"error" => "Valid `account_id` required"} = conn - |> assign(:user, reporter) |> post("/api/v1/reports", %{"status_ids" => [activity.id]}) |> json_response(400) end test "comment must be up to the size specified in the config", %{ conn: conn, - reporter: reporter, target_user: target_user } do max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000) @@ -68,20 +63,15 @@ defmodule Pleroma.Web.MastodonAPI.ReportControllerTest do assert ^error = conn - |> assign(:user, reporter) |> post("/api/v1/reports", %{"account_id" => target_user.id, "comment" => comment}) |> json_response(400) end test "returns error when account is not exist", %{ conn: conn, - reporter: reporter, activity: activity } do - conn = - conn - |> assign(:user, reporter) - |> post("/api/v1/reports", %{"status_ids" => [activity.id], "account_id" => "foo"}) + conn = post(conn, "/api/v1/reports", %{"status_ids" => [activity.id], "account_id" => "foo"}) assert json_response(conn, 400) == %{"error" => "Account not found"} end diff --git a/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs b/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs index ae5fee2bc..9666a7f2e 100644 --- a/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs +++ b/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs @@ -10,89 +10,69 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityControllerTest do import Pleroma.Factory - test "shows scheduled activities", %{conn: conn} do - user = insert(:user) + test "shows scheduled activities" do + %{user: user, conn: conn} = oauth_access(["read:statuses"]) + scheduled_activity_id1 = insert(:scheduled_activity, user: user).id |> to_string() scheduled_activity_id2 = insert(:scheduled_activity, user: user).id |> to_string() scheduled_activity_id3 = insert(:scheduled_activity, user: user).id |> to_string() scheduled_activity_id4 = insert(:scheduled_activity, user: user).id |> to_string() - conn = - conn - |> assign(:user, user) - # min_id - conn_res = - conn - |> get("/api/v1/scheduled_statuses?limit=2&min_id=#{scheduled_activity_id1}") + conn_res = get(conn, "/api/v1/scheduled_statuses?limit=2&min_id=#{scheduled_activity_id1}") result = json_response(conn_res, 200) assert [%{"id" => ^scheduled_activity_id3}, %{"id" => ^scheduled_activity_id2}] = result # since_id - conn_res = - conn - |> get("/api/v1/scheduled_statuses?limit=2&since_id=#{scheduled_activity_id1}") + conn_res = get(conn, "/api/v1/scheduled_statuses?limit=2&since_id=#{scheduled_activity_id1}") result = json_response(conn_res, 200) assert [%{"id" => ^scheduled_activity_id4}, %{"id" => ^scheduled_activity_id3}] = result # max_id - conn_res = - conn - |> get("/api/v1/scheduled_statuses?limit=2&max_id=#{scheduled_activity_id4}") + conn_res = get(conn, "/api/v1/scheduled_statuses?limit=2&max_id=#{scheduled_activity_id4}") result = json_response(conn_res, 200) assert [%{"id" => ^scheduled_activity_id3}, %{"id" => ^scheduled_activity_id2}] = result end - test "shows a scheduled activity", %{conn: conn} do - user = insert(:user) + test "shows a scheduled activity" do + %{user: user, conn: conn} = oauth_access(["read:statuses"]) scheduled_activity = insert(:scheduled_activity, user: user) - res_conn = - conn - |> assign(:user, user) - |> get("/api/v1/scheduled_statuses/#{scheduled_activity.id}") + res_conn = get(conn, "/api/v1/scheduled_statuses/#{scheduled_activity.id}") assert %{"id" => scheduled_activity_id} = json_response(res_conn, 200) assert scheduled_activity_id == scheduled_activity.id |> to_string() - res_conn = - conn - |> assign(:user, user) - |> get("/api/v1/scheduled_statuses/404") + res_conn = get(conn, "/api/v1/scheduled_statuses/404") assert %{"error" => "Record not found"} = json_response(res_conn, 404) end - test "updates a scheduled activity", %{conn: conn} do - user = insert(:user) + test "updates a scheduled activity" do + %{user: user, conn: conn} = oauth_access(["write:statuses"]) scheduled_activity = insert(:scheduled_activity, user: user) new_scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond) res_conn = - conn - |> assign(:user, user) - |> put("/api/v1/scheduled_statuses/#{scheduled_activity.id}", %{ + put(conn, "/api/v1/scheduled_statuses/#{scheduled_activity.id}", %{ scheduled_at: new_scheduled_at }) assert %{"scheduled_at" => expected_scheduled_at} = json_response(res_conn, 200) assert expected_scheduled_at == Pleroma.Web.CommonAPI.Utils.to_masto_date(new_scheduled_at) - res_conn = - conn - |> assign(:user, user) - |> put("/api/v1/scheduled_statuses/404", %{scheduled_at: new_scheduled_at}) + res_conn = put(conn, "/api/v1/scheduled_statuses/404", %{scheduled_at: new_scheduled_at}) assert %{"error" => "Record not found"} = json_response(res_conn, 404) end - test "deletes a scheduled activity", %{conn: conn} do - user = insert(:user) + test "deletes a scheduled activity" do + %{user: user, conn: conn} = oauth_access(["write:statuses"]) scheduled_activity = insert(:scheduled_activity, user: user) res_conn = diff --git a/test/web/mastodon_api/controllers/search_controller_test.exs b/test/web/mastodon_api/controllers/search_controller_test.exs index 7953fad62..effae130c 100644 --- a/test/web/mastodon_api/controllers/search_controller_test.exs +++ b/test/web/mastodon_api/controllers/search_controller_test.exs @@ -53,7 +53,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do {:ok, _} = CommonAPI.post(user_two, %{"status" => "This isn't"}) results = - get(conn, "/api/v2/search", %{"q" => "2hu #private"}) + conn + |> get("/api/v2/search", %{"q" => "2hu #private"}) |> json_response(200) [account | _] = results["accounts"] @@ -73,17 +74,39 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do [status] = results["statuses"] assert status["id"] == to_string(activity.id) end + + test "excludes a blocked users from search results", %{conn: conn} do + user = insert(:user) + user_smith = insert(:user, %{nickname: "Agent", name: "I love 2hu"}) + user_neo = insert(:user, %{nickname: "Agent Neo", name: "Agent"}) + + {:ok, act1} = CommonAPI.post(user, %{"status" => "This is about 2hu private 天子"}) + {:ok, act2} = CommonAPI.post(user_smith, %{"status" => "Agent Smith"}) + {:ok, act3} = CommonAPI.post(user_neo, %{"status" => "Agent Smith"}) + Pleroma.User.block(user, user_smith) + + results = + conn + |> assign(:user, user) + |> assign(:token, insert(:oauth_token, user: user, scopes: ["read"])) + |> get("/api/v2/search", %{"q" => "Agent"}) + |> json_response(200) + + status_ids = Enum.map(results["statuses"], fn g -> g["id"] end) + + assert act3.id in status_ids + refute act2.id in status_ids + refute act1.id in status_ids + end end describe ".account_search" do test "account search", %{conn: conn} do - user = insert(:user) user_two = insert(:user, %{nickname: "shp@shitposter.club"}) user_three = insert(:user, %{nickname: "shp@heldscal.la", name: "I love 2hu"}) results = conn - |> assign(:user, user) |> get("/api/v1/accounts/search", %{"q" => "shp"}) |> json_response(200) @@ -94,7 +117,6 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do results = conn - |> assign(:user, user) |> get("/api/v1/accounts/search", %{"q" => "2hu"}) |> json_response(200) @@ -104,11 +126,10 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do end test "returns account if query contains a space", %{conn: conn} do - user = insert(:user, %{nickname: "shp@shitposter.club"}) + insert(:user, %{nickname: "shp@shitposter.club"}) results = conn - |> assign(:user, user) |> get("/api/v1/accounts/search", %{"q" => "shp@shitposter.club xxx "}) |> json_response(200) @@ -150,11 +171,10 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do {:ok, _} = CommonAPI.post(user_two, %{"status" => "This isn't"}) - conn = + results = conn |> get("/api/v1/search", %{"q" => "2hu"}) - - assert results = json_response(conn, 200) + |> json_response(200) [account | _] = results["accounts"] assert account["id"] == to_string(user_three.id) @@ -165,15 +185,19 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do assert status["id"] == to_string(activity.id) end - test "search fetches remote statuses", %{conn: conn} do + test "search fetches remote statuses and prefers them over other results", %{conn: conn} do capture_log(fn -> - conn = + {:ok, %{id: activity_id}} = + CommonAPI.post(insert(:user), %{ + "status" => "check out https://shitposter.club/notice/2827873" + }) + + results = conn |> get("/api/v1/search", %{"q" => "https://shitposter.club/notice/2827873"}) + |> json_response(200) - assert results = json_response(conn, 200) - - [status] = results["statuses"] + [status, %{"id" => ^activity_id}] = results["statuses"] assert status["uri"] == "tag:shitposter.club,2017-05-05:noticeId=2827873:objectType=comment" @@ -188,11 +212,10 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do }) capture_log(fn -> - conn = + results = conn |> get("/api/v1/search", %{"q" => Object.normalize(activity).data["id"]}) - - assert results = json_response(conn, 200) + |> json_response(200) [] = results["statuses"] end) @@ -201,22 +224,23 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do test "search fetches remote accounts", %{conn: conn} do user = insert(:user) - conn = + results = conn |> assign(:user, user) + |> assign(:token, insert(:oauth_token, user: user, scopes: ["read"])) |> get("/api/v1/search", %{"q" => "mike@osada.macgirvin.com", "resolve" => "true"}) + |> json_response(200) - assert results = json_response(conn, 200) [account] = results["accounts"] assert account["acct"] == "mike@osada.macgirvin.com" end test "search doesn't fetch remote accounts if resolve is false", %{conn: conn} do - conn = + results = conn |> get("/api/v1/search", %{"q" => "mike@osada.macgirvin.com", "resolve" => "false"}) + |> json_response(200) - assert results = json_response(conn, 200) assert [] == results["accounts"] end diff --git a/test/web/mastodon_api/controllers/status_controller_test.exs b/test/web/mastodon_api/controllers/status_controller_test.exs index 5fbe947ba..b03b4b344 100644 --- a/test/web/mastodon_api/controllers/status_controller_test.exs +++ b/test/web/mastodon_api/controllers/status_controller_test.exs @@ -23,24 +23,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do clear_config([:instance, :allow_relay]) describe "posting statuses" do - setup do - user = insert(:user) - - conn = - build_conn() - |> assign(:user, user) - - [conn: conn] - end + setup do: oauth_access(["write:statuses"]) test "posting a status does not increment reblog_count when relaying", %{conn: conn} do Pleroma.Config.put([:instance, :federating], true) Pleroma.Config.get([:instance, :allow_relay], true) - user = insert(:user) response = conn - |> assign(:user, user) |> post("api/v1/statuses", %{ "content_type" => "text/plain", "source" => "Pleroma FE", @@ -54,7 +44,6 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do response = conn - |> assign(:user, user) |> get("api/v1/statuses/#{response["id"]}", %{}) |> json_response(200) @@ -132,9 +121,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do NaiveDateTime.to_iso8601(expiration.scheduled_at) end - test "posting an undefined status with an attachment", %{conn: conn} do - user = insert(:user) - + test "posting an undefined status with an attachment", %{user: user, conn: conn} do file = %Plug.Upload{ content_type: "image/jpg", path: Path.absname("test/fixtures/image.jpg"), @@ -144,17 +131,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do {:ok, upload} = ActivityPub.upload(file, actor: user.ap_id) conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "media_ids" => [to_string(upload.id)] }) assert json_response(conn, 200) end - test "replying to a status", %{conn: conn} do - user = insert(:user) + test "replying to a status", %{user: user, conn: conn} do {:ok, replied_to} = CommonAPI.post(user, %{"status" => "cofe"}) conn = @@ -169,8 +153,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do assert Activity.get_in_reply_to_activity(activity).id == replied_to.id end - test "replying to a direct message with visibility other than direct", %{conn: conn} do - user = insert(:user) + test "replying to a direct message with visibility other than direct", %{ + user: user, + conn: conn + } do {:ok, replied_to} = CommonAPI.post(user, %{"status" => "suya..", "visibility" => "direct"}) Enum.each(["public", "private", "unlisted"], fn visibility -> @@ -187,18 +173,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end test "posting a status with an invalid in_reply_to_id", %{conn: conn} do - conn = - conn - |> post("/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => ""}) + conn = post(conn, "/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => ""}) assert %{"content" => "xD", "id" => id} = json_response(conn, 200) assert Activity.get_by_id(id) end test "posting a sensitive status", %{conn: conn} do - conn = - conn - |> post("/api/v1/statuses", %{"status" => "cofe", "sensitive" => true}) + conn = post(conn, "/api/v1/statuses", %{"status" => "cofe", "sensitive" => true}) assert %{"content" => "cofe", "id" => id, "sensitive" => true} = json_response(conn, 200) assert Activity.get_by_id(id) @@ -206,8 +188,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do test "posting a fake status", %{conn: conn} do real_conn = - conn - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "status" => "\"Tenshi Eating a Corndog\" is a much discussed concept on /jp/. The significance of it is disputed, so I will focus on one core concept: the symbolism behind it" }) @@ -226,8 +207,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do |> Kernel.put_in(["pleroma", "conversation_id"], nil) fake_conn = - conn - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "status" => "\"Tenshi Eating a Corndog\" is a much discussed concept on /jp/. The significance of it is disputed, so I will focus on one core concept: the symbolism behind it", "preview" => true @@ -254,8 +234,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do Config.put([:rich_media, :enabled], true) conn = - conn - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "status" => "https://example.com/ogp" }) @@ -267,9 +246,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do user2 = insert(:user) content = "direct cofe @#{user2.nickname}" - conn = - conn - |> post("api/v1/statuses", %{"status" => content, "visibility" => "direct"}) + conn = post(conn, "api/v1/statuses", %{"status" => content, "visibility" => "direct"}) assert %{"id" => id} = response = json_response(conn, 200) assert response["visibility"] == "direct" @@ -282,14 +259,13 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end describe "posting scheduled statuses" do + setup do: oauth_access(["write:statuses"]) + test "creates a scheduled activity", %{conn: conn} do - user = insert(:user) scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond) conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "status" => "scheduled", "scheduled_at" => scheduled_at }) @@ -299,8 +275,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do assert [] == Repo.all(Activity) end - test "creates a scheduled activity with a media attachment", %{conn: conn} do - user = insert(:user) + test "creates a scheduled activity with a media attachment", %{user: user, conn: conn} do scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond) file = %Plug.Upload{ @@ -312,9 +287,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do {:ok, upload} = ActivityPub.upload(file, actor: user.ap_id) conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "media_ids" => [to_string(upload.id)], "status" => "scheduled", "scheduled_at" => scheduled_at @@ -326,15 +299,11 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do test "skips the scheduling and creates the activity if scheduled_at is earlier than 5 minutes from now", %{conn: conn} do - user = insert(:user) - scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(5) - 1, :millisecond) conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "status" => "not scheduled", "scheduled_at" => scheduled_at }) @@ -343,9 +312,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do assert [] == Repo.all(ScheduledActivity) end - test "returns error when daily user limit is exceeded", %{conn: conn} do - user = insert(:user) - + test "returns error when daily user limit is exceeded", %{user: user, conn: conn} do today = NaiveDateTime.utc_now() |> NaiveDateTime.add(:timer.minutes(6), :millisecond) @@ -355,17 +322,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do {:ok, _} = ScheduledActivity.create(user, attrs) {:ok, _} = ScheduledActivity.create(user, attrs) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => today}) + conn = post(conn, "/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => today}) assert %{"error" => "daily limit exceeded"} == json_response(conn, 422) end - test "returns error when total user limit is exceeded", %{conn: conn} do - user = insert(:user) - + test "returns error when total user limit is exceeded", %{user: user, conn: conn} do today = NaiveDateTime.utc_now() |> NaiveDateTime.add(:timer.minutes(6), :millisecond) @@ -382,23 +344,20 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do {:ok, _} = ScheduledActivity.create(user, %{params: %{}, scheduled_at: tomorrow}) conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => tomorrow}) + post(conn, "/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => tomorrow}) assert %{"error" => "total limit exceeded"} == json_response(conn, 422) end end describe "posting polls" do + setup do: oauth_access(["write:statuses"]) + test "posting a poll", %{conn: conn} do - user = insert(:user) time = NaiveDateTime.utc_now() conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "status" => "Who is the #bestgrill?", "poll" => %{"options" => ["Rei", "Asuka", "Misato"], "expires_in" => 420} }) @@ -414,13 +373,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end test "option limit is enforced", %{conn: conn} do - user = insert(:user) limit = Config.get([:instance, :poll_limits, :max_options]) conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "status" => "desu~", "poll" => %{"options" => Enum.map(0..limit, fn _ -> "desu" end), "expires_in" => 1} }) @@ -430,13 +386,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end test "option character limit is enforced", %{conn: conn} do - user = insert(:user) limit = Config.get([:instance, :poll_limits, :max_option_chars]) conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "status" => "...", "poll" => %{ "options" => [Enum.reduce(0..limit, "", fn _, acc -> acc <> "." end)], @@ -449,13 +402,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end test "minimal date limit is enforced", %{conn: conn} do - user = insert(:user) limit = Config.get([:instance, :poll_limits, :min_expiration]) conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "status" => "imagine arbitrary limits", "poll" => %{ "options" => ["this post was made by pleroma gang"], @@ -468,13 +418,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end test "maximum date limit is enforced", %{conn: conn} do - user = insert(:user) limit = Config.get([:instance, :poll_limits, :max_expiration]) conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses", %{ + post(conn, "/api/v1/statuses", %{ "status" => "imagine arbitrary limits", "poll" => %{ "options" => ["this post was made by pleroma gang"], @@ -487,19 +434,18 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end end - test "get a status", %{conn: conn} do + test "get a status" do + %{conn: conn} = oauth_access(["read:statuses"]) activity = insert(:note_activity) - conn = - conn - |> get("/api/v1/statuses/#{activity.id}") + conn = get(conn, "/api/v1/statuses/#{activity.id}") assert %{"id" => id} = json_response(conn, 200) assert id == to_string(activity.id) end - test "get a direct status", %{conn: conn} do - user = insert(:user) + test "get a direct status" do + %{user: user, conn: conn} = oauth_access(["read:statuses"]) other_user = insert(:user) {:ok, activity} = @@ -516,7 +462,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do assert res["pleroma"]["direct_conversation_id"] == participation.id end - test "get statuses by IDs", %{conn: conn} do + test "get statuses by IDs" do + %{conn: conn} = oauth_access(["read:statuses"]) %{id: id1} = insert(:note_activity) %{id: id2} = insert(:note_activity) @@ -527,9 +474,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end describe "deleting a status" do - test "when you created it", %{conn: conn} do - activity = insert(:note_activity) - author = User.get_cached_by_ap_id(activity.data["actor"]) + test "when you created it" do + %{user: author, conn: conn} = oauth_access(["write:statuses"]) + activity = insert(:note_activity, user: author) conn = conn @@ -541,14 +488,11 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do refute Activity.get_by_id(activity.id) end - test "when you didn't create it", %{conn: conn} do + test "when you didn't create it" do + %{conn: conn} = oauth_access(["write:statuses"]) activity = insert(:note_activity) - user = insert(:user) - conn = - conn - |> assign(:user, user) - |> delete("/api/v1/statuses/#{activity.id}") + conn = delete(conn, "/api/v1/statuses/#{activity.id}") assert %{"error" => _} = json_response(conn, 403) @@ -564,6 +508,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do res_conn = conn |> assign(:user, admin) + |> assign(:token, insert(:oauth_token, user: admin, scopes: ["write:statuses"])) |> delete("/api/v1/statuses/#{activity1.id}") assert %{} = json_response(res_conn, 200) @@ -571,6 +516,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do res_conn = conn |> assign(:user, moderator) + |> assign(:token, insert(:oauth_token, user: moderator, scopes: ["write:statuses"])) |> delete("/api/v1/statuses/#{activity2.id}") assert %{} = json_response(res_conn, 200) @@ -581,14 +527,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end describe "reblogging" do + setup do: oauth_access(["write:statuses"]) + test "reblogs and returns the reblogged status", %{conn: conn} do activity = insert(:note_activity) - user = insert(:user) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/#{activity.id}/reblog") + conn = post(conn, "/api/v1/statuses/#{activity.id}/reblog") assert %{ "reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}, @@ -600,12 +544,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do test "reblogs privately and returns the reblogged status", %{conn: conn} do activity = insert(:note_activity) - user = insert(:user) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/#{activity.id}/reblog", %{"visibility" => "private"}) + conn = post(conn, "/api/v1/statuses/#{activity.id}/reblog", %{"visibility" => "private"}) assert %{ "reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}, @@ -616,7 +556,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do assert to_string(activity.id) == id end - test "reblogged status for another user", %{conn: conn} do + test "reblogged status for another user" do activity = insert(:note_activity) user1 = insert(:user) user2 = insert(:user) @@ -627,8 +567,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do {:ok, _, _object} = CommonAPI.repeat(activity.id, user2) conn_res = - conn + build_conn() |> assign(:user, user3) + |> assign(:token, insert(:oauth_token, user: user3, scopes: ["read:statuses"])) |> get("/api/v1/statuses/#{reblog_activity1.id}") assert %{ @@ -639,8 +580,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do } = json_response(conn_res, 200) conn_res = - conn + build_conn() |> assign(:user, user2) + |> assign(:token, insert(:oauth_token, user: user2, scopes: ["read:statuses"])) |> get("/api/v1/statuses/#{reblog_activity1.id}") assert %{ @@ -654,28 +596,21 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end test "returns 400 error when activity is not exist", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/foo/reblog") + conn = post(conn, "/api/v1/statuses/foo/reblog") assert json_response(conn, 400) == %{"error" => "Could not repeat"} end end describe "unreblogging" do - test "unreblogs and returns the unreblogged status", %{conn: conn} do + setup do: oauth_access(["write:statuses"]) + + test "unreblogs and returns the unreblogged status", %{user: user, conn: conn} do activity = insert(:note_activity) - user = insert(:user) {:ok, _, _} = CommonAPI.repeat(activity.id, user) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/#{activity.id}/unreblog") + conn = post(conn, "/api/v1/statuses/#{activity.id}/unreblog") assert %{"id" => id, "reblogged" => false, "reblogs_count" => 0} = json_response(conn, 200) @@ -683,26 +618,19 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end test "returns 400 error when activity is not exist", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/foo/unreblog") + conn = post(conn, "/api/v1/statuses/foo/unreblog") assert json_response(conn, 400) == %{"error" => "Could not unrepeat"} end end describe "favoriting" do + setup do: oauth_access(["write:favourites"]) + test "favs a status and returns it", %{conn: conn} do activity = insert(:note_activity) - user = insert(:user) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/#{activity.id}/favourite") + conn = post(conn, "/api/v1/statuses/#{activity.id}/favourite") assert %{"id" => id, "favourites_count" => 1, "favourited" => true} = json_response(conn, 200) @@ -710,29 +638,29 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do assert to_string(activity.id) == id end - test "returns 400 error for a wrong id", %{conn: conn} do - user = insert(:user) + test "favoriting twice will just return 200", %{conn: conn} do + activity = insert(:note_activity) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/1/favourite") + post(conn, "/api/v1/statuses/#{activity.id}/favourite") + assert post(conn, "/api/v1/statuses/#{activity.id}/favourite") |> json_response(200) + end + + test "returns 400 error for a wrong id", %{conn: conn} do + conn = post(conn, "/api/v1/statuses/1/favourite") assert json_response(conn, 400) == %{"error" => "Could not favorite"} end end describe "unfavoriting" do - test "unfavorites a status and returns it", %{conn: conn} do + setup do: oauth_access(["write:favourites"]) + + test "unfavorites a status and returns it", %{user: user, conn: conn} do activity = insert(:note_activity) - user = insert(:user) {:ok, _, _} = CommonAPI.favorite(activity.id, user) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/#{activity.id}/unfavourite") + conn = post(conn, "/api/v1/statuses/#{activity.id}/unfavourite") assert %{"id" => id, "favourites_count" => 0, "favourited" => false} = json_response(conn, 200) @@ -741,23 +669,19 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end test "returns 400 error for a wrong id", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/1/unfavourite") + conn = post(conn, "/api/v1/statuses/1/unfavourite") assert json_response(conn, 400) == %{"error" => "Could not unfavorite"} end end describe "pinned statuses" do - setup do - user = insert(:user) + setup do: oauth_access(["write:accounts"]) + + setup %{user: user} do {:ok, activity} = CommonAPI.post(user, %{"status" => "HI!!!"}) - [user: user, activity: activity] + %{activity: activity} end clear_config([:instance, :max_pinned_statuses]) do @@ -769,13 +693,11 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do assert %{"id" => ^id_str, "pinned" => true} = conn - |> assign(:user, user) |> post("/api/v1/statuses/#{activity.id}/pin") |> json_response(200) assert [%{"id" => ^id_str, "pinned" => true}] = conn - |> assign(:user, user) |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true") |> json_response(200) end @@ -783,19 +705,16 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do test "/pin: returns 400 error when activity is not public", %{conn: conn, user: user} do {:ok, dm} = CommonAPI.post(user, %{"status" => "test", "visibility" => "direct"}) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/#{dm.id}/pin") + conn = post(conn, "/api/v1/statuses/#{dm.id}/pin") assert json_response(conn, 400) == %{"error" => "Could not pin"} end test "unpin status", %{conn: conn, user: user, activity: activity} do {:ok, _} = CommonAPI.pin(activity.id, user) + user = refresh_record(user) id_str = to_string(activity.id) - user = refresh_record(user) assert %{"id" => ^id_str, "pinned" => false} = conn @@ -805,16 +724,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do assert [] = conn - |> assign(:user, user) |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true") |> json_response(200) end - test "/unpin: returns 400 error when activity is not exist", %{conn: conn, user: user} do - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/1/unpin") + test "/unpin: returns 400 error when activity is not exist", %{conn: conn} do + conn = post(conn, "/api/v1/statuses/1/unpin") assert json_response(conn, 400) == %{"error" => "Could not unpin"} end @@ -826,7 +741,6 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do assert %{"id" => ^id_str_one, "pinned" => true} = conn - |> assign(:user, user) |> post("/api/v1/statuses/#{id_str_one}/pin") |> json_response(200) @@ -844,8 +758,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do setup do Config.put([:rich_media, :enabled], true) - user = insert(:user) - %{user: user} + oauth_access(["read:statuses"]) end test "returns rich-media card", %{conn: conn, user: user} do @@ -887,7 +800,6 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do response_two = conn - |> assign(:user, user) |> get("/api/v1/statuses/#{activity.id}/card") |> json_response(200) @@ -925,72 +837,55 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end test "bookmarks" do - user = insert(:user) - for_user = insert(:user) + %{conn: conn} = oauth_access(["write:bookmarks", "read:bookmarks"]) + author = insert(:user) {:ok, activity1} = - CommonAPI.post(user, %{ + CommonAPI.post(author, %{ "status" => "heweoo?" }) {:ok, activity2} = - CommonAPI.post(user, %{ + CommonAPI.post(author, %{ "status" => "heweoo!" }) - response1 = - build_conn() - |> assign(:user, for_user) - |> post("/api/v1/statuses/#{activity1.id}/bookmark") + response1 = post(conn, "/api/v1/statuses/#{activity1.id}/bookmark") assert json_response(response1, 200)["bookmarked"] == true - response2 = - build_conn() - |> assign(:user, for_user) - |> post("/api/v1/statuses/#{activity2.id}/bookmark") + response2 = post(conn, "/api/v1/statuses/#{activity2.id}/bookmark") assert json_response(response2, 200)["bookmarked"] == true - bookmarks = - build_conn() - |> assign(:user, for_user) - |> get("/api/v1/bookmarks") + bookmarks = get(conn, "/api/v1/bookmarks") assert [json_response(response2, 200), json_response(response1, 200)] == json_response(bookmarks, 200) - response1 = - build_conn() - |> assign(:user, for_user) - |> post("/api/v1/statuses/#{activity1.id}/unbookmark") + response1 = post(conn, "/api/v1/statuses/#{activity1.id}/unbookmark") assert json_response(response1, 200)["bookmarked"] == false - bookmarks = - build_conn() - |> assign(:user, for_user) - |> get("/api/v1/bookmarks") + bookmarks = get(conn, "/api/v1/bookmarks") assert [json_response(response2, 200)] == json_response(bookmarks, 200) end describe "conversation muting" do + setup do: oauth_access(["write:mutes"]) + setup do post_user = insert(:user) - user = insert(:user) - {:ok, activity} = CommonAPI.post(post_user, %{"status" => "HIE"}) - - [user: user, activity: activity] + %{activity: activity} end - test "mute conversation", %{conn: conn, user: user, activity: activity} do + test "mute conversation", %{conn: conn, activity: activity} do id_str = to_string(activity.id) assert %{"id" => ^id_str, "muted" => true} = conn - |> assign(:user, user) |> post("/api/v1/statuses/#{activity.id}/mute") |> json_response(200) end @@ -998,10 +893,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do test "cannot mute already muted conversation", %{conn: conn, user: user, activity: activity} do {:ok, _} = CommonAPI.add_mute(user, activity) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/statuses/#{activity.id}/mute") + conn = post(conn, "/api/v1/statuses/#{activity.id}/mute") assert json_response(conn, 400) == %{"error" => "conversation is already muted"} end @@ -1010,11 +902,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do {:ok, _} = CommonAPI.add_mute(user, activity) id_str = to_string(activity.id) - user = refresh_record(user) assert %{"id" => ^id_str, "muted" => false} = conn - |> assign(:user, user) + # |> assign(:user, user) |> post("/api/v1/statuses/#{activity.id}/unmute") |> json_response(200) end @@ -1031,6 +922,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do conn1 = conn |> assign(:user, user2) + |> assign(:token, insert(:oauth_token, user: user2, scopes: ["write:statuses"])) |> post("/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => replied_to.id}) assert %{"content" => "xD", "id" => id} = json_response(conn1, 200) @@ -1044,6 +936,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do conn2 = conn |> assign(:user, user3) + |> assign(:token, insert(:oauth_token, user: user3, scopes: ["write:statuses"])) |> post("/api/v1/statuses/#{activity.id}/reblog") assert %{"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}} = @@ -1055,6 +948,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do conn3 = conn |> assign(:user, user3) + |> assign(:token, insert(:oauth_token, user: user3, scopes: ["read:statuses"])) |> get("api/v1/timelines/home") [reblogged_activity] = json_response(conn3, 200) @@ -1066,15 +960,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end describe "GET /api/v1/statuses/:id/favourited_by" do - setup do - user = insert(:user) - {:ok, activity} = CommonAPI.post(user, %{"status" => "test"}) + setup do: oauth_access(["read:accounts"]) - conn = - build_conn() - |> assign(:user, user) + setup %{user: user} do + {:ok, activity} = CommonAPI.post(user, %{"status" => "test"}) - [conn: conn, activity: activity, user: user] + %{activity: activity} end test "returns users who have favorited the status", %{conn: conn, activity: activity} do @@ -1114,20 +1005,18 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do response = conn - |> assign(:user, user) |> get("/api/v1/statuses/#{activity.id}/favourited_by") |> json_response(:ok) assert Enum.empty?(response) end - test "does not fail on an unauthenticated request", %{conn: conn, activity: activity} do + test "does not fail on an unauthenticated request", %{activity: activity} do other_user = insert(:user) {:ok, _, _} = CommonAPI.favorite(activity.id, other_user) response = - conn - |> assign(:user, nil) + build_conn() |> get("/api/v1/statuses/#{activity.id}/favourited_by") |> json_response(:ok) @@ -1135,7 +1024,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do assert id == other_user.id end - test "requires authentification for private posts", %{conn: conn, user: user} do + test "requires authentication for private posts", %{user: user} do other_user = insert(:user) {:ok, activity} = @@ -1146,15 +1035,25 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do {:ok, _, _} = CommonAPI.favorite(activity.id, other_user) - conn - |> assign(:user, nil) - |> get("/api/v1/statuses/#{activity.id}/favourited_by") + favourited_by_url = "/api/v1/statuses/#{activity.id}/favourited_by" + + build_conn() + |> get(favourited_by_url) |> json_response(404) - response = + conn = build_conn() |> assign(:user, other_user) - |> get("/api/v1/statuses/#{activity.id}/favourited_by") + |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"])) + + conn + |> assign(:token, nil) + |> get(favourited_by_url) + |> json_response(404) + + response = + conn + |> get(favourited_by_url) |> json_response(200) [%{"id" => id}] = response @@ -1163,15 +1062,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end describe "GET /api/v1/statuses/:id/reblogged_by" do - setup do - user = insert(:user) - {:ok, activity} = CommonAPI.post(user, %{"status" => "test"}) + setup do: oauth_access(["read:accounts"]) - conn = - build_conn() - |> assign(:user, user) + setup %{user: user} do + {:ok, activity} = CommonAPI.post(user, %{"status" => "test"}) - [conn: conn, activity: activity, user: user] + %{activity: activity} end test "returns users who have reblogged the status", %{conn: conn, activity: activity} do @@ -1211,7 +1107,6 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do response = conn - |> assign(:user, user) |> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> json_response(:ok) @@ -1219,7 +1114,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do end test "does not return users who have reblogged the status privately", %{ - conn: %{assigns: %{user: user}} = conn, + conn: conn, activity: activity } do other_user = insert(:user) @@ -1228,20 +1123,18 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do response = conn - |> assign(:user, user) |> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> json_response(:ok) assert Enum.empty?(response) end - test "does not fail on an unauthenticated request", %{conn: conn, activity: activity} do + test "does not fail on an unauthenticated request", %{activity: activity} do other_user = insert(:user) {:ok, _, _} = CommonAPI.repeat(activity.id, other_user) response = - conn - |> assign(:user, nil) + build_conn() |> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> json_response(:ok) @@ -1249,7 +1142,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do assert id == other_user.id end - test "requires authentification for private posts", %{conn: conn, user: user} do + test "requires authentication for private posts", %{user: user} do other_user = insert(:user) {:ok, activity} = @@ -1258,14 +1151,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do "visibility" => "direct" }) - conn - |> assign(:user, nil) + build_conn() |> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> json_response(404) response = build_conn() |> assign(:user, other_user) + |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"])) |> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> json_response(200) @@ -1284,7 +1177,6 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do response = build_conn() - |> assign(:user, nil) |> get("/api/v1/statuses/#{id3}/context") |> json_response(:ok) @@ -1294,8 +1186,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do } = response end - test "returns the favorites of a user", %{conn: conn} do - user = insert(:user) + test "returns the favorites of a user" do + %{user: user, conn: conn} = oauth_access(["read:favourites"]) other_user = insert(:user) {:ok, _} = CommonAPI.post(other_user, %{"status" => "bla"}) @@ -1303,10 +1195,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do {:ok, _, _} = CommonAPI.favorite(activity.id, user) - first_conn = - conn - |> assign(:user, user) - |> get("/api/v1/favourites") + first_conn = get(conn, "/api/v1/favourites") assert [status] = json_response(first_conn, 200) assert status["id"] == to_string(activity.id) @@ -1325,18 +1214,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do last_like = status["id"] - second_conn = - conn - |> assign(:user, user) - |> get("/api/v1/favourites?since_id=#{last_like}") + second_conn = get(conn, "/api/v1/favourites?since_id=#{last_like}") assert [second_status] = json_response(second_conn, 200) assert second_status["id"] == to_string(second_activity.id) - third_conn = - conn - |> assign(:user, user) - |> get("/api/v1/favourites?limit=0") + third_conn = get(conn, "/api/v1/favourites?limit=0") assert [] = json_response(third_conn, 200) end diff --git a/test/web/mastodon_api/controllers/suggestion_controller_test.exs b/test/web/mastodon_api/controllers/suggestion_controller_test.exs index 78620a873..c4118a576 100644 --- a/test/web/mastodon_api/controllers/suggestion_controller_test.exs +++ b/test/web/mastodon_api/controllers/suggestion_controller_test.exs @@ -11,8 +11,9 @@ defmodule Pleroma.Web.MastodonAPI.SuggestionControllerTest do import Pleroma.Factory import Tesla.Mock - setup do - user = insert(:user) + setup do: oauth_access(["read"]) + + setup %{user: user} do other_user = insert(:user) host = Config.get([Pleroma.Web.Endpoint, :url, :host]) url500 = "http://test500?#{host}&#{user.nickname}" @@ -32,31 +33,29 @@ defmodule Pleroma.Web.MastodonAPI.SuggestionControllerTest do } end) - [user: user, other_user: other_user] + [other_user: other_user] end clear_config(:suggestions) - test "returns empty result when suggestions disabled", %{conn: conn, user: user} do + test "returns empty result when suggestions disabled", %{conn: conn} do Config.put([:suggestions, :enabled], false) res = conn - |> assign(:user, user) |> get("/api/v1/suggestions") |> json_response(200) assert res == [] end - test "returns error", %{conn: conn, user: user} do + test "returns error", %{conn: conn} do Config.put([:suggestions, :enabled], true) Config.put([:suggestions, :third_party_engine], "http://test500?{{host}}&{{user}}") assert capture_log(fn -> res = conn - |> assign(:user, user) |> get("/api/v1/suggestions") |> json_response(500) @@ -64,13 +63,12 @@ defmodule Pleroma.Web.MastodonAPI.SuggestionControllerTest do end) =~ "Could not retrieve suggestions" end - test "returns suggestions", %{conn: conn, user: user, other_user: other_user} do + test "returns suggestions", %{conn: conn, other_user: other_user} do Config.put([:suggestions, :enabled], true) Config.put([:suggestions, :third_party_engine], "http://test200?{{host}}&{{user}}") res = conn - |> assign(:user, user) |> get("/api/v1/suggestions") |> json_response(200) diff --git a/test/web/mastodon_api/controllers/timeline_controller_test.exs b/test/web/mastodon_api/controllers/timeline_controller_test.exs index dc17cc963..bb94d8e5a 100644 --- a/test/web/mastodon_api/controllers/timeline_controller_test.exs +++ b/test/web/mastodon_api/controllers/timeline_controller_test.exs @@ -20,31 +20,25 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do end describe "home" do - test "the home timeline", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["read:statuses"]) + + test "the home timeline", %{user: user, conn: conn} do following = insert(:user) {:ok, _activity} = CommonAPI.post(following, %{"status" => "test"}) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/timelines/home") + ret_conn = get(conn, "/api/v1/timelines/home") - assert Enum.empty?(json_response(conn, :ok)) + assert Enum.empty?(json_response(ret_conn, :ok)) - {:ok, user} = User.follow(user, following) + {:ok, _user} = User.follow(user, following) - conn = - build_conn() - |> assign(:user, user) - |> get("/api/v1/timelines/home") + conn = get(conn, "/api/v1/timelines/home") assert [%{"content" => "test"}] = json_response(conn, :ok) end - test "the home timeline when the direct messages are excluded", %{conn: conn} do - user = insert(:user) + test "the home timeline when the direct messages are excluded", %{user: user, conn: conn} do {:ok, public_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "public"}) {:ok, direct_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"}) @@ -54,10 +48,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do {:ok, private_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "private"}) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/timelines/home", %{"exclude_visibilities" => ["direct"]}) + conn = get(conn, "/api/v1/timelines/home", %{"exclude_visibilities" => ["direct"]}) assert status_ids = json_response(conn, :ok) |> Enum.map(& &1["id"]) assert public_activity.id in status_ids @@ -99,11 +90,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do end test "the public timeline includes only public statuses for an authenticated user" do - user = insert(:user) - - conn = - build_conn() - |> assign(:user, user) + %{user: user, conn: conn} = oauth_access(["read:statuses"]) {:ok, _activity} = CommonAPI.post(user, %{"status" => "test"}) {:ok, _activity} = CommonAPI.post(user, %{"status" => "test", "visibility" => "private"}) @@ -134,11 +121,13 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do "visibility" => "private" }) - # Only direct should be visible here - res_conn = + conn_user_two = conn |> assign(:user, user_two) - |> get("api/v1/timelines/direct") + |> assign(:token, insert(:oauth_token, user: user_two, scopes: ["read:statuses"])) + + # Only direct should be visible here + res_conn = get(conn_user_two, "api/v1/timelines/direct") [status] = json_response(res_conn, :ok) @@ -149,6 +138,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do res_conn = build_conn() |> assign(:user, user_one) + |> assign(:token, insert(:oauth_token, user: user_one, scopes: ["read:statuses"])) |> get("api/v1/timelines/direct") [status] = json_response(res_conn, :ok) @@ -156,10 +146,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do assert %{"visibility" => "direct"} = status # Both should be visible here - res_conn = - conn - |> assign(:user, user_two) - |> get("api/v1/timelines/home") + res_conn = get(conn_user_two, "api/v1/timelines/home") [_s1, _s2] = json_response(res_conn, :ok) @@ -172,28 +159,23 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do }) end) - res_conn = - conn - |> assign(:user, user_two) - |> get("api/v1/timelines/direct") + res_conn = get(conn_user_two, "api/v1/timelines/direct") statuses = json_response(res_conn, :ok) assert length(statuses) == 20 res_conn = - conn - |> assign(:user, user_two) - |> get("api/v1/timelines/direct", %{max_id: List.last(statuses)["id"]}) + get(conn_user_two, "api/v1/timelines/direct", %{max_id: List.last(statuses)["id"]}) [status] = json_response(res_conn, :ok) assert status["url"] != direct.data["id"] end - test "doesn't include DMs from blocked users", %{conn: conn} do - blocker = insert(:user) + test "doesn't include DMs from blocked users" do + %{user: blocker, conn: conn} = oauth_access(["read:statuses"]) blocked = insert(:user) - user = insert(:user) + other_user = insert(:user) {:ok, _user_relationship} = User.block(blocker, blocked) {:ok, _blocked_direct} = @@ -203,15 +185,12 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do }) {:ok, direct} = - CommonAPI.post(user, %{ + CommonAPI.post(other_user, %{ "status" => "Hi @#{blocker.nickname}!", "visibility" => "direct" }) - res_conn = - conn - |> assign(:user, user) - |> get("api/v1/timelines/direct") + res_conn = get(conn, "api/v1/timelines/direct") [status] = json_response(res_conn, :ok) assert status["id"] == direct.id @@ -219,26 +198,26 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do end describe "list" do - test "list timeline", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["read:lists"]) + + test "list timeline", %{user: user, conn: conn} do other_user = insert(:user) {:ok, _activity_one} = CommonAPI.post(user, %{"status" => "Marisa is cute."}) {:ok, activity_two} = CommonAPI.post(other_user, %{"status" => "Marisa is cute."}) {:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.follow(list, other_user) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/timelines/list/#{list.id}") + conn = get(conn, "/api/v1/timelines/list/#{list.id}") assert [%{"id" => id}] = json_response(conn, :ok) assert id == to_string(activity_two.id) end - test "list timeline does not leak non-public statuses for unfollowed users", %{conn: conn} do - user = insert(:user) + test "list timeline does not leak non-public statuses for unfollowed users", %{ + user: user, + conn: conn + } do other_user = insert(:user) {:ok, activity_one} = CommonAPI.post(other_user, %{"status" => "Marisa is cute."}) @@ -251,10 +230,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do {:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.follow(list, other_user) - conn = - conn - |> assign(:user, user) - |> get("/api/v1/timelines/list/#{list.id}") + conn = get(conn, "/api/v1/timelines/list/#{list.id}") assert [%{"id" => id}] = json_response(conn, :ok) @@ -263,6 +239,8 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do end describe "hashtag" do + setup do: oauth_access(["n/a"]) + @tag capture_log: true test "hashtag timeline", %{conn: conn} do following = insert(:user) diff --git a/test/web/mastodon_api/mastodon_api_controller_test.exs b/test/web/mastodon_api/mastodon_api_controller_test.exs index 42a8779c0..c1f70f9fe 100644 --- a/test/web/mastodon_api/mastodon_api_controller_test.exs +++ b/test/web/mastodon_api/mastodon_api_controller_test.exs @@ -5,69 +5,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do use Pleroma.Web.ConnCase - alias Pleroma.Notification - alias Pleroma.Repo - alias Pleroma.Web.CommonAPI - - import Pleroma.Factory - import Tesla.Mock - - setup do - mock(fn env -> apply(HttpRequestMock, :request, [env]) end) - :ok - end - - clear_config([:rich_media, :enabled]) - - test "unimplemented follow_requests, blocks, domain blocks" do - user = insert(:user) - - ["blocks", "domain_blocks", "follow_requests"] - |> Enum.each(fn endpoint -> - conn = - build_conn() - |> assign(:user, user) - |> get("/api/v1/#{endpoint}") - - assert [] = json_response(conn, 200) - end) - end - - describe "link headers" do - test "preserves parameters in link headers", %{conn: conn} do - user = insert(:user) - other_user = insert(:user) - - {:ok, activity1} = - CommonAPI.post(other_user, %{ - "status" => "hi @#{user.nickname}", - "visibility" => "public" - }) - - {:ok, activity2} = - CommonAPI.post(other_user, %{ - "status" => "hi @#{user.nickname}", - "visibility" => "public" - }) - - notification1 = Repo.get_by(Notification, activity_id: activity1.id) - notification2 = Repo.get_by(Notification, activity_id: activity2.id) - - conn = - conn - |> assign(:user, user) - |> get("/api/v1/notifications", %{media_only: true}) - - assert [link_header] = get_resp_header(conn, "link") - assert link_header =~ ~r/media_only=true/ - assert link_header =~ ~r/min_id=#{notification2.id}/ - assert link_header =~ ~r/max_id=#{notification1.id}/ - end - end - - describe "empty_array, stubs for mastodon api" do - test "GET /api/v1/accounts/:id/identity_proofs", %{conn: conn} do - user = insert(:user) + describe "empty_array/2 (stubs)" do + test "GET /api/v1/accounts/:id/identity_proofs" do + %{user: user, conn: conn} = oauth_access(["n/a"]) res = conn @@ -78,12 +18,11 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do assert res == [] end - test "GET /api/v1/endorsements", %{conn: conn} do - user = insert(:user) + test "GET /api/v1/endorsements" do + %{conn: conn} = oauth_access(["read:accounts"]) res = conn - |> assign(:user, user) |> get("/api/v1/endorsements") |> json_response(200) @@ -91,11 +30,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do end test "GET /api/v1/trends", %{conn: conn} do - user = insert(:user) - res = conn - |> assign(:user, user) |> get("/api/v1/trends") |> json_response(200) diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs index ed6f2ecbd..2107bb85c 100644 --- a/test/web/mastodon_api/views/account_view_test.exs +++ b/test/web/mastodon_api/views/account_view_test.exs @@ -66,6 +66,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do note: "valid html", sensitive: false, pleroma: %{ + actor_type: "Person", discoverable: false }, fields: [] @@ -92,13 +93,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do test "Represent the user account for the account owner" do user = insert(:user) - notification_settings = %{ - "followers" => true, - "follows" => true, - "non_follows" => true, - "non_followers" => true - } - + notification_settings = %Pleroma.User.NotificationSetting{} privacy = user.default_scope assert %{ @@ -112,7 +107,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do insert(:user, %{ follower_count: 3, note_count: 5, - source_data: %{"type" => "Service"}, + source_data: %{}, + actor_type: "Service", nickname: "shp@shitposter.club", inserted_at: ~N[2017-08-15 15:47:06.597036] }) @@ -140,6 +136,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do note: user.bio, sensitive: false, pleroma: %{ + actor_type: "Service", discoverable: false }, fields: [] @@ -284,7 +281,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do insert(:user, %{ follower_count: 0, note_count: 5, - source_data: %{"type" => "Service"}, + source_data: %{}, + actor_type: "Service", nickname: "shp@shitposter.club", inserted_at: ~N[2017-08-15 15:47:06.597036] }) @@ -317,6 +315,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do note: user.bio, sensitive: false, pleroma: %{ + actor_type: "Service", discoverable: false }, fields: [] diff --git a/test/web/mastodon_api/views/notification_view_test.exs b/test/web/mastodon_api/views/notification_view_test.exs index ba1721e06..1fe83cb2c 100644 --- a/test/web/mastodon_api/views/notification_view_test.exs +++ b/test/web/mastodon_api/views/notification_view_test.exs @@ -134,4 +134,31 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do assert [expected] == NotificationView.render("index.json", %{notifications: [notification], for: follower}) end + + test "EmojiReaction notification" do + user = insert(:user) + other_user = insert(:user) + + {:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"}) + {:ok, _activity, _} = CommonAPI.react_with_emoji(activity.id, other_user, "☕") + + activity = Repo.get(Activity, activity.id) + + [notification] = Notification.for_user(user) + + assert notification + + expected = %{ + id: to_string(notification.id), + pleroma: %{is_seen: false}, + type: "pleroma:emoji_reaction", + emoji: "☕", + account: AccountView.render("show.json", %{user: other_user, for: user}), + status: StatusView.render("show.json", %{activity: activity, for: user}), + created_at: Utils.to_masto_date(notification.inserted_at) + } + + assert expected == + NotificationView.render("show.json", %{notification: notification, for: user}) + end end diff --git a/test/web/mastodon_api/views/status_view_test.exs b/test/web/mastodon_api/views/status_view_test.exs index bdd87a79e..25777b011 100644 --- a/test/web/mastodon_api/views/status_view_test.exs +++ b/test/web/mastodon_api/views/status_view_test.exs @@ -24,6 +24,24 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do :ok end + test "has an emoji reaction list" do + user = insert(:user) + other_user = insert(:user) + third_user = insert(:user) + {:ok, activity} = CommonAPI.post(user, %{"status" => "dae cofe??"}) + + {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, user, "☕") + {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, third_user, "🍵") + {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, other_user, "☕") + activity = Repo.get(Activity, activity.id) + status = StatusView.render("show.json", activity: activity) + + assert status[:pleroma][:emoji_reactions] == [ + %{emoji: "☕", count: 2}, + %{emoji: "🍵", count: 1} + ] + end + test "loads and returns the direct conversation id when given the `with_direct_conversation_id` option" do user = insert(:user) @@ -172,7 +190,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do spoiler_text: %{"text/plain" => HTML.strip_tags(object_data["summary"])}, expires_at: nil, direct_conversation_id: nil, - thread_muted: false + thread_muted: false, + emoji_reactions: [] } } @@ -394,6 +413,21 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do assert length(represented[:media_attachments]) == 1 end + test "a Mobilizon event" do + user = insert(:user) + + {:ok, object} = + Pleroma.Object.Fetcher.fetch_object_from_id( + "https://mobilizon.org/events/252d5816-00a3-4a89-a66f-15bf65c33e39" + ) + + %Activity{} = activity = Activity.get_create_by_object_ap_id(object.data["id"]) + + represented = StatusView.render("show.json", %{for: user, activity: activity}) + + assert represented[:id] == to_string(activity.id) + end + describe "build_tags/1" do test "it returns a a dictionary tags" do object_tags = [ diff --git a/test/web/metadata/twitter_card_test.exs b/test/web/metadata/twitter_card_test.exs index 0814006d2..85a654f52 100644 --- a/test/web/metadata/twitter_card_test.exs +++ b/test/web/metadata/twitter_card_test.exs @@ -26,7 +26,32 @@ defmodule Pleroma.Web.Metadata.Providers.TwitterCardTest do ] end - test "it does not render attachments if post is nsfw" do + test "it uses summary twittercard if post has no attachment" do + user = insert(:user, name: "Jimmy Hendriks", bio: "born 19 March 1994") + {:ok, activity} = CommonAPI.post(user, %{"status" => "HI"}) + + note = + insert(:note, %{ + data: %{ + "actor" => user.ap_id, + "tag" => [], + "id" => "https://pleroma.gov/objects/whatever", + "content" => "pleroma in a nutshell" + } + }) + + result = TwitterCard.build_tags(%{object: note, user: user, activity_id: activity.id}) + + assert [ + {:meta, [property: "twitter:title", content: Utils.user_name_string(user)], []}, + {:meta, [property: "twitter:description", content: "“pleroma in a nutshell”"], []}, + {:meta, [property: "twitter:image", content: "http://localhost:4001/images/avi.png"], + []}, + {:meta, [property: "twitter:card", content: "summary"], []} + ] == result + end + + test "it renders avatar not attachment if post is nsfw and unfurl_nsfw is disabled" do Pleroma.Config.put([Pleroma.Web.Metadata, :unfurl_nsfw], false) user = insert(:user, name: "Jimmy Hendriks", bio: "born 19 March 1994") {:ok, activity} = CommonAPI.post(user, %{"status" => "HI"}) @@ -67,7 +92,7 @@ defmodule Pleroma.Web.Metadata.Providers.TwitterCardTest do {:meta, [property: "twitter:description", content: "“pleroma in a nutshell”"], []}, {:meta, [property: "twitter:image", content: "http://localhost:4001/images/avi.png"], []}, - {:meta, [property: "twitter:card", content: "summary_large_image"], []} + {:meta, [property: "twitter:card", content: "summary"], []} ] == result end diff --git a/test/web/metadata/utils_test.exs b/test/web/metadata/utils_test.exs new file mode 100644 index 000000000..7547f2932 --- /dev/null +++ b/test/web/metadata/utils_test.exs @@ -0,0 +1,32 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.Metadata.UtilsTest do + use Pleroma.DataCase + import Pleroma.Factory + alias Pleroma.Web.Metadata.Utils + + describe "scrub_html_and_truncate/1" do + test "it returns text without encode HTML" do + user = insert(:user) + + note = + insert(:note, %{ + data: %{ + "actor" => user.ap_id, + "id" => "https://pleroma.gov/objects/whatever", + "content" => "Pleroma's really cool!" + } + }) + + assert Utils.scrub_html_and_truncate(note) == "Pleroma's really cool!" + end + end + + describe "scrub_html_and_truncate/2" do + test "it returns text without encode HTML" do + assert Utils.scrub_html_and_truncate("Pleroma's really cool!") == "Pleroma's really cool!" + end + end +end diff --git a/test/web/oauth/oauth_controller_test.exs b/test/web/oauth/oauth_controller_test.exs index beb995cd8..adeff8e25 100644 --- a/test/web/oauth/oauth_controller_test.exs +++ b/test/web/oauth/oauth_controller_test.exs @@ -450,7 +450,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do test "renders authentication page if user is already authenticated but `force_login` is tru-ish", %{app: app, conn: conn} do - token = insert(:oauth_token, app_id: app.id) + token = insert(:oauth_token, app: app) conn = conn @@ -474,7 +474,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do app: app, conn: conn } do - token = insert(:oauth_token, app_id: app.id) + token = insert(:oauth_token, app: app) conn = conn @@ -497,7 +497,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do app: app, conn: conn } do - token = insert(:oauth_token, app_id: app.id) + token = insert(:oauth_token, app: app) conn = conn @@ -523,7 +523,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do conn: conn } do unlisted_redirect_uri = "http://cross-site-request.com" - token = insert(:oauth_token, app_id: app.id) + token = insert(:oauth_token, app: app) conn = conn @@ -547,7 +547,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do app: app, conn: conn } do - token = insert(:oauth_token, app_id: app.id) + token = insert(:oauth_token, app: app) conn = conn @@ -567,33 +567,46 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do end describe "POST /oauth/authorize" do - test "redirects with oauth authorization" do - user = insert(:user) - app = insert(:oauth_app, scopes: ["read", "write", "follow"]) + test "redirects with oauth authorization, " <> + "granting requested app-supported scopes to both admin- and non-admin users" do + app_scopes = ["read", "write", "admin", "secret_scope"] + app = insert(:oauth_app, scopes: app_scopes) redirect_uri = OAuthController.default_redirect_uri(app) - conn = - build_conn() - |> post("/oauth/authorize", %{ - "authorization" => %{ - "name" => user.nickname, - "password" => "test", - "client_id" => app.client_id, - "redirect_uri" => redirect_uri, - "scope" => "read:subscope write", - "state" => "statepassed" - } - }) + non_admin = insert(:user, is_admin: false) + admin = insert(:user, is_admin: true) + scopes_subset = ["read:subscope", "write", "admin"] - target = redirected_to(conn) - assert target =~ redirect_uri + # In case scope param is missing, expecting _all_ app-supported scopes to be granted + for user <- [non_admin, admin], + {requested_scopes, expected_scopes} <- + %{scopes_subset => scopes_subset, nil => app_scopes} do + conn = + post( + build_conn(), + "/oauth/authorize", + %{ + "authorization" => %{ + "name" => user.nickname, + "password" => "test", + "client_id" => app.client_id, + "redirect_uri" => redirect_uri, + "scope" => requested_scopes, + "state" => "statepassed" + } + } + ) + + target = redirected_to(conn) + assert target =~ redirect_uri - query = URI.parse(target).query |> URI.query_decoder() |> Map.new() + query = URI.parse(target).query |> URI.query_decoder() |> Map.new() - assert %{"state" => "statepassed", "code" => code} = query - auth = Repo.get_by(Authorization, token: code) - assert auth - assert auth.scopes == ["read:subscope", "write"] + assert %{"state" => "statepassed", "code" => code} = query + auth = Repo.get_by(Authorization, token: code) + assert auth + assert auth.scopes == expected_scopes + end end test "returns 401 for wrong credentials", %{conn: conn} do @@ -623,13 +636,13 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do assert result =~ "Invalid Username/Password" end - test "returns 401 for missing scopes", %{conn: conn} do - user = insert(:user) - app = insert(:oauth_app) + test "returns 401 for missing scopes" do + user = insert(:user, is_admin: false) + app = insert(:oauth_app, scopes: ["read", "write", "admin"]) redirect_uri = OAuthController.default_redirect_uri(app) result = - conn + build_conn() |> post("/oauth/authorize", %{ "authorization" => %{ "name" => user.nickname, @@ -806,7 +819,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do |> User.confirmation_changeset(need_confirmation: true) |> User.update_and_set_cache() - refute Pleroma.User.auth_active?(user) + refute Pleroma.User.account_status(user) == :active app = insert(:oauth_app) @@ -836,7 +849,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do app = insert(:oauth_app) - conn = + resp = build_conn() |> post("/oauth/token", %{ "grant_type" => "password", @@ -845,10 +858,12 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do "client_id" => app.client_id, "client_secret" => app.client_secret }) + |> json_response(403) - assert resp = json_response(conn, 403) - assert %{"error" => _} = resp - refute Map.has_key?(resp, "access_token") + assert resp == %{ + "error" => "Your account is currently disabled", + "identifier" => "account_is_disabled" + } end test "rejects token exchange for user with password_reset_pending set to true" do @@ -862,7 +877,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do app = insert(:oauth_app, scopes: ["read", "write"]) - conn = + resp = build_conn() |> post("/oauth/token", %{ "grant_type" => "password", @@ -871,12 +886,41 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do "client_id" => app.client_id, "client_secret" => app.client_secret }) + |> json_response(403) - assert resp = json_response(conn, 403) + assert resp == %{ + "error" => "Password reset is required", + "identifier" => "password_reset_required" + } + end - assert resp["error"] == "Password reset is required" - assert resp["identifier"] == "password_reset_required" - refute Map.has_key?(resp, "access_token") + test "rejects token exchange for user with confirmation_pending set to true" do + Pleroma.Config.put([:instance, :account_activation_required], true) + password = "testpassword" + + user = + insert(:user, + password_hash: Comeonin.Pbkdf2.hashpwsalt(password), + confirmation_pending: true + ) + + app = insert(:oauth_app, scopes: ["read", "write"]) + + resp = + build_conn() + |> post("/oauth/token", %{ + "grant_type" => "password", + "username" => user.nickname, + "password" => password, + "client_id" => app.client_id, + "client_secret" => app.client_secret + }) + |> json_response(403) + + assert resp == %{ + "error" => "Your login is missing a confirmed e-mail address", + "identifier" => "missing_confirmed_email" + } end test "rejects an invalid authorization code" do diff --git a/test/web/pleroma_api/controllers/account_controller_test.exs b/test/web/pleroma_api/controllers/account_controller_test.exs index c809f510f..d17026a6b 100644 --- a/test/web/pleroma_api/controllers/account_controller_test.exs +++ b/test/web/pleroma_api/controllers/account_controller_test.exs @@ -33,7 +33,6 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do test "resend account confirmation email", %{conn: conn, user: user} do conn - |> assign(:user, user) |> post("/api/v1/pleroma/accounts/confirmation_resend?email=#{user.email}") |> json_response(:no_content) @@ -52,14 +51,12 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do end describe "PATCH /api/v1/pleroma/accounts/update_avatar" do - test "user avatar can be set", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["write:accounts"]) + + test "user avatar can be set", %{user: user, conn: conn} do avatar_image = File.read!("test/fixtures/avatar_data_uri") - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/pleroma/accounts/update_avatar", %{img: avatar_image}) + conn = patch(conn, "/api/v1/pleroma/accounts/update_avatar", %{img: avatar_image}) user = refresh_record(user) @@ -78,13 +75,8 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do assert %{"url" => _} = json_response(conn, 200) end - test "user avatar can be reset", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/pleroma/accounts/update_avatar", %{img: ""}) + test "user avatar can be reset", %{user: user, conn: conn} do + conn = patch(conn, "/api/v1/pleroma/accounts/update_avatar", %{img: ""}) user = User.get_cached_by_id(user.id) @@ -95,13 +87,10 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do end describe "PATCH /api/v1/pleroma/accounts/update_banner" do - test "can set profile banner", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["write:accounts"]) - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/pleroma/accounts/update_banner", %{"banner" => @image}) + test "can set profile banner", %{user: user, conn: conn} do + conn = patch(conn, "/api/v1/pleroma/accounts/update_banner", %{"banner" => @image}) user = refresh_record(user) assert user.banner["type"] == "Image" @@ -109,13 +98,8 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do assert %{"url" => _} = json_response(conn, 200) end - test "can reset profile banner", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/pleroma/accounts/update_banner", %{"banner" => ""}) + test "can reset profile banner", %{user: user, conn: conn} do + conn = patch(conn, "/api/v1/pleroma/accounts/update_banner", %{"banner" => ""}) user = refresh_record(user) assert user.banner == %{} @@ -125,26 +109,18 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do end describe "PATCH /api/v1/pleroma/accounts/update_background" do - test "background image can be set", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["write:accounts"]) - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/pleroma/accounts/update_background", %{"img" => @image}) + test "background image can be set", %{user: user, conn: conn} do + conn = patch(conn, "/api/v1/pleroma/accounts/update_background", %{"img" => @image}) user = refresh_record(user) assert user.background["type"] == "Image" assert %{"url" => _} = json_response(conn, 200) end - test "background image can be reset", %{conn: conn} do - user = insert(:user) - - conn = - conn - |> assign(:user, user) - |> patch("/api/v1/pleroma/accounts/update_background", %{"img" => ""}) + test "background image can be reset", %{user: user, conn: conn} do + conn = patch(conn, "/api/v1/pleroma/accounts/update_background", %{"img" => ""}) user = refresh_record(user) assert user.background == %{} @@ -155,12 +131,12 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do describe "getting favorites timeline of specified user" do setup do [current_user, user] = insert_pair(:user, hide_favorites: false) - [current_user: current_user, user: user] + %{user: current_user, conn: conn} = oauth_access(["read:favourites"], user: current_user) + [current_user: current_user, user: user, conn: conn] end test "returns list of statuses favorited by specified user", %{ conn: conn, - current_user: current_user, user: user } do [activity | _] = insert_pair(:note_activity) @@ -168,7 +144,6 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do response = conn - |> assign(:user, current_user) |> get("/api/v1/pleroma/accounts/#{user.id}/favourites") |> json_response(:ok) @@ -178,23 +153,18 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do assert like["id"] == activity.id end - test "returns favorites for specified user_id when user is not logged in", %{ - conn: conn, + test "does not return favorites for specified user_id when user is not logged in", %{ user: user } do activity = insert(:note_activity) CommonAPI.favorite(activity.id, user) - response = - conn - |> get("/api/v1/pleroma/accounts/#{user.id}/favourites") - |> json_response(:ok) - - assert length(response) == 1 + build_conn() + |> get("/api/v1/pleroma/accounts/#{user.id}/favourites") + |> json_response(403) end test "returns favorited DM only when user is logged in and he is one of recipients", %{ - conn: conn, current_user: current_user, user: user } do @@ -206,25 +176,24 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do CommonAPI.favorite(direct.id, user) - response = - conn - |> assign(:user, current_user) - |> get("/api/v1/pleroma/accounts/#{user.id}/favourites") - |> json_response(:ok) + for u <- [user, current_user] do + response = + build_conn() + |> assign(:user, u) + |> assign(:token, insert(:oauth_token, user: u, scopes: ["read:favourites"])) + |> get("/api/v1/pleroma/accounts/#{user.id}/favourites") + |> json_response(:ok) - assert length(response) == 1 + assert length(response) == 1 + end - anonymous_response = - conn - |> get("/api/v1/pleroma/accounts/#{user.id}/favourites") - |> json_response(:ok) - - assert Enum.empty?(anonymous_response) + build_conn() + |> get("/api/v1/pleroma/accounts/#{user.id}/favourites") + |> json_response(403) end test "does not return others' favorited DM when user is not one of recipients", %{ conn: conn, - current_user: current_user, user: user } do user_two = insert(:user) @@ -239,7 +208,6 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do response = conn - |> assign(:user, current_user) |> get("/api/v1/pleroma/accounts/#{user.id}/favourites") |> json_response(:ok) @@ -248,7 +216,6 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do test "paginates favorites using since_id and max_id", %{ conn: conn, - current_user: current_user, user: user } do activities = insert_list(10, :note_activity) @@ -262,7 +229,6 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do response = conn - |> assign(:user, current_user) |> get("/api/v1/pleroma/accounts/#{user.id}/favourites", %{ since_id: third_activity.id, max_id: seventh_activity.id @@ -276,7 +242,6 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do test "limits favorites using limit parameter", %{ conn: conn, - current_user: current_user, user: user } do 7 @@ -287,7 +252,6 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do response = conn - |> assign(:user, current_user) |> get("/api/v1/pleroma/accounts/#{user.id}/favourites", %{limit: "3"}) |> json_response(:ok) @@ -296,12 +260,10 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do test "returns empty response when user does not have any favorited statuses", %{ conn: conn, - current_user: current_user, user: user } do response = conn - |> assign(:user, current_user) |> get("/api/v1/pleroma/accounts/#{user.id}/favourites") |> json_response(:ok) @@ -314,79 +276,61 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do assert json_response(conn, 404) == %{"error" => "Record not found"} end - test "returns 403 error when user has hidden own favorites", %{ - conn: conn, - current_user: current_user - } do + test "returns 403 error when user has hidden own favorites", %{conn: conn} do user = insert(:user, hide_favorites: true) activity = insert(:note_activity) CommonAPI.favorite(activity.id, user) - conn = - conn - |> assign(:user, current_user) - |> get("/api/v1/pleroma/accounts/#{user.id}/favourites") + conn = get(conn, "/api/v1/pleroma/accounts/#{user.id}/favourites") assert json_response(conn, 403) == %{"error" => "Can't get favorites"} end - test "hides favorites for new users by default", %{conn: conn, current_user: current_user} do + test "hides favorites for new users by default", %{conn: conn} do user = insert(:user) activity = insert(:note_activity) CommonAPI.favorite(activity.id, user) - conn = - conn - |> assign(:user, current_user) - |> get("/api/v1/pleroma/accounts/#{user.id}/favourites") - assert user.hide_favorites + conn = get(conn, "/api/v1/pleroma/accounts/#{user.id}/favourites") + assert json_response(conn, 403) == %{"error" => "Can't get favorites"} end end describe "subscribing / unsubscribing" do - test "subscribing / unsubscribing to a user", %{conn: conn} do - user = insert(:user) + test "subscribing / unsubscribing to a user" do + %{user: user, conn: conn} = oauth_access(["follow"]) subscription_target = insert(:user) - conn = + ret_conn = conn |> assign(:user, user) |> post("/api/v1/pleroma/accounts/#{subscription_target.id}/subscribe") - assert %{"id" => _id, "subscribing" => true} = json_response(conn, 200) + assert %{"id" => _id, "subscribing" => true} = json_response(ret_conn, 200) - conn = - build_conn() - |> assign(:user, user) - |> post("/api/v1/pleroma/accounts/#{subscription_target.id}/unsubscribe") + conn = post(conn, "/api/v1/pleroma/accounts/#{subscription_target.id}/unsubscribe") assert %{"id" => _id, "subscribing" => false} = json_response(conn, 200) end end describe "subscribing" do - test "returns 404 when subscription_target not found", %{conn: conn} do - user = insert(:user) + test "returns 404 when subscription_target not found" do + %{conn: conn} = oauth_access(["write:follows"]) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/pleroma/accounts/target_id/subscribe") + conn = post(conn, "/api/v1/pleroma/accounts/target_id/subscribe") assert %{"error" => "Record not found"} = json_response(conn, 404) end end describe "unsubscribing" do - test "returns 404 when subscription_target not found", %{conn: conn} do - user = insert(:user) + test "returns 404 when subscription_target not found" do + %{conn: conn} = oauth_access(["follow"]) - conn = - conn - |> assign(:user, user) - |> post("/api/v1/pleroma/accounts/target_id/unsubscribe") + conn = post(conn, "/api/v1/pleroma/accounts/target_id/unsubscribe") assert %{"error" => "Record not found"} = json_response(conn, 404) end diff --git a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs index 3d3becefd..8e76f2f3d 100644 --- a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs +++ b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs @@ -14,6 +14,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do "emoji" ) + clear_config([:auth, :enforce_oauth_admin_scope_usage]) do + Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], false) + end + test "shared & non-shared pack information in list_packs is ok" do conn = build_conn() resp = conn |> get(emoji_api_path(conn, :list_packs)) |> json_response(200) @@ -39,9 +43,12 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do test "listing remote packs" do admin = insert(:user, is_admin: true) - conn = build_conn() |> assign(:user, admin) + %{conn: conn} = oauth_access(["admin:write"], user: admin) - resp = conn |> get(emoji_api_path(conn, :list_packs)) |> json_response(200) + resp = + build_conn() + |> get(emoji_api_path(conn, :list_packs)) + |> json_response(200) mock(fn %{method: :get, url: "https://example.com/.well-known/nodeinfo"} -> @@ -123,7 +130,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do admin = insert(:user, is_admin: true) - conn = build_conn() |> assign(:user, admin) + conn = + build_conn() + |> assign(:user, admin) + |> assign(:token, insert(:oauth_admin_token, user: admin, scopes: ["admin:write"])) assert (conn |> put_req_header("content-type", "application/json") @@ -168,8 +178,6 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do # non-shared, downloaded from the fallback URL - conn = build_conn() |> assign(:user, admin) - assert conn |> put_req_header("content-type", "application/json") |> post( @@ -205,8 +213,12 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do File.write!(pack_file, original_content) end) + admin = insert(:user, is_admin: true) + %{conn: conn} = oauth_access(["admin:write"], user: admin) + {:ok, - admin: insert(:user, is_admin: true), + admin: admin, + conn: conn, pack_file: pack_file, new_data: %{ "license" => "Test license changed", @@ -217,10 +229,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do end test "for a pack without a fallback source", ctx do - conn = build_conn() + conn = ctx[:conn] assert conn - |> assign(:user, ctx[:admin]) |> post( emoji_api_path(conn, :update_metadata, "test_pack"), %{ @@ -250,10 +261,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do "74409E2674DAA06C072729C6C8426C4CB3B7E0B85ED77792DB7A436E11D76DAF" ) - conn = build_conn() + conn = ctx[:conn] assert conn - |> assign(:user, ctx[:admin]) |> post( emoji_api_path(conn, :update_metadata, "test_pack"), %{ @@ -277,10 +287,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do new_data = Map.put(ctx[:new_data], "fallback-src", "https://nonshared-pack") - conn = build_conn() + conn = ctx[:conn] assert (conn - |> assign(:user, ctx[:admin]) |> post( emoji_api_path(conn, :update_metadata, "test_pack"), %{ @@ -304,8 +313,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do end) admin = insert(:user, is_admin: true) - - conn = build_conn() + %{conn: conn} = oauth_access(["admin:write"], user: admin) same_name = %{ "action" => "add", @@ -319,8 +327,6 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do different_name = %{same_name | "shortcode" => "blank_2"} - conn = conn |> assign(:user, admin) - assert (conn |> post(emoji_api_path(conn, :update_file, "test_pack"), same_name) |> json_response(:conflict))["error"] =~ "already exists" @@ -392,8 +398,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do end) admin = insert(:user, is_admin: true) - - conn = build_conn() |> assign(:user, admin) + %{conn: conn} = oauth_access(["admin:write"], user: admin) assert conn |> put_req_header("content-type", "application/json") @@ -432,9 +437,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do refute Map.has_key?(resp, "test_pack_for_import") admin = insert(:user, is_admin: true) + %{conn: conn} = oauth_access(["admin:write"], user: admin) assert conn - |> assign(:user, admin) |> post(emoji_api_path(conn, :import_from_fs)) |> json_response(200) == ["test_pack_for_import"] @@ -449,11 +454,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do File.write!("#{@emoji_dir_path}/test_pack_for_import/emoji.txt", emoji_txt_content) assert conn - |> assign(:user, admin) |> post(emoji_api_path(conn, :import_from_fs)) |> json_response(200) == ["test_pack_for_import"] - resp = conn |> get(emoji_api_path(conn, :list_packs)) |> json_response(200) + resp = build_conn() |> get(emoji_api_path(conn, :list_packs)) |> json_response(200) assert resp["test_pack_for_import"]["files"] == %{ "blank" => "blank.png", diff --git a/test/web/pleroma_api/controllers/mascot_controller_test.exs b/test/web/pleroma_api/controllers/mascot_controller_test.exs index ae9539b04..40c33e609 100644 --- a/test/web/pleroma_api/controllers/mascot_controller_test.exs +++ b/test/web/pleroma_api/controllers/mascot_controller_test.exs @@ -7,10 +7,8 @@ defmodule Pleroma.Web.PleromaAPI.MascotControllerTest do alias Pleroma.User - import Pleroma.Factory - - test "mascot upload", %{conn: conn} do - user = insert(:user) + test "mascot upload" do + %{conn: conn} = oauth_access(["write:accounts"]) non_image_file = %Plug.Upload{ content_type: "audio/mpeg", @@ -18,12 +16,9 @@ defmodule Pleroma.Web.PleromaAPI.MascotControllerTest do filename: "sound.mp3" } - conn = - conn - |> assign(:user, user) - |> put("/api/v1/pleroma/mascot", %{"file" => non_image_file}) + ret_conn = put(conn, "/api/v1/pleroma/mascot", %{"file" => non_image_file}) - assert json_response(conn, 415) + assert json_response(ret_conn, 415) file = %Plug.Upload{ content_type: "image/jpg", @@ -31,23 +26,18 @@ defmodule Pleroma.Web.PleromaAPI.MascotControllerTest do filename: "an_image.jpg" } - conn = - build_conn() - |> assign(:user, user) - |> put("/api/v1/pleroma/mascot", %{"file" => file}) + conn = put(conn, "/api/v1/pleroma/mascot", %{"file" => file}) assert %{"id" => _, "type" => image} = json_response(conn, 200) end - test "mascot retrieving", %{conn: conn} do - user = insert(:user) + test "mascot retrieving" do + %{user: user, conn: conn} = oauth_access(["read:accounts", "write:accounts"]) + # When user hasn't set a mascot, we should just get pleroma tan back - conn = - conn - |> assign(:user, user) - |> get("/api/v1/pleroma/mascot") + ret_conn = get(conn, "/api/v1/pleroma/mascot") - assert %{"url" => url} = json_response(conn, 200) + assert %{"url" => url} = json_response(ret_conn, 200) assert url =~ "pleroma-fox-tan-smol" # When a user sets their mascot, we should get that back @@ -57,17 +47,14 @@ defmodule Pleroma.Web.PleromaAPI.MascotControllerTest do filename: "an_image.jpg" } - conn = - build_conn() - |> assign(:user, user) - |> put("/api/v1/pleroma/mascot", %{"file" => file}) + ret_conn = put(conn, "/api/v1/pleroma/mascot", %{"file" => file}) - assert json_response(conn, 200) + assert json_response(ret_conn, 200) user = User.get_cached_by_id(user.id) conn = - build_conn() + conn |> assign(:user, user) |> get("/api/v1/pleroma/mascot") diff --git a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs index b1b59beed..3978c2ec5 100644 --- a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs +++ b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs @@ -23,6 +23,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do result = conn |> assign(:user, other_user) + |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"])) |> post("/api/v1/pleroma/statuses/#{activity.id}/react_with_emoji", %{"emoji" => "☕"}) assert %{"id" => id} = json_response(result, 200) @@ -39,6 +40,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do result = conn |> assign(:user, other_user) + |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"])) |> post("/api/v1/pleroma/statuses/#{activity.id}/unreact_with_emoji", %{"emoji" => "☕"}) assert %{"id" => id} = json_response(result, 200) @@ -60,7 +62,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do |> get("/api/v1/pleroma/statuses/#{activity.id}/emoji_reactions_by") |> json_response(200) - assert result == %{} + assert result == [] {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, other_user, "🎅") @@ -69,13 +71,13 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do |> get("/api/v1/pleroma/statuses/#{activity.id}/emoji_reactions_by") |> json_response(200) - [represented_user] = result["🎅"] + [%{"emoji" => "🎅", "count" => 1, "accounts" => [represented_user]}] = result assert represented_user["id"] == other_user.id end - test "/api/v1/pleroma/conversations/:id", %{conn: conn} do + test "/api/v1/pleroma/conversations/:id" do user = insert(:user) - other_user = insert(:user) + %{user: other_user, conn: conn} = oauth_access(["read:statuses"]) {:ok, _activity} = CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}!", "visibility" => "direct"}) @@ -84,16 +86,15 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do result = conn - |> assign(:user, other_user) |> get("/api/v1/pleroma/conversations/#{participation.id}") |> json_response(200) assert result["id"] == participation.id |> to_string() end - test "/api/v1/pleroma/conversations/:id/statuses", %{conn: conn} do + test "/api/v1/pleroma/conversations/:id/statuses" do user = insert(:user) - other_user = insert(:user) + %{user: other_user, conn: conn} = oauth_access(["read:statuses"]) third_user = insert(:user) {:ok, _activity} = @@ -113,7 +114,6 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do result = conn - |> assign(:user, other_user) |> get("/api/v1/pleroma/conversations/#{participation.id}/statuses") |> json_response(200) @@ -124,8 +124,8 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do assert [%{"id" => ^id_one}, %{"id" => ^id_two}] = result end - test "PATCH /api/v1/pleroma/conversations/:id", %{conn: conn} do - user = insert(:user) + test "PATCH /api/v1/pleroma/conversations/:id" do + %{user: user, conn: conn} = oauth_access(["write:conversations"]) other_user = insert(:user) {:ok, _activity} = CommonAPI.post(user, %{"status" => "Hi", "visibility" => "direct"}) @@ -140,7 +140,6 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do result = conn - |> assign(:user, user) |> patch("/api/v1/pleroma/conversations/#{participation.id}", %{ "recipients" => [user.id, other_user.id] }) @@ -155,9 +154,9 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do assert other_user in participation.recipients end - test "POST /api/v1/pleroma/conversations/read", %{conn: conn} do + test "POST /api/v1/pleroma/conversations/read" do user = insert(:user) - other_user = insert(:user) + %{user: other_user, conn: conn} = oauth_access(["write:notifications"]) {:ok, _activity} = CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}", "visibility" => "direct"}) @@ -172,7 +171,6 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do [%{"unread" => false}, %{"unread" => false}] = conn - |> assign(:user, other_user) |> post("/api/v1/pleroma/conversations/read", %{}) |> json_response(200) @@ -183,8 +181,9 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do end describe "POST /api/v1/pleroma/notifications/read" do - test "it marks a single notification as read", %{conn: conn} do - user1 = insert(:user) + setup do: oauth_access(["write:notifications"]) + + test "it marks a single notification as read", %{user: user1, conn: conn} do user2 = insert(:user) {:ok, activity1} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"}) {:ok, activity2} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"}) @@ -193,7 +192,6 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do response = conn - |> assign(:user, user1) |> post("/api/v1/pleroma/notifications/read", %{"id" => "#{notification1.id}"}) |> json_response(:ok) @@ -202,8 +200,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do refute Repo.get(Notification, notification2.id).seen end - test "it marks multiple notifications as read", %{conn: conn} do - user1 = insert(:user) + test "it marks multiple notifications as read", %{user: user1, conn: conn} do user2 = insert(:user) {:ok, _activity1} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"}) {:ok, _activity2} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"}) @@ -213,7 +210,6 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do [response1, response2] = conn - |> assign(:user, user1) |> post("/api/v1/pleroma/notifications/read", %{"max_id" => "#{notification2.id}"}) |> json_response(:ok) @@ -225,11 +221,8 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do end test "it returns error when notification not found", %{conn: conn} do - user1 = insert(:user) - response = conn - |> assign(:user, user1) |> post("/api/v1/pleroma/notifications/read", %{"id" => "22222222222222"}) |> json_response(:bad_request) diff --git a/test/web/pleroma_api/controllers/scrobble_controller_test.exs b/test/web/pleroma_api/controllers/scrobble_controller_test.exs index 881f8012c..2242610f1 100644 --- a/test/web/pleroma_api/controllers/scrobble_controller_test.exs +++ b/test/web/pleroma_api/controllers/scrobble_controller_test.exs @@ -6,16 +6,13 @@ defmodule Pleroma.Web.PleromaAPI.ScrobbleControllerTest do use Pleroma.Web.ConnCase alias Pleroma.Web.CommonAPI - import Pleroma.Factory describe "POST /api/v1/pleroma/scrobble" do - test "works correctly", %{conn: conn} do - user = insert(:user) + test "works correctly" do + %{conn: conn} = oauth_access(["write"]) conn = - conn - |> assign(:user, user) - |> post("/api/v1/pleroma/scrobble", %{ + post(conn, "/api/v1/pleroma/scrobble", %{ "title" => "lain radio episode 1", "artist" => "lain", "album" => "lain radio", @@ -27,8 +24,8 @@ defmodule Pleroma.Web.PleromaAPI.ScrobbleControllerTest do end describe "GET /api/v1/pleroma/accounts/:id/scrobbles" do - test "works correctly", %{conn: conn} do - user = insert(:user) + test "works correctly" do + %{user: user, conn: conn} = oauth_access(["read"]) {:ok, _activity} = CommonAPI.listen(user, %{ @@ -51,9 +48,7 @@ defmodule Pleroma.Web.PleromaAPI.ScrobbleControllerTest do "album" => "lain radio" }) - conn = - conn - |> get("/api/v1/pleroma/accounts/#{user.id}/scrobbles") + conn = get(conn, "/api/v1/pleroma/accounts/#{user.id}/scrobbles") result = json_response(conn, 200) diff --git a/test/web/push/impl_test.exs b/test/web/push/impl_test.exs index 9b554601d..acae7a734 100644 --- a/test/web/push/impl_test.exs +++ b/test/web/push/impl_test.exs @@ -6,6 +6,7 @@ defmodule Pleroma.Web.Push.ImplTest do use Pleroma.DataCase alias Pleroma.Object + alias Pleroma.User alias Pleroma.Web.CommonAPI alias Pleroma.Web.Push.Impl alias Pleroma.Web.Push.Subscription @@ -182,4 +183,50 @@ defmodule Pleroma.Web.Push.ImplTest do assert Impl.format_title(%{activity: activity}) == "New Direct Message" end + + describe "build_content/3" do + test "returns info content for direct message with enabled privacy option" do + user = insert(:user, nickname: "Bob") + user2 = insert(:user, nickname: "Rob", notification_settings: %{privacy_option: true}) + + {:ok, activity} = + CommonAPI.post(user, %{ + "visibility" => "direct", + "status" => "<Lorem ipsum dolor sit amet." + }) + + notif = insert(:notification, user: user2, activity: activity) + + actor = User.get_cached_by_ap_id(notif.activity.data["actor"]) + object = Object.normalize(activity) + + assert Impl.build_content(notif, actor, object) == %{ + body: "@Bob", + title: "New Direct Message" + } + end + + test "returns regular content for direct message with disabled privacy option" do + user = insert(:user, nickname: "Bob") + user2 = insert(:user, nickname: "Rob", notification_settings: %{privacy_option: false}) + + {:ok, activity} = + CommonAPI.post(user, %{ + "visibility" => "direct", + "status" => + "<span>Lorem ipsum dolor sit amet</span>, consectetur :firefox: adipiscing elit. Fusce sagittis finibus turpis." + }) + + notif = insert(:notification, user: user2, activity: activity) + + actor = User.get_cached_by_ap_id(notif.activity.data["actor"]) + object = Object.normalize(activity) + + assert Impl.build_content(notif, actor, object) == %{ + body: + "@Bob: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sagittis fini...", + title: "New Direct Message" + } + end + end end diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs index 8911c46b1..7166d6f0b 100644 --- a/test/web/streamer/streamer_test.exs +++ b/test/web/streamer/streamer_test.exs @@ -16,6 +16,10 @@ defmodule Pleroma.Web.StreamerTest do alias Pleroma.Web.Streamer.Worker @moduletag needs_streamer: true, capture_log: true + + @streamer_timeout 150 + @streamer_start_wait 10 + clear_config_all([:instance, :skip_thread_containment]) describe "user streams" do @@ -28,7 +32,7 @@ defmodule Pleroma.Web.StreamerTest do test "it sends notify to in the 'user' stream", %{user: user, notify: notify} do task = Task.async(fn -> - assert_receive {:text, _}, 4_000 + assert_receive {:text, _}, @streamer_timeout end) Streamer.add_socket( @@ -43,7 +47,7 @@ defmodule Pleroma.Web.StreamerTest do test "it sends notify to in the 'user:notification' stream", %{user: user, notify: notify} do task = Task.async(fn -> - assert_receive {:text, _}, 4_000 + assert_receive {:text, _}, @streamer_timeout end) Streamer.add_socket( @@ -61,7 +65,7 @@ defmodule Pleroma.Web.StreamerTest do blocked = insert(:user) {:ok, _user_relationship} = User.block(user, blocked) - task = Task.async(fn -> refute_receive {:text, _}, 4_000 end) + task = Task.async(fn -> refute_receive {:text, _}, @streamer_timeout end) Streamer.add_socket( "user:notification", @@ -79,7 +83,7 @@ defmodule Pleroma.Web.StreamerTest do user: user } do user2 = insert(:user) - task = Task.async(fn -> refute_receive {:text, _}, 4_000 end) + task = Task.async(fn -> refute_receive {:text, _}, @streamer_timeout end) Streamer.add_socket( "user:notification", @@ -97,7 +101,7 @@ defmodule Pleroma.Web.StreamerTest do user: user } do user2 = insert(:user, %{ap_id: "https://hecking-lewd-place.com/user/meanie"}) - task = Task.async(fn -> refute_receive {:text, _}, 4_000 end) + task = Task.async(fn -> refute_receive {:text, _}, @streamer_timeout end) Streamer.add_socket( "user:notification", @@ -116,7 +120,9 @@ defmodule Pleroma.Web.StreamerTest do user: user } do user2 = insert(:user) - task = Task.async(fn -> assert_receive {:text, _}, 4_000 end) + task = Task.async(fn -> assert_receive {:text, _}, @streamer_timeout end) + + Process.sleep(@streamer_start_wait) Streamer.add_socket( "user:notification", @@ -137,7 +143,7 @@ defmodule Pleroma.Web.StreamerTest do task = Task.async(fn -> - assert_receive {:text, _}, 4_000 + assert_receive {:text, _}, @streamer_timeout end) fake_socket = %StreamerSocket{ @@ -164,7 +170,7 @@ defmodule Pleroma.Web.StreamerTest do } |> Jason.encode!() - assert_receive {:text, received_event}, 4_000 + assert_receive {:text, received_event}, @streamer_timeout assert received_event == expected_event end) @@ -458,9 +464,7 @@ defmodule Pleroma.Web.StreamerTest do {:ok, activity} = CommonAPI.add_mute(user2, activity) - task = Task.async(fn -> refute_receive {:text, _}, 4_000 end) - - Process.sleep(4000) + task = Task.async(fn -> refute_receive {:text, _}, @streamer_timeout end) Streamer.add_socket( "user", @@ -482,7 +486,7 @@ defmodule Pleroma.Web.StreamerTest do task = Task.async(fn -> - assert_receive {:text, received_event}, 4_000 + assert_receive {:text, received_event}, @streamer_timeout assert %{"event" => "conversation", "payload" => received_payload} = Jason.decode!(received_event) @@ -518,13 +522,13 @@ defmodule Pleroma.Web.StreamerTest do task = Task.async(fn -> - assert_receive {:text, received_event}, 4_000 + assert_receive {:text, received_event}, @streamer_timeout assert %{"event" => "delete", "payload" => _} = Jason.decode!(received_event) - refute_receive {:text, _}, 4_000 + refute_receive {:text, _}, @streamer_timeout end) - Process.sleep(1000) + Process.sleep(@streamer_start_wait) Streamer.add_socket( "direct", @@ -555,10 +559,10 @@ defmodule Pleroma.Web.StreamerTest do task = Task.async(fn -> - assert_receive {:text, received_event}, 4_000 + assert_receive {:text, received_event}, @streamer_timeout assert %{"event" => "delete", "payload" => _} = Jason.decode!(received_event) - assert_receive {:text, received_event}, 4_000 + assert_receive {:text, received_event}, @streamer_timeout assert %{"event" => "conversation", "payload" => received_payload} = Jason.decode!(received_event) @@ -567,7 +571,7 @@ defmodule Pleroma.Web.StreamerTest do assert last_status["id"] == to_string(create_activity.id) end) - Process.sleep(1000) + Process.sleep(@streamer_start_wait) Streamer.add_socket( "direct", diff --git a/test/web/twitter_api/password_controller_test.exs b/test/web/twitter_api/password_controller_test.exs index 840c84a05..29ba7d265 100644 --- a/test/web/twitter_api/password_controller_test.exs +++ b/test/web/twitter_api/password_controller_test.exs @@ -55,7 +55,7 @@ defmodule Pleroma.Web.TwitterAPI.PasswordControllerTest do user = refresh_record(user) assert Comeonin.Pbkdf2.checkpw("test", user.password_hash) - assert length(Token.get_user_tokens(user)) == 0 + assert Enum.empty?(Token.get_user_tokens(user)) end test "it sets password_reset_pending to false", %{conn: conn} do diff --git a/test/web/twitter_api/remote_follow_controller_test.exs b/test/web/twitter_api/remote_follow_controller_test.exs new file mode 100644 index 000000000..444949375 --- /dev/null +++ b/test/web/twitter_api/remote_follow_controller_test.exs @@ -0,0 +1,235 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do + use Pleroma.Web.ConnCase + + alias Pleroma.User + alias Pleroma.Web.CommonAPI + import ExUnit.CaptureLog + import Pleroma.Factory + + setup do + Tesla.Mock.mock(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + + clear_config([:instance]) + clear_config([:frontend_configurations, :pleroma_fe]) + clear_config([:user, :deny_follow_blocked]) + + describe "GET /ostatus_subscribe - remote_follow/2" do + test "adds status to pleroma instance if the `acct` is a status", %{conn: conn} do + assert conn + |> get( + remote_follow_path(conn, :follow, %{ + acct: "https://mastodon.social/users/emelie/statuses/101849165031453009" + }) + ) + |> redirected_to() =~ "/notice/" + end + + test "show follow account page if the `acct` is a account link", %{conn: conn} do + response = + conn + |> get(remote_follow_path(conn, :follow, %{acct: "https://mastodon.social/users/emelie"})) + |> html_response(200) + + assert response =~ "Log in to follow" + end + + test "show follow page if the `acct` is a account link", %{conn: conn} do + user = insert(:user) + + response = + conn + |> assign(:user, user) + |> get(remote_follow_path(conn, :follow, %{acct: "https://mastodon.social/users/emelie"})) + |> html_response(200) + + assert response =~ "Remote follow" + end + + test "show follow page with error when user cannot fecth by `acct` link", %{conn: conn} do + user = insert(:user) + + assert capture_log(fn -> + response = + conn + |> assign(:user, user) + |> get( + remote_follow_path(conn, :follow, %{ + acct: "https://mastodon.social/users/not_found" + }) + ) + |> html_response(200) + + assert response =~ "Error fetching user" + end) =~ "Object has been deleted" + end + end + + describe "POST /ostatus_subscribe - do_follow/2 with assigned user " do + test "required `follow | write:follows` scope", %{conn: conn} do + user = insert(:user) + user2 = insert(:user) + read_token = insert(:oauth_token, user: user, scopes: ["read"]) + + assert capture_log(fn -> + response = + conn + |> assign(:user, user) + |> assign(:token, read_token) + |> post(remote_follow_path(conn, :do_follow), %{"user" => %{"id" => user2.id}}) + |> response(200) + + assert response =~ "Error following account" + end) =~ "Insufficient permissions: follow | write:follows." + end + + test "follows user", %{conn: conn} do + user = insert(:user) + user2 = insert(:user) + + response = + conn + |> assign(:user, user) + |> assign(:token, insert(:oauth_token, user: user, scopes: ["write:follows"])) + |> post(remote_follow_path(conn, :do_follow), %{"user" => %{"id" => user2.id}}) + |> response(200) + + assert response =~ "Account followed!" + assert user2.follower_address in User.following(user) + end + + test "returns error when user is deactivated", %{conn: conn} do + user = insert(:user, deactivated: true) + user2 = insert(:user) + + response = + conn + |> assign(:user, user) + |> post(remote_follow_path(conn, :do_follow), %{"user" => %{"id" => user2.id}}) + |> response(200) + + assert response =~ "Error following account" + end + + test "returns error when user is blocked", %{conn: conn} do + Pleroma.Config.put([:user, :deny_follow_blocked], true) + user = insert(:user) + user2 = insert(:user) + + {:ok, _user_block} = Pleroma.User.block(user2, user) + + response = + conn + |> assign(:user, user) + |> post(remote_follow_path(conn, :do_follow), %{"user" => %{"id" => user2.id}}) + |> response(200) + + assert response =~ "Error following account" + end + + test "returns error when followee not found", %{conn: conn} do + user = insert(:user) + + response = + conn + |> assign(:user, user) + |> post(remote_follow_path(conn, :do_follow), %{"user" => %{"id" => "jimm"}}) + |> response(200) + + assert response =~ "Error following account" + end + + test "returns success result when user already in followers", %{conn: conn} do + user = insert(:user) + user2 = insert(:user) + {:ok, _, _, _} = CommonAPI.follow(user, user2) + + response = + conn + |> assign(:user, refresh_record(user)) + |> assign(:token, insert(:oauth_token, user: user, scopes: ["write:follows"])) + |> post(remote_follow_path(conn, :do_follow), %{"user" => %{"id" => user2.id}}) + |> response(200) + + assert response =~ "Account followed!" + end + end + + describe "POST /ostatus_subscribe - follow/2 without assigned user " do + test "follows", %{conn: conn} do + user = insert(:user) + user2 = insert(:user) + + response = + conn + |> post(remote_follow_path(conn, :do_follow), %{ + "authorization" => %{"name" => user.nickname, "password" => "test", "id" => user2.id} + }) + |> response(200) + + assert response =~ "Account followed!" + assert user2.follower_address in User.following(user) + end + + test "returns error when followee not found", %{conn: conn} do + user = insert(:user) + + response = + conn + |> post(remote_follow_path(conn, :do_follow), %{ + "authorization" => %{"name" => user.nickname, "password" => "test", "id" => "jimm"} + }) + |> response(200) + + assert response =~ "Error following account" + end + + test "returns error when login invalid", %{conn: conn} do + user = insert(:user) + + response = + conn + |> post(remote_follow_path(conn, :do_follow), %{ + "authorization" => %{"name" => "jimm", "password" => "test", "id" => user.id} + }) + |> response(200) + + assert response =~ "Wrong username or password" + end + + test "returns error when password invalid", %{conn: conn} do + user = insert(:user) + user2 = insert(:user) + + response = + conn + |> post(remote_follow_path(conn, :do_follow), %{ + "authorization" => %{"name" => user.nickname, "password" => "42", "id" => user2.id} + }) + |> response(200) + + assert response =~ "Wrong username or password" + end + + test "returns error when user is blocked", %{conn: conn} do + Pleroma.Config.put([:user, :deny_follow_blocked], true) + user = insert(:user) + user2 = insert(:user) + {:ok, _user_block} = Pleroma.User.block(user2, user) + + response = + conn + |> post(remote_follow_path(conn, :do_follow), %{ + "authorization" => %{"name" => user.nickname, "password" => "test", "id" => user2.id} + }) + |> response(200) + + assert response =~ "Error following account" + end + end +end diff --git a/test/web/twitter_api/util_controller_test.exs b/test/web/twitter_api/util_controller_test.exs index 986ee01f3..5d60c0d51 100644 --- a/test/web/twitter_api/util_controller_test.exs +++ b/test/web/twitter_api/util_controller_test.exs @@ -6,11 +6,9 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do use Pleroma.Web.ConnCase use Oban.Testing, repo: Pleroma.Repo - alias Pleroma.Repo alias Pleroma.Tests.ObanHelpers alias Pleroma.User - alias Pleroma.Web.CommonAPI - import ExUnit.CaptureLog + import Pleroma.Factory import Mock @@ -24,21 +22,20 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do clear_config([:user, :deny_follow_blocked]) describe "POST /api/pleroma/follow_import" do + setup do: oauth_access(["follow"]) + test "it returns HTTP 200", %{conn: conn} do - user1 = insert(:user) user2 = insert(:user) response = conn - |> assign(:user, user1) |> post("/api/pleroma/follow_import", %{"list" => "#{user2.ap_id}"}) |> json_response(:ok) assert response == "job started" end - test "it imports follow lists from file", %{conn: conn} do - user1 = insert(:user) + test "it imports follow lists from file", %{user: user1, conn: conn} do user2 = insert(:user) with_mocks([ @@ -49,7 +46,6 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do ]) do response = conn - |> assign(:user, user1) |> post("/api/pleroma/follow_import", %{"list" => %Plug.Upload{path: "follow_list.txt"}}) |> json_response(:ok) @@ -67,12 +63,10 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do end test "it imports new-style mastodon follow lists", %{conn: conn} do - user1 = insert(:user) user2 = insert(:user) response = conn - |> assign(:user, user1) |> post("/api/pleroma/follow_import", %{ "list" => "Account address,Show boosts\n#{user2.ap_id},true" }) @@ -81,7 +75,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do assert response == "job started" end - test "requires 'follow' or 'write:follows' permissions", %{conn: conn} do + test "requires 'follow' or 'write:follows' permissions" do token1 = insert(:oauth_token, scopes: ["read", "write"]) token2 = insert(:oauth_token, scopes: ["follow"]) token3 = insert(:oauth_token, scopes: ["something"]) @@ -89,7 +83,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do for token <- [token1, token2, token3] do conn = - conn + build_conn() |> put_req_header("authorization", "Bearer #{token.token}") |> post("/api/pleroma/follow_import", %{"list" => "#{another_user.ap_id}"}) @@ -104,21 +98,21 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do end describe "POST /api/pleroma/blocks_import" do + # Note: "follow" or "write:blocks" permission is required + setup do: oauth_access(["write:blocks"]) + test "it returns HTTP 200", %{conn: conn} do - user1 = insert(:user) user2 = insert(:user) response = conn - |> assign(:user, user1) |> post("/api/pleroma/blocks_import", %{"list" => "#{user2.ap_id}"}) |> json_response(:ok) assert response == "job started" end - test "it imports blocks users from file", %{conn: conn} do - user1 = insert(:user) + test "it imports blocks users from file", %{user: user1, conn: conn} do user2 = insert(:user) user3 = insert(:user) @@ -127,7 +121,6 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do ]) do response = conn - |> assign(:user, user1) |> post("/api/pleroma/blocks_import", %{"list" => %Plug.Upload{path: "blocks_list.txt"}}) |> json_response(:ok) @@ -146,24 +139,40 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do end describe "PUT /api/pleroma/notification_settings" do - test "it updates notification settings", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["write:accounts"]) + test "it updates notification settings", %{user: user, conn: conn} do conn - |> assign(:user, user) |> put("/api/pleroma/notification_settings", %{ "followers" => false, "bar" => 1 }) |> json_response(:ok) - user = Repo.get(User, user.id) + user = refresh_record(user) - assert %{ - "followers" => false, - "follows" => true, - "non_follows" => true, - "non_followers" => true + assert %Pleroma.User.NotificationSetting{ + followers: false, + follows: true, + non_follows: true, + non_followers: true, + privacy_option: false + } == user.notification_settings + end + + test "it updates notification privacy option", %{user: user, conn: conn} do + conn + |> put("/api/pleroma/notification_settings", %{"privacy_option" => "1"}) + |> json_response(:ok) + + user = refresh_record(user) + + assert %Pleroma.User.NotificationSetting{ + followers: true, + follows: true, + non_follows: true, + non_followers: true, + privacy_option: true } == user.notification_settings end end @@ -308,196 +317,6 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do end end - describe "GET /ostatus_subscribe - remote_follow/2" do - test "adds status to pleroma instance if the `acct` is a status", %{conn: conn} do - conn = - get( - conn, - "/ostatus_subscribe?acct=https://mastodon.social/users/emelie/statuses/101849165031453009" - ) - - assert redirected_to(conn) =~ "/notice/" - end - - test "show follow account page if the `acct` is a account link", %{conn: conn} do - response = - get( - conn, - "/ostatus_subscribe?acct=https://mastodon.social/users/emelie" - ) - - assert html_response(response, 200) =~ "Log in to follow" - end - - test "show follow page if the `acct` is a account link", %{conn: conn} do - user = insert(:user) - - response = - conn - |> assign(:user, user) - |> get("/ostatus_subscribe?acct=https://mastodon.social/users/emelie") - - assert html_response(response, 200) =~ "Remote follow" - end - - test "show follow page with error when user cannot fecth by `acct` link", %{conn: conn} do - user = insert(:user) - - assert capture_log(fn -> - response = - conn - |> assign(:user, user) - |> get("/ostatus_subscribe?acct=https://mastodon.social/users/not_found") - - assert html_response(response, 200) =~ "Error fetching user" - end) =~ "Object has been deleted" - end - end - - describe "POST /ostatus_subscribe - do_remote_follow/2 with assigned user " do - test "follows user", %{conn: conn} do - user = insert(:user) - user2 = insert(:user) - - response = - conn - |> assign(:user, user) - |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) - |> response(200) - - assert response =~ "Account followed!" - assert user2.follower_address in User.following(user) - end - - test "returns error when user is deactivated", %{conn: conn} do - user = insert(:user, deactivated: true) - user2 = insert(:user) - - response = - conn - |> assign(:user, user) - |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) - |> response(200) - - assert response =~ "Error following account" - end - - test "returns error when user is blocked", %{conn: conn} do - Pleroma.Config.put([:user, :deny_follow_blocked], true) - user = insert(:user) - user2 = insert(:user) - - {:ok, _user_block} = Pleroma.User.block(user2, user) - - response = - conn - |> assign(:user, user) - |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) - |> response(200) - - assert response =~ "Error following account" - end - - test "returns error when followee not found", %{conn: conn} do - user = insert(:user) - - response = - conn - |> assign(:user, user) - |> post("/ostatus_subscribe", %{"user" => %{"id" => "jimm"}}) - |> response(200) - - assert response =~ "Error following account" - end - - test "returns success result when user already in followers", %{conn: conn} do - user = insert(:user) - user2 = insert(:user) - {:ok, _, _, _} = CommonAPI.follow(user, user2) - - response = - conn - |> assign(:user, refresh_record(user)) - |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) - |> response(200) - - assert response =~ "Account followed!" - end - end - - describe "POST /ostatus_subscribe - do_remote_follow/2 without assigned user " do - test "follows", %{conn: conn} do - user = insert(:user) - user2 = insert(:user) - - response = - conn - |> post("/ostatus_subscribe", %{ - "authorization" => %{"name" => user.nickname, "password" => "test", "id" => user2.id} - }) - |> response(200) - - assert response =~ "Account followed!" - assert user2.follower_address in User.following(user) - end - - test "returns error when followee not found", %{conn: conn} do - user = insert(:user) - - response = - conn - |> post("/ostatus_subscribe", %{ - "authorization" => %{"name" => user.nickname, "password" => "test", "id" => "jimm"} - }) - |> response(200) - - assert response =~ "Error following account" - end - - test "returns error when login invalid", %{conn: conn} do - user = insert(:user) - - response = - conn - |> post("/ostatus_subscribe", %{ - "authorization" => %{"name" => "jimm", "password" => "test", "id" => user.id} - }) - |> response(200) - - assert response =~ "Wrong username or password" - end - - test "returns error when password invalid", %{conn: conn} do - user = insert(:user) - user2 = insert(:user) - - response = - conn - |> post("/ostatus_subscribe", %{ - "authorization" => %{"name" => user.nickname, "password" => "42", "id" => user2.id} - }) - |> response(200) - - assert response =~ "Wrong username or password" - end - - test "returns error when user is blocked", %{conn: conn} do - Pleroma.Config.put([:user, :deny_follow_blocked], true) - user = insert(:user) - user2 = insert(:user) - {:ok, _user_block} = Pleroma.User.block(user2, user) - - response = - conn - |> post("/ostatus_subscribe", %{ - "authorization" => %{"name" => user.nickname, "password" => "test", "id" => user2.id} - }) - |> response(200) - - assert response =~ "Error following account" - end - end - describe "GET /api/pleroma/healthcheck" do clear_config([:instance, :healthcheck]) @@ -532,7 +351,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do end end - test "returns 503 when healthcheck enabled and health is false", %{conn: conn} do + test "returns 503 when healthcheck enabled and health is false", %{conn: conn} do Pleroma.Config.put([:instance, :healthcheck], true) with_mock Pleroma.Healthcheck, @@ -554,12 +373,11 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do end describe "POST /api/pleroma/disable_account" do - test "it returns HTTP 200", %{conn: conn} do - user = insert(:user) + setup do: oauth_access(["write:accounts"]) + test "with valid permissions and password, it disables the account", %{conn: conn, user: user} do response = conn - |> assign(:user, user) |> post("/api/pleroma/disable_account", %{"password" => "test"}) |> json_response(:ok) @@ -571,12 +389,11 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do assert user.deactivated == true end - test "it returns returns when password invalid", %{conn: conn} do + test "with valid permissions and invalid password, it returns an error", %{conn: conn} do user = insert(:user) response = conn - |> assign(:user, user) |> post("/api/pleroma/disable_account", %{"password" => "test1"}) |> json_response(:ok) @@ -646,7 +463,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do "https://social.heldscal.la/main/ostatussub?profile=#{user.ap_id}" end - test "it renders form with error when use not found", %{conn: conn} do + test "it renders form with error when user not found", %{conn: conn} do user2 = insert(:user, ap_id: "shp@social.heldscal.la") response = @@ -671,29 +488,21 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do end end - defp with_credentials(conn, username, password) do - header_content = "Basic " <> Base.encode64("#{username}:#{password}") - put_req_header(conn, "authorization", header_content) - end - - defp valid_user(_context) do - user = insert(:user) - [user: user] - end - describe "POST /api/pleroma/change_email" do - setup [:valid_user] + setup do: oauth_access(["write:accounts"]) + + test "without permissions", %{conn: conn} do + conn = + conn + |> assign(:token, nil) + |> post("/api/pleroma/change_email") - test "without credentials", %{conn: conn} do - conn = post(conn, "/api/pleroma/change_email") - assert json_response(conn, 403) == %{"error" => "Invalid credentials."} + assert json_response(conn, 403) == %{"error" => "Insufficient permissions: write:accounts."} end - test "with credentials and invalid password", %{conn: conn, user: current_user} do + test "with proper permissions and invalid password", %{conn: conn} do conn = - conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/change_email", %{ + post(conn, "/api/pleroma/change_email", %{ "password" => "hi", "email" => "test@test.com" }) @@ -701,14 +510,11 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do assert json_response(conn, 200) == %{"error" => "Invalid password."} end - test "with credentials, valid password and invalid email", %{ - conn: conn, - user: current_user + test "with proper permissions, valid password and invalid email", %{ + conn: conn } do conn = - conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/change_email", %{ + post(conn, "/api/pleroma/change_email", %{ "password" => "test", "email" => "foobar" }) @@ -716,28 +522,22 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do assert json_response(conn, 200) == %{"error" => "Email has invalid format."} end - test "with credentials, valid password and no email", %{ - conn: conn, - user: current_user + test "with proper permissions, valid password and no email", %{ + conn: conn } do conn = - conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/change_email", %{ + post(conn, "/api/pleroma/change_email", %{ "password" => "test" }) assert json_response(conn, 200) == %{"error" => "Email can't be blank."} end - test "with credentials, valid password and blank email", %{ - conn: conn, - user: current_user + test "with proper permissions, valid password and blank email", %{ + conn: conn } do conn = - conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/change_email", %{ + post(conn, "/api/pleroma/change_email", %{ "password" => "test", "email" => "" }) @@ -745,16 +545,13 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do assert json_response(conn, 200) == %{"error" => "Email can't be blank."} end - test "with credentials, valid password and non unique email", %{ - conn: conn, - user: current_user + test "with proper permissions, valid password and non unique email", %{ + conn: conn } do user = insert(:user) conn = - conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/change_email", %{ + post(conn, "/api/pleroma/change_email", %{ "password" => "test", "email" => user.email }) @@ -762,14 +559,11 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do assert json_response(conn, 200) == %{"error" => "Email has already been taken."} end - test "with credentials, valid password and valid email", %{ - conn: conn, - user: current_user + test "with proper permissions, valid password and valid email", %{ + conn: conn } do conn = - conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/change_email", %{ + post(conn, "/api/pleroma/change_email", %{ "password" => "test", "email" => "cofe@foobar.com" }) @@ -779,18 +573,20 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do end describe "POST /api/pleroma/change_password" do - setup [:valid_user] + setup do: oauth_access(["write:accounts"]) - test "without credentials", %{conn: conn} do - conn = post(conn, "/api/pleroma/change_password") - assert json_response(conn, 403) == %{"error" => "Invalid credentials."} + test "without permissions", %{conn: conn} do + conn = + conn + |> assign(:token, nil) + |> post("/api/pleroma/change_password") + + assert json_response(conn, 403) == %{"error" => "Insufficient permissions: write:accounts."} end - test "with credentials and invalid password", %{conn: conn, user: current_user} do + test "with proper permissions and invalid password", %{conn: conn} do conn = - conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/change_password", %{ + post(conn, "/api/pleroma/change_password", %{ "password" => "hi", "new_password" => "newpass", "new_password_confirmation" => "newpass" @@ -799,14 +595,12 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do assert json_response(conn, 200) == %{"error" => "Invalid password."} end - test "with credentials, valid password and new password and confirmation not matching", %{ - conn: conn, - user: current_user - } do + test "with proper permissions, valid password and new password and confirmation not matching", + %{ + conn: conn + } do conn = - conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/change_password", %{ + post(conn, "/api/pleroma/change_password", %{ "password" => "test", "new_password" => "newpass", "new_password_confirmation" => "notnewpass" @@ -817,14 +611,11 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do } end - test "with credentials, valid password and invalid new password", %{ - conn: conn, - user: current_user + test "with proper permissions, valid password and invalid new password", %{ + conn: conn } do conn = - conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/change_password", %{ + post(conn, "/api/pleroma/change_password", %{ "password" => "test", "new_password" => "", "new_password_confirmation" => "" @@ -835,51 +626,48 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do } end - test "with credentials, valid password and matching new password and confirmation", %{ + test "with proper permissions, valid password and matching new password and confirmation", %{ conn: conn, - user: current_user + user: user } do conn = - conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/change_password", %{ + post(conn, "/api/pleroma/change_password", %{ "password" => "test", "new_password" => "newpass", "new_password_confirmation" => "newpass" }) assert json_response(conn, 200) == %{"status" => "success"} - fetched_user = User.get_cached_by_id(current_user.id) + fetched_user = User.get_cached_by_id(user.id) assert Comeonin.Pbkdf2.checkpw("newpass", fetched_user.password_hash) == true end end describe "POST /api/pleroma/delete_account" do - setup [:valid_user] - - test "without credentials", %{conn: conn} do - conn = post(conn, "/api/pleroma/delete_account") - assert json_response(conn, 403) == %{"error" => "Invalid credentials."} - end + setup do: oauth_access(["write:accounts"]) - test "with credentials and invalid password", %{conn: conn, user: current_user} do + test "without permissions", %{conn: conn} do conn = conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/delete_account", %{"password" => "hi"}) + |> assign(:token, nil) + |> post("/api/pleroma/delete_account") - assert json_response(conn, 200) == %{"error" => "Invalid password."} + assert json_response(conn, 403) == + %{"error" => "Insufficient permissions: write:accounts."} end - test "with credentials and valid password", %{conn: conn, user: current_user} do - conn = - conn - |> with_credentials(current_user.nickname, "test") - |> post("/api/pleroma/delete_account", %{"password" => "test"}) + test "with proper permissions and wrong or missing password", %{conn: conn} do + for params <- [%{"password" => "hi"}, %{}] do + ret_conn = post(conn, "/api/pleroma/delete_account", params) + + assert json_response(ret_conn, 200) == %{"error" => "Invalid password."} + end + end + + test "with proper permissions and valid password", %{conn: conn} do + conn = post(conn, "/api/pleroma/delete_account", %{"password" => "test"}) assert json_response(conn, 200) == %{"status" => "success"} - # Wait a second for the started task to end - :timer.sleep(1000) end end end |