diff options
Diffstat (limited to 'test')
89 files changed, 3742 insertions, 1239 deletions
diff --git a/test/activity_test.exs b/test/activity_test.exs index 55849c522..36c718869 100644 --- a/test/activity_test.exs +++ b/test/activity_test.exs @@ -1,17 +1,22 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.ActivityTest do use Pleroma.DataCase + alias Pleroma.Activity import Pleroma.Factory test "returns an activity by it's AP id" do activity = insert(:note_activity) - found_activity = Pleroma.Activity.get_by_ap_id(activity.data["id"]) + found_activity = Activity.get_by_ap_id(activity.data["id"]) assert activity == found_activity end test "returns activities by it's objects AP ids" do activity = insert(:note_activity) - [found_activity] = Pleroma.Activity.all_by_object_ap_id(activity.data["object"]["id"]) + [found_activity] = Activity.all_by_object_ap_id(activity.data["object"]["id"]) assert activity == found_activity end @@ -19,8 +24,7 @@ defmodule Pleroma.ActivityTest do test "returns the activity that created an object" do activity = insert(:note_activity) - found_activity = - Pleroma.Activity.get_create_activity_by_object_ap_id(activity.data["object"]["id"]) + found_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"]["id"]) assert activity == found_activity end diff --git a/test/captcha_test.exs b/test/captcha_test.exs new file mode 100644 index 000000000..7f559ac72 --- /dev/null +++ b/test/captcha_test.exs @@ -0,0 +1,44 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.CaptchaTest do + use ExUnit.Case + + import Tesla.Mock + + alias Pleroma.Captcha.Kocaptcha + + @ets_options [:ordered_set, :private, :named_table, {:read_concurrency, true}] + + describe "Kocaptcha" do + setup do + ets_name = Kocaptcha.Ets + ^ets_name = :ets.new(ets_name, @ets_options) + + mock(fn + %{method: :get, url: "https://captcha.kotobank.ch/new"} -> + json(%{ + md5: "63615261b77f5354fb8c4e4986477555", + token: "afa1815e14e29355e6c8f6b143a39fa2", + url: "/captchas/afa1815e14e29355e6c8f6b143a39fa2.png" + }) + end) + + :ok + end + + test "new and validate" do + assert Kocaptcha.new() == %{ + type: :kocaptcha, + token: "afa1815e14e29355e6c8f6b143a39fa2", + url: "https://captcha.kotobank.ch/captchas/afa1815e14e29355e6c8f6b143a39fa2.png" + } + + assert Kocaptcha.validate( + "afa1815e14e29355e6c8f6b143a39fa2", + "7oEy8c" + ) + end + end +end diff --git a/test/config_test.exs b/test/config_test.exs index 0124544c8..0a6f0395a 100644 --- a/test/config_test.exs +++ b/test/config_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.ConfigTest do use ExUnit.Case @@ -53,4 +57,19 @@ defmodule Pleroma.ConfigTest do assert Pleroma.Config.get([:instance, :config_test]) == true assert Pleroma.Config.get([:instance, :config_nested_test, :x]) == true end + + test "delete/1 with a key" do + Pleroma.Config.put([:delete_me], :delete_me) + Pleroma.Config.delete([:delete_me]) + assert Pleroma.Config.get([:delete_me]) == nil + end + + test "delete/2 with a list of keys" do + Pleroma.Config.put([:delete_me], hello: "world", world: "Hello") + Pleroma.Config.delete([:delete_me, :world]) + assert Pleroma.Config.get([:delete_me]) == [hello: "world"] + Pleroma.Config.put([:delete_me, :delete_me], hello: "world", world: "Hello") + Pleroma.Config.delete([:delete_me, :delete_me, :world]) + assert Pleroma.Config.get([:delete_me, :delete_me]) == [hello: "world"] + end end diff --git a/test/filter_test.exs b/test/filter_test.exs index 509c15317..b31c68efd 100644 --- a/test/filter_test.exs +++ b/test/filter_test.exs @@ -1,9 +1,12 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.FilterTest do - alias Pleroma.{User, Repo} + alias Pleroma.Repo use Pleroma.DataCase import Pleroma.Factory - import Ecto.Query describe "creating filters" do test "creating one filter" do @@ -99,7 +102,7 @@ defmodule Pleroma.FilterTest do context: ["home"] } - {:ok, filter} = Pleroma.Filter.create(query) + {:ok, _filter} = Pleroma.Filter.create(query) {:ok, filter} = Pleroma.Filter.delete(query) assert is_nil(Repo.get(Pleroma.Filter, filter.filter_id)) end diff --git a/test/fixtures/httpoison_mock/framatube.org_host_meta b/test/fixtures/httpoison_mock/framatube.org_host_meta new file mode 100644 index 000000000..91516ff6d --- /dev/null +++ b/test/fixtures/httpoison_mock/framatube.org_host_meta @@ -0,0 +1,2 @@ +<?xml version="1.0" encoding="UTF-8"?> +<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"><hm:Host xmlns:hm="http://host-meta.net/xrd/1.0">framatube.org</hm:Host><Link rel="lrdd" template="http://framatube.org/main/xrd?uri={uri}"><Title>Resource Descriptor</Title></Link></XRD> diff --git a/test/fixtures/httpoison_mock/gerzilla.de_host_meta b/test/fixtures/httpoison_mock/gerzilla.de_host_meta new file mode 100644 index 000000000..fae8f37eb --- /dev/null +++ b/test/fixtures/httpoison_mock/gerzilla.de_host_meta @@ -0,0 +1,10 @@ +<?xml version='1.0' encoding='UTF-8'?><XRD xmlns='http://docs.oasis-open.org/ns/xri/xrd-1.0' + xmlns:hm='http://host-meta.net/xrd/1.0'> + + <hm:Host>gerzilla.de</hm:Host> + + <Link rel='lrdd' type="application/xrd+xml" template='https://gerzilla.de/xrd/?uri={uri}' /> + <Link rel="http://oexchange.org/spec/0.8/rel/resident-target" type="application/xrd+xml" + href="https://gerzilla.de/oexchange/xrd" /> + +</XRD> diff --git a/test/fixtures/httpoison_mock/gnusocial.de_host_meta b/test/fixtures/httpoison_mock/gnusocial.de_host_meta new file mode 100644 index 000000000..a4affb102 --- /dev/null +++ b/test/fixtures/httpoison_mock/gnusocial.de_host_meta @@ -0,0 +1,2 @@ +<?xml version="1.0" encoding="UTF-8"?> +<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"><hm:Host xmlns:hm="http://host-meta.net/xrd/1.0">gnusocial.de</hm:Host><Link rel="lrdd" template="http://gnusocial.de/main/xrd?uri={uri}"><Title>Resource Descriptor</Title></Link></XRD> diff --git a/test/formatter_test.exs b/test/formatter_test.exs index 13084baa7..c76149e38 100644 --- a/test/formatter_test.exs +++ b/test/formatter_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.FormatterTest do alias Pleroma.Formatter alias Pleroma.User @@ -5,12 +9,29 @@ defmodule Pleroma.FormatterTest do import Pleroma.Factory + setup_all do + Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + describe ".add_hashtag_links" do test "turns hashtags into links" do text = "I love #cofe and #2hu" expected_text = - "I love <a href='http://localhost:4001/tag/cofe' rel='tag'>#cofe</a> and <a href='http://localhost:4001/tag/2hu' rel='tag'>#2hu</a>" + "I love <a data-tag='cofe' href='http://localhost:4001/tag/cofe' rel='tag'>#cofe</a> and <a data-tag='2hu' href='http://localhost:4001/tag/2hu' rel='tag'>#2hu</a>" + + tags = Formatter.parse_tags(text) + + assert expected_text == + Formatter.add_hashtag_links({[], text}, tags) |> Formatter.finalize() + end + + test "does not turn html characters to tags" do + text = "Fact #3: pleroma does what mastodon't" + + expected_text = + "Fact <a data-tag='3' href='http://localhost:4001/tag/3' rel='tag'>#3</a>: pleroma does what mastodon't" tags = Formatter.parse_tags(text) @@ -104,13 +125,13 @@ defmodule Pleroma.FormatterTest do describe "add_user_links" do test "gives a replacement for user links" do - text = "@gsimg According to @archaeme, that is @daggsy. Also hello @archaeme@archae.me" + text = "@gsimg According to @archa_eme_, that is @daggsy. Also hello @archaeme@archae.me" gsimg = insert(:user, %{nickname: "gsimg"}) archaeme = insert(:user, %{ - nickname: "archaeme", - info: %{"source_data" => %{"url" => "https://archeme/@archaeme"}} + nickname: "archa_eme_", + info: %Pleroma.User.Info{source_data: %{"url" => "https://archeme/@archa_eme_"}} }) archaeme_remote = insert(:user, %{nickname: "archaeme@archae.me"}) @@ -123,11 +144,11 @@ defmodule Pleroma.FormatterTest do Enum.each(subs, fn {uuid, _} -> assert String.contains?(text, uuid) end) expected_text = - "<span><a class='mention' href='#{gsimg.ap_id}'>@<span>gsimg</span></a></span> According to <span><a class='mention' href='#{ - "https://archeme/@archaeme" - }'>@<span>archaeme</span></a></span>, that is @daggsy. Also hello <span><a class='mention' href='#{ - archaeme_remote.ap_id - }'>@<span>archaeme</span></a></span>" + "<span><a data-user='#{gsimg.id}' class='mention' href='#{gsimg.ap_id}'>@<span>gsimg</span></a></span> According to <span><a data-user='#{ + archaeme.id + }' class='mention' href='#{"https://archeme/@archa_eme_"}'>@<span>archa_eme_</span></a></span>, that is @daggsy. Also hello <span><a data-user='#{ + archaeme_remote.id + }' class='mention' href='#{archaeme_remote.ap_id}'>@<span>archaeme</span></a></span>" assert expected_text == Formatter.finalize({subs, text}) end @@ -145,7 +166,7 @@ defmodule Pleroma.FormatterTest do Enum.each(subs, fn {uuid, _} -> assert String.contains?(text, uuid) end) expected_text = - "<span><a class='mention' href='#{mike.ap_id}'>@<span>mike</span></a></span> test" + "<span><a data-user='#{mike.id}' class='mention' href='#{mike.ap_id}'>@<span>mike</span></a></span> test" assert expected_text == Formatter.finalize({subs, text}) end @@ -161,7 +182,9 @@ defmodule Pleroma.FormatterTest do assert length(subs) == 1 Enum.each(subs, fn {uuid, _} -> assert String.contains?(text, uuid) end) - expected_text = "<span><a class='mention' href='#{o.ap_id}'>@<span>o</span></a></span> hi" + expected_text = + "<span><a data-user='#{o.id}' class='mention' href='#{o.ap_id}'>@<span>o</span></a></span> hi" + assert expected_text == Formatter.finalize({subs, text}) end @@ -196,8 +219,11 @@ defmodule Pleroma.FormatterTest do end test "it can parse mentions and return the relevant users" do - text = "@gsimg According to @archaeme, that is @daggsy. Also hello @archaeme@archae.me" + text = + "@@gsimg According to @archaeme, that is @daggsy. Also hello @archaeme@archae.me and @o and @@@jimm" + o = insert(:user, %{nickname: "o"}) + jimm = insert(:user, %{nickname: "jimm"}) gsimg = insert(:user, %{nickname: "gsimg"}) archaeme = insert(:user, %{nickname: "archaeme"}) archaeme_remote = insert(:user, %{nickname: "archaeme@archae.me"}) @@ -205,7 +231,9 @@ defmodule Pleroma.FormatterTest do expected_result = [ {"@gsimg", gsimg}, {"@archaeme", archaeme}, - {"@archaeme@archae.me", archaeme_remote} + {"@archaeme@archae.me", archaeme_remote}, + {"@o", o}, + {"@jimm", jimm} ] assert Formatter.parse_mentions(text) == expected_result @@ -250,4 +278,23 @@ defmodule Pleroma.FormatterTest do text = nil assert Formatter.get_emoji(text) == [] end + + describe "/mentions_escape" do + test "it returns text with escaped mention names" do + text = """ + @a_breakin_glass@cybre.space + (also, little voice inside my head thinking "maybe this will encourage people + pronouncing it properly instead of saying _raKEWdo_ ") + """ + + escape_text = """ + @a\\_breakin\\_glass@cybre\\.space + (also, little voice inside my head thinking \"maybe this will encourage people + pronouncing it properly instead of saying _raKEWdo_ \") + """ + + mentions = [{"@a_breakin_glass@cybre.space", %{}}] + assert Formatter.mentions_escape(text, mentions) == escape_text + end + end end diff --git a/test/html_test.exs b/test/html_test.exs index f7150759b..29cab17f3 100644 --- a/test/html_test.exs +++ b/test/html_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.HTMLTest do alias Pleroma.HTML use Pleroma.DataCase diff --git a/test/http_test.exs b/test/http_test.exs new file mode 100644 index 000000000..5f9522cf0 --- /dev/null +++ b/test/http_test.exs @@ -0,0 +1,59 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.HTTPTest do + use Pleroma.DataCase + import Tesla.Mock + + setup do + mock(fn + %{ + method: :get, + url: "http://example.com/hello", + headers: [{"content-type", "application/json"}] + } -> + json(%{"my" => "data"}) + + %{method: :get, url: "http://example.com/hello"} -> + %Tesla.Env{status: 200, body: "hello"} + + %{method: :post, url: "http://example.com/world"} -> + %Tesla.Env{status: 200, body: "world"} + end) + + :ok + end + + describe "get/1" do + test "returns successfully result" do + assert Pleroma.HTTP.get("http://example.com/hello") == { + :ok, + %Tesla.Env{status: 200, body: "hello"} + } + end + end + + describe "get/2 (with headers)" do + test "returns successfully result for json content-type" do + assert Pleroma.HTTP.get("http://example.com/hello", [{"content-type", "application/json"}]) == + { + :ok, + %Tesla.Env{ + status: 200, + body: "{\"my\":\"data\"}", + headers: [{"content-type", "application/json"}] + } + } + end + end + + describe "post/2" do + test "returns successfully result" do + assert Pleroma.HTTP.post("http://example.com/world", "") == { + :ok, + %Tesla.Env{status: 200, body: "world"} + } + end + end +end diff --git a/test/integration/mastodon_websocket_test.exs b/test/integration/mastodon_websocket_test.exs new file mode 100644 index 000000000..03aabf12c --- /dev/null +++ b/test/integration/mastodon_websocket_test.exs @@ -0,0 +1,104 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Integration.MastodonWebsocketTest do + use Pleroma.DataCase + + import Pleroma.Factory + + alias Pleroma.Web.CommonAPI + alias Pleroma.Web.OAuth + alias Pleroma.Integration.WebsocketClient + alias Pleroma.Web.Streamer + + @path Pleroma.Web.Endpoint.url() + |> URI.parse() + |> Map.put(:scheme, "ws") + |> Map.put(:path, "/api/v1/streaming") + |> URI.to_string() + + setup do + GenServer.start(Streamer, %{}, name: Streamer) + + on_exit(fn -> + if pid = Process.whereis(Streamer) do + Process.exit(pid, :kill) + end + end) + end + + def start_socket(qs \\ nil, headers \\ []) do + path = + case qs do + nil -> @path + qs -> @path <> qs + end + + WebsocketClient.start_link(self(), path, headers) + end + + test "refuses invalid requests" do + assert {:error, {400, _}} = start_socket() + assert {:error, {404, _}} = start_socket("?stream=ncjdk") + end + + test "requires authentication and a valid token for protected streams" do + assert {:error, {403, _}} = start_socket("?stream=user&access_token=aaaaaaaaaaaa") + assert {:error, {403, _}} = start_socket("?stream=user") + end + + test "allows public streams without authentication" do + assert {:ok, _} = start_socket("?stream=public") + assert {:ok, _} = start_socket("?stream=public:local") + assert {:ok, _} = start_socket("?stream=hashtag&tag=lain") + end + + test "receives well formatted events" do + user = insert(:user) + {:ok, _} = start_socket("?stream=public") + {:ok, activity} = CommonAPI.post(user, %{"status" => "nice echo chamber"}) + + assert_receive {:text, raw_json}, 1_000 + assert {:ok, json} = Jason.decode(raw_json) + + assert "update" == json["event"] + assert json["payload"] + assert {:ok, json} = Jason.decode(json["payload"]) + + # Note: we remove the "statuses_count" from this result as it changes in the meantime + + view_json = + Pleroma.Web.MastodonAPI.StatusView.render("status.json", activity: activity, for: nil) + |> Jason.encode!() + |> Jason.decode!() + |> put_in(["account", "statuses_count"], 0) + + assert json == view_json + end + + describe "with a valid user token" do + setup do + {:ok, app} = + Pleroma.Repo.insert( + OAuth.App.register_changeset(%OAuth.App{}, %{ + client_name: "client", + scopes: "scope", + redirect_uris: "url" + }) + ) + + user = insert(:user) + + {:ok, auth} = OAuth.Authorization.create_authorization(app, user) + + {:ok, token} = OAuth.Token.exchange_token(app, auth) + + %{user: user, token: token} + end + + test "accepts valid tokens", state do + assert {:ok, _} = start_socket("?stream=user&access_token=#{state.token.token}") + end + end +end diff --git a/test/list_test.exs b/test/list_test.exs index 19eef8f6b..1909c0cd9 100644 --- a/test/list_test.exs +++ b/test/list_test.exs @@ -1,9 +1,12 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.ListTest do - alias Pleroma.{User, Repo} + alias Pleroma.Repo use Pleroma.DataCase import Pleroma.Factory - import Ecto.Query test "creating a list" do user = insert(:user) @@ -32,7 +35,7 @@ defmodule Pleroma.ListTest do user = insert(:user) other_user = insert(:user) {:ok, list} = Pleroma.List.create("title", user) - {:ok, %{following: following}} = Pleroma.List.follow(list, other_user) + {:ok, %{following: _following}} = Pleroma.List.follow(list, other_user) {:ok, %{following: following}} = Pleroma.List.unfollow(list, other_user) assert [] == following end diff --git a/test/media_proxy_test.exs b/test/media_proxy_test.exs index c69ed7ea4..05d927422 100644 --- a/test/media_proxy_test.exs +++ b/test/media_proxy_test.exs @@ -1,6 +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.MediaProxyTest do use ExUnit.Case import Pleroma.Web.MediaProxy + alias Pleroma.Web.MediaProxy.MediaProxyController describe "when enabled" do setup do @@ -65,6 +70,14 @@ defmodule Pleroma.MediaProxyTest do assert decode_result(encoded) == url end + test "ensures urls are url-encoded" do + assert decode_result(url("https://pleroma.social/Hello world.jpg")) == + "https://pleroma.social/Hello%20world.jpg" + + assert decode_result(url("https://pleroma.social/Hello%20world.jpg")) == + "https://pleroma.social/Hello%20world.jpg" + end + test "validates signature" do secret_key_base = Pleroma.Config.get([Pleroma.Web.Endpoint, :secret_key_base]) @@ -82,6 +95,51 @@ defmodule Pleroma.MediaProxyTest do [_, "proxy", sig, base64 | _] = URI.parse(encoded).path |> String.split("/") assert decode_url(sig, base64) == {:error, :invalid_signature} end + + test "filename_matches matches url encoded paths" do + assert MediaProxyController.filename_matches( + true, + "/Hello%20world.jpg", + "http://pleroma.social/Hello world.jpg" + ) == :ok + + assert MediaProxyController.filename_matches( + true, + "/Hello%20world.jpg", + "http://pleroma.social/Hello%20world.jpg" + ) == :ok + end + + test "filename_matches matches non-url encoded paths" do + assert MediaProxyController.filename_matches( + true, + "/Hello world.jpg", + "http://pleroma.social/Hello%20world.jpg" + ) == :ok + + assert MediaProxyController.filename_matches( + true, + "/Hello world.jpg", + "http://pleroma.social/Hello world.jpg" + ) == :ok + end + + test "uses the configured base_url" do + base_url = Pleroma.Config.get([:media_proxy, :base_url]) + + if base_url do + on_exit(fn -> + Pleroma.Config.put([:media_proxy, :base_url], base_url) + end) + end + + Pleroma.Config.put([:media_proxy, :base_url], "https://cache.pleroma.social") + + url = "https://pleroma.soykaf.com/static/logo.png" + encoded = url(url) + + assert String.starts_with?(encoded, Pleroma.Config.get([:media_proxy, :base_url])) + end end describe "when disabled" do diff --git a/test/notification_test.exs b/test/notification_test.exs index a36ed5bb8..31c0d2c64 100644 --- a/test/notification_test.exs +++ b/test/notification_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.NotificationTest do use Pleroma.DataCase alias Pleroma.Web.TwitterAPI.TwitterAPI @@ -127,12 +131,12 @@ defmodule Pleroma.NotificationTest do user = insert(:user) other_user = insert(:user) - {:ok, activity} = + {:ok, _activity} = TwitterAPI.create_status(user, %{ "status" => "hey @#{other_user.nickname}!" }) - {:ok, activity} = + {:ok, _activity} = TwitterAPI.create_status(user, %{ "status" => "hey again @#{other_user.nickname}!" }) @@ -142,14 +146,14 @@ defmodule Pleroma.NotificationTest do assert n2.id > n1.id - {:ok, activity} = + {:ok, _activity} = TwitterAPI.create_status(user, %{ "status" => "hey yet again @#{other_user.nickname}!" }) Notification.set_read_up_to(other_user, n2.id) - [n3, n2, n1] = notifs = Notification.for_user(other_user) + [n3, n2, n1] = Notification.for_user(other_user) assert n1.seen == true assert n2.seen == true diff --git a/test/object_test.exs b/test/object_test.exs index 909605560..72194975d 100644 --- a/test/object_test.exs +++ b/test/object_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.ObjectTest do use Pleroma.DataCase import Pleroma.Factory @@ -32,6 +36,8 @@ defmodule Pleroma.ObjectTest do found_object = Object.get_by_ap_id(object.data["id"]) refute object == found_object + + assert found_object.data["type"] == "Tombstone" end test "ensures cache is cleared for the object" do @@ -47,6 +53,8 @@ defmodule Pleroma.ObjectTest do cached_object = Object.get_cached_by_ap_id(object.data["id"]) refute object == cached_object + + assert cached_object.data["type"] == "Tombstone" end end end diff --git a/test/plugs/admin_secret_authentication_plug_test.exs b/test/plugs/admin_secret_authentication_plug_test.exs new file mode 100644 index 000000000..e1d4b391f --- /dev/null +++ b/test/plugs/admin_secret_authentication_plug_test.exs @@ -0,0 +1,42 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Plugs.AdminSecretAuthenticationPlugTest do + use Pleroma.Web.ConnCase, async: true + import Pleroma.Factory + + alias Pleroma.Plugs.AdminSecretAuthenticationPlug + + test "does nothing if a user is assigned", %{conn: conn} do + user = insert(:user) + + conn = + conn + |> assign(:user, user) + + ret_conn = + conn + |> AdminSecretAuthenticationPlug.call(%{}) + + assert conn == ret_conn + end + + test "with secret set and given in the 'admin_token' parameter, it assigns an admin user", %{ + conn: conn + } do + Pleroma.Config.put(:admin_token, "password123") + + conn = + %{conn | params: %{"admin_token" => "wrong_password"}} + |> AdminSecretAuthenticationPlug.call(%{}) + + refute conn.assigns[:user] + + conn = + %{conn | params: %{"admin_token" => "password123"}} + |> AdminSecretAuthenticationPlug.call(%{}) + + assert conn.assigns[:user].info.is_admin + end +end diff --git a/test/plugs/authentication_plug_test.exs b/test/plugs/authentication_plug_test.exs index 061fa0cac..6158086ea 100644 --- a/test/plugs/authentication_plug_test.exs +++ b/test/plugs/authentication_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Plugs.AuthenticationPlugTest do use Pleroma.Web.ConnCase, async: true diff --git a/test/plugs/basic_auth_decoder_plug_test.exs b/test/plugs/basic_auth_decoder_plug_test.exs index a4876fef7..4d7728e93 100644 --- a/test/plugs/basic_auth_decoder_plug_test.exs +++ b/test/plugs/basic_auth_decoder_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Plugs.BasicAuthDecoderPlugTest do use Pleroma.Web.ConnCase, async: true diff --git a/test/plugs/ensure_authenticated_plug_test.exs b/test/plugs/ensure_authenticated_plug_test.exs index b32817fef..37ab5213a 100644 --- a/test/plugs/ensure_authenticated_plug_test.exs +++ b/test/plugs/ensure_authenticated_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Plugs.EnsureAuthenticatedPlugTest do use Pleroma.Web.ConnCase, async: true diff --git a/test/plugs/ensure_user_key_plug_test.exs b/test/plugs/ensure_user_key_plug_test.exs index 9beda838e..6a9627f6a 100644 --- a/test/plugs/ensure_user_key_plug_test.exs +++ b/test/plugs/ensure_user_key_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Plugs.EnsureUserKeyPlugTest do use Pleroma.Web.ConnCase, async: true diff --git a/test/plugs/http_security_plug_test.exs b/test/plugs/http_security_plug_test.exs index 169c3b3a8..0cbb7e4b1 100644 --- a/test/plugs/http_security_plug_test.exs +++ b/test/plugs/http_security_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Plugs.HTTPSecurityPlugTest do use Pleroma.Web.ConnCase alias Pleroma.Config diff --git a/test/plugs/http_signature_plug_test.exs b/test/plugs/http_signature_plug_test.exs index a15c5b470..6a00dd4fd 100644 --- a/test/plugs/http_signature_plug_test.exs +++ b/test/plugs/http_signature_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Plugs.HTTPSignaturePlugTest do use Pleroma.Web.ConnCase alias Pleroma.Web.HTTPSignatures diff --git a/test/plugs/instance_static_test.exs b/test/plugs/instance_static_test.exs new file mode 100644 index 000000000..e2dcfa3d8 --- /dev/null +++ b/test/plugs/instance_static_test.exs @@ -0,0 +1,47 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.RuntimeStaticPlugTest do + use Pleroma.Web.ConnCase + + @dir "test/tmp/instance_static" + + setup do + static_dir = Pleroma.Config.get([:instance, :static_dir]) + Pleroma.Config.put([:instance, :static_dir], @dir) + File.mkdir_p!(@dir) + + on_exit(fn -> + Pleroma.Config.put([:instance, :static_dir], static_dir) + File.rm_rf(@dir) + end) + end + + test "overrides index" do + bundled_index = get(build_conn(), "/") + assert html_response(bundled_index, 200) == File.read!("priv/static/index.html") + + File.write!(@dir <> "/index.html", "hello world") + + index = get(build_conn(), "/") + assert html_response(index, 200) == "hello world" + end + + test "overrides any file in static/static" do + bundled_index = get(build_conn(), "/static/terms-of-service.html") + + assert html_response(bundled_index, 200) == + File.read!("priv/static/static/terms-of-service.html") + + File.mkdir!(@dir <> "/static") + File.write!(@dir <> "/static/terms-of-service.html", "plz be kind") + + index = get(build_conn(), "/static/terms-of-service.html") + assert html_response(index, 200) == "plz be kind" + + File.write!(@dir <> "/static/kaniini.html", "<h1>rabbit hugs as a service</h1>") + index = get(build_conn(), "/static/kaniini.html") + assert html_response(index, 200) == "<h1>rabbit hugs as a service</h1>" + end +end diff --git a/test/plugs/legacy_authentication_plug_test.exs b/test/plugs/legacy_authentication_plug_test.exs index 383a22ff8..302662797 100644 --- a/test/plugs/legacy_authentication_plug_test.exs +++ b/test/plugs/legacy_authentication_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Plugs.LegacyAuthenticationPlugTest do use Pleroma.Web.ConnCase, async: true diff --git a/test/plugs/oauth_plug_test.exs b/test/plugs/oauth_plug_test.exs new file mode 100644 index 000000000..17fdba916 --- /dev/null +++ b/test/plugs/oauth_plug_test.exs @@ -0,0 +1,60 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Plugs.OAuthPlugTest do + use Pleroma.Web.ConnCase, async: true + + alias Pleroma.Plugs.OAuthPlug + import Pleroma.Factory + + @session_opts [ + store: :cookie, + key: "_test", + signing_salt: "cooldude" + ] + + setup %{conn: conn} do + user = insert(:user) + {:ok, %{token: token}} = Pleroma.Web.OAuth.Token.create_token(insert(:oauth_app), user) + %{user: user, token: token, conn: conn} + end + + test "with valid token(uppercase), it assigns the user", %{conn: conn} = opts do + conn = + conn + |> put_req_header("authorization", "BEARER #{opts[:token]}") + |> OAuthPlug.call(%{}) + + assert conn.assigns[:user] == opts[:user] + end + + test "with valid token(downcase), it assigns the user", %{conn: conn} = opts do + conn = + conn + |> put_req_header("authorization", "bearer #{opts[:token]}") + |> OAuthPlug.call(%{}) + + assert conn.assigns[:user] == opts[:user] + end + + test "with invalid token, it not assigns the user", %{conn: conn} do + conn = + conn + |> put_req_header("authorization", "bearer TTTTT") + |> OAuthPlug.call(%{}) + + refute conn.assigns[:user] + end + + test "when token is missed but token in session, it assigns the user", %{conn: conn} = opts do + conn = + conn + |> Plug.Session.call(Plug.Session.init(@session_opts)) + |> fetch_session() + |> put_session(:oauth_token, opts[:token]) + |> OAuthPlug.call(%{}) + + assert conn.assigns[:user] == opts[:user] + end +end diff --git a/test/plugs/session_authentication_plug_test.exs b/test/plugs/session_authentication_plug_test.exs index bb51bc0db..0000f4258 100644 --- a/test/plugs/session_authentication_plug_test.exs +++ b/test/plugs/session_authentication_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Plugs.SessionAuthenticationPlugTest do use Pleroma.Web.ConnCase, async: true diff --git a/test/plugs/set_user_session_id_plug_test.exs b/test/plugs/set_user_session_id_plug_test.exs index 5edc0dab8..f8bfde039 100644 --- a/test/plugs/set_user_session_id_plug_test.exs +++ b/test/plugs/set_user_session_id_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Plugs.SetUserSessionIdPlugTest do use Pleroma.Web.ConnCase, async: true @@ -28,6 +32,8 @@ defmodule Pleroma.Plugs.SetUserSessionIdPlugTest do end test "sets the user_id in the session to the user id of the user assign", %{conn: conn} do + Code.ensure_compiled(Pleroma.User) + conn = conn |> assign(:user, %User{id: 1}) diff --git a/test/plugs/user_enabled_plug_test.exs b/test/plugs/user_enabled_plug_test.exs index ee4f72ccf..c0fafcab1 100644 --- a/test/plugs/user_enabled_plug_test.exs +++ b/test/plugs/user_enabled_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Plugs.UserEnabledPlugTest do use Pleroma.Web.ConnCase, async: true @@ -13,7 +17,7 @@ defmodule Pleroma.Plugs.UserEnabledPlugTest do end test "with a user that is deactivated, it removes that user", %{conn: conn} do - user = insert(:user, info: %{"deactivated" => true}) + user = insert(:user, info: %{deactivated: true}) conn = conn diff --git a/test/plugs/user_fetcher_plug_test.exs b/test/plugs/user_fetcher_plug_test.exs index 5195a0c4a..262eb8d93 100644 --- a/test/plugs/user_fetcher_plug_test.exs +++ b/test/plugs/user_fetcher_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Plugs.UserFetcherPlugTest do use Pleroma.Web.ConnCase, async: true diff --git a/test/plugs/user_is_admin_plug_test.exs b/test/plugs/user_is_admin_plug_test.exs index ddf9eb139..9e05fff18 100644 --- a/test/plugs/user_is_admin_plug_test.exs +++ b/test/plugs/user_is_admin_plug_test.exs @@ -1,11 +1,15 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Plugs.UserIsAdminPlugTest do use Pleroma.Web.ConnCase, async: true alias Pleroma.Plugs.UserIsAdminPlug import Pleroma.Factory - test "accepts a user that is admin", %{conn: conn} do - user = insert(:user, info: %{"is_admin" => true}) + test "accepts a user that is admin" do + user = insert(:user, info: %{is_admin: true}) conn = build_conn() @@ -18,7 +22,7 @@ defmodule Pleroma.Plugs.UserIsAdminPlugTest do assert conn == ret_conn end - test "denies a user that isn't admin", %{conn: conn} do + test "denies a user that isn't admin" do user = insert(:user) conn = @@ -29,7 +33,7 @@ defmodule Pleroma.Plugs.UserIsAdminPlugTest do assert conn.status == 403 end - test "denies when a user isn't set", %{conn: conn} do + test "denies when a user isn't set" do conn = build_conn() |> UserIsAdminPlug.call(%{}) diff --git a/test/support/builders/activity_builder.ex b/test/support/builders/activity_builder.ex index eb72d5ba9..6e5a8e059 100644 --- a/test/support/builders/activity_builder.ex +++ b/test/support/builders/activity_builder.ex @@ -1,5 +1,4 @@ defmodule Pleroma.Builders.ActivityBuilder do - alias Pleroma.Builders.UserBuilder alias Pleroma.Web.ActivityPub.ActivityPub def build(data \\ %{}, opts \\ %{}) do diff --git a/test/support/captcha_mock.ex b/test/support/captcha_mock.ex new file mode 100644 index 000000000..3ab02916f --- /dev/null +++ b/test/support/captcha_mock.ex @@ -0,0 +1,17 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Captcha.Mock do + alias Pleroma.Captcha.Service + @behaviour Service + + @impl Service + def new(), do: %{type: :mock} + + @impl Service + def validate(_token, _captcha), do: true + + @impl Service + def cleanup(), do: :ok +end diff --git a/test/support/channel_case.ex b/test/support/channel_case.ex index 68995a01d..466d8986f 100644 --- a/test/support/channel_case.ex +++ b/test/support/channel_case.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ChannelCase do @moduledoc """ This module defines the test case to be used by diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex index 2e6707087..c201d9a9b 100644 --- a/test/support/conn_case.ex +++ b/test/support/conn_case.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ConnCase do @moduledoc """ This module defines the test case to be used by @@ -19,6 +23,7 @@ defmodule Pleroma.Web.ConnCase do quote do # Import conveniences for testing with connections use Phoenix.ConnTest + use Pleroma.Tests.Helpers import Pleroma.Web.Router.Helpers # The default endpoint for testing diff --git a/test/support/data_case.ex b/test/support/data_case.ex index 8eff0fd94..56d5896ad 100644 --- a/test/support/data_case.ex +++ b/test/support/data_case.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.DataCase do @moduledoc """ This module defines the setup for tests requiring @@ -22,6 +26,7 @@ defmodule Pleroma.DataCase do import Ecto.Changeset import Ecto.Query import Pleroma.DataCase + use Pleroma.Tests.Helpers end end @@ -36,6 +41,23 @@ defmodule Pleroma.DataCase do :ok end + def ensure_local_uploader(_context) do + uploader = Pleroma.Config.get([Pleroma.Upload, :uploader]) + filters = Pleroma.Config.get([Pleroma.Upload, :filters]) + + unless uploader == Pleroma.Uploaders.Local || filters != [] do + Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) + Pleroma.Config.put([Pleroma.Upload, :filters], []) + + on_exit(fn -> + Pleroma.Config.put([Pleroma.Upload, :uploader], uploader) + Pleroma.Config.put([Pleroma.Upload, :filters], filters) + end) + end + + :ok + end + @doc """ A helper that transform changeset errors to a map of messages. diff --git a/test/support/factory.ex b/test/support/factory.ex index 4f5060abf..e5c0c5bcc 100644 --- a/test/support/factory.ex +++ b/test/support/factory.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Factory do use ExMachina.Ecto, repo: Pleroma.Repo @@ -7,7 +11,8 @@ defmodule Pleroma.Factory do email: sequence(:email, &"user#{&1}@example.com"), nickname: sequence(:nickname, &"nick#{&1}"), password_hash: Comeonin.Pbkdf2.hashpwsalt("test"), - bio: sequence(:bio, &"Tester Number #{&1}") + bio: sequence(:bio, &"Tester Number #{&1}"), + info: %{} } %{ diff --git a/test/support/helpers.ex b/test/support/helpers.ex new file mode 100644 index 000000000..6e389ce52 --- /dev/null +++ b/test/support/helpers.ex @@ -0,0 +1,29 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Tests.Helpers do + @moduledoc """ + Helpers for use in tests. + """ + + defmacro __using__(_opts) do + quote do + def refresh_record(%{id: id, __struct__: model} = _), + do: refresh_record(model, %{id: id}) + + def refresh_record(model, %{id: id} = _) do + Pleroma.Repo.get_by(model, id: id) + end + + # Used for comparing json rendering during tests. + def render_json(view, template, assigns) do + assigns = Map.new(assigns) + + view.render(template, assigns) + |> Poison.encode!() + |> Poison.decode!() + end + end + end +end diff --git a/test/support/http_request_mock.ex b/test/support/http_request_mock.ex new file mode 100644 index 000000000..e4279e14d --- /dev/null +++ b/test/support/http_request_mock.ex @@ -0,0 +1,679 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule HttpRequestMock do + require Logger + + def request( + %Tesla.Env{ + url: url, + method: method, + headers: headers, + query: query, + body: body + } = _env + ) do + with {:ok, res} <- apply(__MODULE__, method, [url, query, body, headers]) do + res + else + {_, _r} = error -> + # Logger.warn(r) + error + end + end + + # GET Requests + # + def get(url, query \\ [], body \\ [], headers \\ []) + + def get("https://osada.macgirvin.com/channel/mike", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: + File.read!("test/fixtures/httpoison_mock/https___osada.macgirvin.com_channel_mike.json") + }} + end + + def get( + "https://osada.macgirvin.com/.well-known/webfinger?resource=acct:mike@osada.macgirvin.com", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/mike@osada.macgirvin.com.json") + }} + end + + def get( + "https://social.heldscal.la/.well-known/webfinger?resource=https://social.heldscal.la/user/29191", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/https___social.heldscal.la_user_29191.xml") + }} + end + + def get("https://pawoo.net/users/pekorino.atom", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/https___pawoo.net_users_pekorino.atom") + }} + end + + def get( + "https://pawoo.net/.well-known/webfinger?resource=acct:https://pawoo.net/users/pekorino", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/https___pawoo.net_users_pekorino.xml") + }} + end + + def get( + "https://social.stopwatchingus-heidelberg.de/api/statuses/user_timeline/18330.atom", + _, + _, + _ + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/atarifrosch_feed.xml") + }} + end + + def get( + "https://social.stopwatchingus-heidelberg.de/.well-known/webfinger?resource=acct:https://social.stopwatchingus-heidelberg.de/user/18330", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/atarifrosch_webfinger.xml") + }} + end + + def get("https://mamot.fr/users/Skruyb.atom", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/https___mamot.fr_users_Skruyb.atom") + }} + end + + def get( + "https://mamot.fr/.well-known/webfinger?resource=acct:https://mamot.fr/users/Skruyb", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/skruyb@mamot.fr.atom") + }} + end + + def get( + "https://social.heldscal.la/.well-known/webfinger?resource=nonexistant@social.heldscal.la", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/nonexistant@social.heldscal.la.xml") + }} + end + + def get("https://squeet.me/xrd/?uri=lain@squeet.me", _, _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/lain_squeet.me_webfinger.xml") + }} + end + + def get("https://mst3k.interlinked.me/users/luciferMysticus", _, _, + Accept: "application/activity+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/lucifermysticus.json") + }} + end + + def get("https://prismo.news/@mxb", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/https___prismo.news__mxb.json") + }} + end + + def get("https://hubzilla.example.org/channel/kaniini", _, _, + Accept: "application/activity+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/kaniini@hubzilla.example.org.json") + }} + end + + def get("https://niu.moe/users/rye", _, _, Accept: "application/activity+json") do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/rye.json") + }} + end + + def get("http://mastodon.example.org/users/admin/statuses/100787282858396771", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: + File.read!( + "test/fixtures/httpoison_mock/http___mastodon.example.org_users_admin_status_1234.json" + ) + }} + end + + def get("https://puckipedia.com/", _, _, Accept: "application/activity+json") do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/puckipedia.com.json") + }} + end + + def get("https://peertube.moe/accounts/7even", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/7even.json") + }} + end + + def get("https://peertube.moe/videos/watch/df5f464b-be8d-46fb-ad81-2d4c2d1630e3", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/peertube.moe-vid.json") + }} + end + + def get("https://baptiste.gelez.xyz/@/BaptisteGelez", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/baptiste.gelex.xyz-user.json") + }} + end + + def get("https://baptiste.gelez.xyz/~/PlumeDevelopment/this-month-in-plume-june-2018/", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/baptiste.gelex.xyz-article.json") + }} + end + + def get("http://mastodon.example.org/users/admin", _, _, Accept: "application/activity+json") do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/admin@mastdon.example.org.json") + }} + end + + def get("http://mastodon.example.org/@admin/99541947525187367", _, _, + Accept: "application/activity+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/mastodon-note-object.json") + }} + end + + def get("https://shitposter.club/notice/7369654", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/7369654.html") + }} + end + + def get("https://mstdn.io/users/mayuutann", _, _, Accept: "application/activity+json") do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/mayumayu.json") + }} + end + + def get("https://mstdn.io/users/mayuutann/statuses/99568293732299394", _, _, + Accept: "application/activity+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/mayumayupost.json") + }} + end + + def get("https://pleroma.soykaf.com/users/lain/feed.atom", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: + File.read!( + "test/fixtures/httpoison_mock/https___pleroma.soykaf.com_users_lain_feed.atom.xml" + ) + }} + end + + def get(url, _, _, Accept: "application/xrd+xml,application/jrd+json") + when url in [ + "https://pleroma.soykaf.com/.well-known/webfinger?resource=acct:https://pleroma.soykaf.com/users/lain", + "https://pleroma.soykaf.com/.well-known/webfinger?resource=https://pleroma.soykaf.com/users/lain" + ] do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/https___pleroma.soykaf.com_users_lain.xml") + }} + end + + def get("https://shitposter.club/api/statuses/user_timeline/1.atom", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: + File.read!( + "test/fixtures/httpoison_mock/https___shitposter.club_api_statuses_user_timeline_1.atom.xml" + ) + }} + end + + def get( + "https://shitposter.club/.well-known/webfinger?resource=https://shitposter.club/user/1", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/https___shitposter.club_user_1.xml") + }} + end + + def get("https://shitposter.club/notice/2827873", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: + File.read!("test/fixtures/httpoison_mock/https___shitposter.club_notice_2827873.html") + }} + end + + def get("https://shitposter.club/api/statuses/show/2827873.atom", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: + File.read!( + "test/fixtures/httpoison_mock/https___shitposter.club_api_statuses_show_2827873.atom.xml" + ) + }} + end + + def get("https://testing.pleroma.lol/objects/b319022a-4946-44c5-9de9-34801f95507b", _, _, _) do + {:ok, %Tesla.Env{status: 200}} + end + + def get("https://shitposter.club/api/statuses/user_timeline/5381.atom", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/spc_5381.atom") + }} + end + + def get( + "https://shitposter.club/.well-known/webfinger?resource=https://shitposter.club/user/5381", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/spc_5381_xrd.xml") + }} + end + + def get("http://shitposter.club/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/shitposter.club_host_meta") + }} + end + + def get("https://shitposter.club/api/statuses/show/7369654.atom", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/7369654.atom") + }} + end + + def get("https://shitposter.club/notice/4027863", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/7369654.html") + }} + end + + def get("https://social.sakamoto.gq/users/eal/feed.atom", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/sakamoto_eal_feed.atom") + }} + end + + def get("http://social.sakamoto.gq/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/social.sakamoto.gq_host_meta") + }} + end + + def get( + "https://social.sakamoto.gq/.well-known/webfinger?resource=https://social.sakamoto.gq/users/eal", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/eal_sakamoto.xml") + }} + end + + def get("https://social.sakamoto.gq/objects/0ccc1a2c-66b0-4305-b23a-7f7f2b040056", _, _, + Accept: "application/atom+xml" + ) do + {:ok, %Tesla.Env{status: 200, body: File.read!("test/fixtures/httpoison_mock/sakamoto.atom")}} + end + + def get("http://mastodon.social/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/mastodon.social_host_meta") + }} + end + + def get( + "https://mastodon.social/.well-known/webfinger?resource=https://mastodon.social/users/lambadalambda", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: + File.read!( + "test/fixtures/httpoison_mock/https___mastodon.social_users_lambadalambda.xml" + ) + }} + end + + def get("http://gs.example.org/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/gs.example.org_host_meta") + }} + end + + def get( + "http://gs.example.org/.well-known/webfinger?resource=http://gs.example.org:4040/index.php/user/1", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: + File.read!( + "test/fixtures/httpoison_mock/http___gs.example.org_4040_index.php_user_1.xml" + ) + }} + end + + def get("http://gs.example.org/index.php/api/statuses/user_timeline/1.atom", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: + File.read!( + "test/fixtures/httpoison_mock/http__gs.example.org_index.php_api_statuses_user_timeline_1.atom.xml" + ) + }} + end + + def get("https://social.heldscal.la/api/statuses/user_timeline/29191.atom", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: + File.read!( + "test/fixtures/httpoison_mock/https___social.heldscal.la_api_statuses_user_timeline_29191.atom.xml" + ) + }} + end + + def get("http://squeet.me/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{status: 200, body: File.read!("test/fixtures/httpoison_mock/squeet.me_host_meta")}} + end + + def get("https://squeet.me/xrd?uri=lain@squeet.me", _, _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/lain_squeet.me_webfinger.xml") + }} + end + + def get( + "https://social.heldscal.la/.well-known/webfinger?resource=shp@social.heldscal.la", + _, + _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/shp@social.heldscal.la.xml") + }} + end + + def get("http://framatube.org/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/framatube.org_host_meta") + }} + end + + def get("http://framatube.org/main/xrd?uri=framasoft@framatube.org", _, _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + headers: [{"content-type", "application/json"}], + body: File.read!("test/fixtures/httpoison_mock/framasoft@framatube.org.json") + }} + end + + def get("http://gnusocial.de/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/gnusocial.de_host_meta") + }} + end + + def get("http://gnusocial.de/main/xrd?uri=winterdienst@gnusocial.de", _, _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/winterdienst_webfinger.json") + }} + end + + def get("http://status.alpicola.com/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/status.alpicola.com_host_meta") + }} + end + + def get("http://macgirvin.com/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/macgirvin.com_host_meta") + }} + end + + def get("http://gerzilla.de/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/gerzilla.de_host_meta") + }} + end + + def get("https://gerzilla.de/xrd/?uri=kaniini@gerzilla.de", _, _, + Accept: "application/xrd+xml,application/jrd+json" + ) do + {:ok, + %Tesla.Env{ + status: 200, + headers: [{"content-type", "application/json"}], + body: File.read!("test/fixtures/httpoison_mock/kaniini@gerzilla.de.json") + }} + end + + def get("https://social.heldscal.la/api/statuses/user_timeline/23211.atom", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: + File.read!( + "test/fixtures/httpoison_mock/https___social.heldscal.la_api_statuses_user_timeline_23211.atom.xml" + ) + }} + end + + def get( + "https://social.heldscal.la/.well-known/webfinger?resource=https://social.heldscal.la/user/23211", + _, + _, + _ + ) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/https___social.heldscal.la_user_23211.xml") + }} + end + + def get("http://social.heldscal.la/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/social.heldscal.la_host_meta") + }} + end + + def get("https://social.heldscal.la/.well-known/host-meta", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: File.read!("test/fixtures/httpoison_mock/social.heldscal.la_host_meta") + }} + end + + def get("https://mastodon.social/users/lambadalambda.atom", _, _, _) do + {:ok, %Tesla.Env{status: 200, body: File.read!("test/fixtures/lambadalambda.atom")}} + end + + def get("https://social.heldscal.la/user/23211", _, _, Accept: "application/activity+json") do + {:ok, Tesla.Mock.json(%{"id" => "https://social.heldscal.la/user/23211"}, status: 200)} + end + + def get(url, query, body, headers) do + {:error, + "Not implemented the mock response for get #{inspect(url)}, #{query}, #{inspect(body)}, #{ + inspect(headers) + }"} + end + + # POST Requests + # + + def post(url, query \\ [], body \\ [], headers \\ []) + + def post("http://example.org/needs_refresh", _, _, _) do + {:ok, + %Tesla.Env{ + status: 200, + body: "" + }} + end + + def post(url, _query, _body, _headers) do + {:error, "Not implemented the mock response for post #{inspect(url)}"} + end +end diff --git a/test/support/httpoison_mock.ex b/test/support/httpoison_mock.ex deleted file mode 100644 index 0be09b6ce..000000000 --- a/test/support/httpoison_mock.ex +++ /dev/null @@ -1,881 +0,0 @@ -defmodule HTTPoisonMock do - alias HTTPoison.Response - - def get(url, body \\ [], headers \\ []) - - def get("https://prismo.news/@mxb", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___prismo.news__mxb.json") - }} - end - - def get("https://osada.macgirvin.com/channel/mike", _, _) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!("test/fixtures/httpoison_mock/https___osada.macgirvin.com_channel_mike.json") - }} - end - - def get( - "https://osada.macgirvin.com/.well-known/webfinger?resource=acct:mike@osada.macgirvin.com", - _, - _ - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/mike@osada.macgirvin.com.json") - }} - end - - def get("https://info.pleroma.site/activity.json", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https__info.pleroma.site_activity.json") - }} - end - - def get("https://info.pleroma.site/activity2.json", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https__info.pleroma.site_activity2.json") - }} - end - - def get("https://info.pleroma.site/activity3.json", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https__info.pleroma.site_activity3.json") - }} - end - - def get("https://info.pleroma.site/activity4.json", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https__info.pleroma.site_activity4.json") - }} - end - - def get("https://info.pleroma.site/actor.json", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___info.pleroma.site_actor.json") - }} - end - - def get("https://puckipedia.com/", [Accept: "application/activity+json"], _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/puckipedia.com.json") - }} - end - - def get( - "https://gerzilla.de/.well-known/webfinger?resource=acct:kaniini@gerzilla.de", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/kaniini@gerzilla.de.json") - }} - end - - def get( - "https://framatube.org/.well-known/webfinger?resource=acct:framasoft@framatube.org", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/framasoft@framatube.org.json") - }} - end - - def get( - "https://gnusocial.de/.well-known/webfinger?resource=acct:winterdienst@gnusocial.de", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/winterdienst_webfinger.json") - }} - end - - def get( - "https://social.heldscal.la/.well-known/webfinger", - [Accept: "application/xrd+xml,application/jrd+json"], - params: [resource: "nonexistant@social.heldscal.la"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 500, - body: File.read!("test/fixtures/httpoison_mock/nonexistant@social.heldscal.la.xml") - }} - end - - def get( - "https://social.heldscal.la/.well-known/webfinger?resource=shp@social.heldscal.la", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/shp@social.heldscal.la.xml") - }} - end - - def get( - "https://social.heldscal.la/.well-known/webfinger", - [Accept: "application/xrd+xml,application/jrd+json"], - params: [resource: "shp@social.heldscal.la"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/shp@social.heldscal.la.xml") - }} - end - - def get( - "https://social.heldscal.la/.well-known/webfinger", - [Accept: "application/xrd+xml,application/jrd+json"], - params: [resource: "https://social.heldscal.la/user/23211"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___social.heldscal.la_user_23211.xml") - }} - end - - def get( - "https://social.heldscal.la/.well-known/webfinger?resource=https://social.heldscal.la/user/23211", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___social.heldscal.la_user_23211.xml") - }} - end - - def get( - "https://social.heldscal.la/.well-known/webfinger", - [Accept: "application/xrd+xml,application/jrd+json"], - params: [resource: "https://social.heldscal.la/user/29191"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___social.heldscal.la_user_29191.xml") - }} - end - - def get( - "https://social.heldscal.la/.well-known/webfinger?resource=https://social.heldscal.la/user/29191", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___social.heldscal.la_user_29191.xml") - }} - end - - def get( - "https://mastodon.social/.well-known/webfinger", - [Accept: "application/xrd+xml,application/jrd+json"], - params: [resource: "https://mastodon.social/users/lambadalambda"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/https___mastodon.social_users_lambadalambda.xml" - ) - }} - end - - def get( - "https://mastodon.social/.well-known/webfinger?resource=https://mastodon.social/users/lambadalambda", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/https___mastodon.social_users_lambadalambda.xml" - ) - }} - end - - def get( - "https://shitposter.club/.well-known/webfinger", - [Accept: "application/xrd+xml,application/jrd+json"], - params: [resource: "https://shitposter.club/user/1"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___shitposter.club_user_1.xml") - }} - end - - def get( - "https://shitposter.club/.well-known/webfinger?resource=https://shitposter.club/user/1", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___shitposter.club_user_1.xml") - }} - end - - def get( - "https://shitposter.club/.well-known/webfinger?resource=https://shitposter.club/user/5381", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/spc_5381_xrd.xml") - }} - end - - def get( - "http://gs.example.org/.well-known/webfinger", - [Accept: "application/xrd+xml,application/jrd+json"], - params: [resource: "http://gs.example.org:4040/index.php/user/1"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/http___gs.example.org_4040_index.php_user_1.xml" - ) - }} - end - - def get( - "http://gs.example.org/.well-known/webfinger?resource=http://gs.example.org:4040/index.php/user/1", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/http___gs.example.org_4040_index.php_user_1.xml" - ) - }} - end - - def get( - "https://social.stopwatchingus-heidelberg.de/.well-known/webfinger?resource=https://social.stopwatchingus-heidelberg.de/user/18330", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/atarifrosch_webfinger.xml") - }} - end - - def get( - "https://pleroma.soykaf.com/.well-known/webfinger", - [Accept: "application/xrd+xml,application/jrd+json"], - params: [resource: "https://pleroma.soykaf.com/users/lain"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___pleroma.soykaf.com_users_lain.xml") - }} - end - - def get( - "https://pleroma.soykaf.com/.well-known/webfinger?resource=https://pleroma.soykaf.com/users/lain", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___pleroma.soykaf.com_users_lain.xml") - }} - end - - def get("https://social.heldscal.la/api/statuses/user_timeline/29191.atom", _body, _headers) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/https___social.heldscal.la_api_statuses_user_timeline_29191.atom.xml" - ) - }} - end - - def get("https://shitposter.club/api/statuses/user_timeline/5381.atom", _body, _headers) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/spc_5381.atom") - }} - end - - def get("https://social.heldscal.la/api/statuses/user_timeline/23211.atom", _body, _headers) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/https___social.heldscal.la_api_statuses_user_timeline_23211.atom.xml" - ) - }} - end - - def get("https://mastodon.social/users/lambadalambda.atom", _body, _headers) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/https___mastodon.social_users_lambadalambda.atom" - ) - }} - end - - def get( - "https://social.stopwatchingus-heidelberg.de/api/statuses/user_timeline/18330.atom", - _body, - _headers - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/atarifrosch_feed.xml") - }} - end - - def get("https://pleroma.soykaf.com/users/lain/feed.atom", _body, _headers) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/https___pleroma.soykaf.com_users_lain_feed.atom.xml" - ) - }} - end - - def get("https://social.sakamoto.gq/users/eal/feed.atom", _body, _headers) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/sakamoto_eal_feed.atom") - }} - end - - def get("http://gs.example.org/index.php/api/statuses/user_timeline/1.atom", _body, _headers) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/http__gs.example.org_index.php_api_statuses_user_timeline_1.atom.xml" - ) - }} - end - - def get("https://shitposter.club/notice/2827873", _body, _headers) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!("test/fixtures/httpoison_mock/https___shitposter.club_notice_2827873.html") - }} - end - - def get("https://shitposter.club/api/statuses/show/2827873.atom", _body, _headers) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/https___shitposter.club_api_statuses_show_2827873.atom.xml" - ) - }} - end - - def get("https://shitposter.club/api/statuses/user_timeline/1.atom", _body, _headers) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/https___shitposter.club_api_statuses_user_timeline_1.atom.xml" - ) - }} - end - - def post( - "https://social.heldscal.la/main/push/hub", - {:form, _data}, - "Content-type": "application/x-www-form-urlencoded" - ) do - {:ok, - %Response{ - status_code: 202 - }} - end - - def get("http://mastodon.example.org/users/admin/statuses/100787282858396771", _, _) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!( - "test/fixtures/httpoison_mock/http___mastodon.example.org_users_admin_status_1234.json" - ) - }} - end - - def get( - "https://pawoo.net/.well-known/webfinger", - [Accept: "application/xrd+xml,application/jrd+json"], - params: [resource: "https://pawoo.net/users/pekorino"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___pawoo.net_users_pekorino.xml") - }} - end - - def get( - "https://pawoo.net/.well-known/webfinger?resource=https://pawoo.net/users/pekorino", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___pawoo.net_users_pekorino.xml") - }} - end - - def get("https://pawoo.net/users/pekorino.atom", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___pawoo.net_users_pekorino.atom") - }} - end - - def get( - "https://mamot.fr/.well-known/webfinger", - [Accept: "application/xrd+xml,application/jrd+json"], - params: [resource: "https://mamot.fr/users/Skruyb"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/skruyb@mamot.fr.atom") - }} - end - - def get( - "https://mamot.fr/.well-known/webfinger?resource=https://mamot.fr/users/Skruyb", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/skruyb@mamot.fr.atom") - }} - end - - def get( - "https://social.sakamoto.gq/.well-known/webfinger", - [Accept: "application/xrd+xml,application/jrd+json"], - params: [resource: "https://social.sakamoto.gq/users/eal"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/eal_sakamoto.xml") - }} - end - - def get( - "https://social.sakamoto.gq/.well-known/webfinger?resource=https://social.sakamoto.gq/users/eal", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/eal_sakamoto.xml") - }} - end - - def get( - "https://pleroma.soykaf.com/.well-known/webfinger?resource=https://pleroma.soykaf.com/users/shp", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/shp@pleroma.soykaf.com.webfigner") - }} - end - - def get( - "https://squeet.me/xrd/?uri=lain@squeet.me", - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/lain_squeet.me_webfinger.xml") - }} - end - - def get("https://mamot.fr/users/Skruyb.atom", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/https___mamot.fr_users_Skruyb.atom") - }} - end - - def get( - "https://social.sakamoto.gq/objects/0ccc1a2c-66b0-4305-b23a-7f7f2b040056", - [Accept: "application/atom+xml"], - _ - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/sakamoto.atom") - }} - end - - def get("https://pleroma.soykaf.com/users/shp/feed.atom", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/shp@pleroma.soykaf.com.feed") - }} - end - - def get("http://social.heldscal.la/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/social.heldscal.la_host_meta") - }} - end - - def get("http://status.alpicola.com/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/status.alpicola.com_host_meta") - }} - end - - def get("http://macgirvin.com/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/macgirvin.com_host_meta") - }} - end - - def get("http://mastodon.social/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/mastodon.social_host_meta") - }} - end - - def get("http://shitposter.club/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/shitposter.club_host_meta") - }} - end - - def get("http://pleroma.soykaf.com/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/pleroma.soykaf.com_host_meta") - }} - end - - def get("http://social.sakamoto.gq/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/social.sakamoto.gq_host_meta") - }} - end - - def get("http://gs.example.org/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/gs.example.org_host_meta") - }} - end - - def get("http://pawoo.net/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/pawoo.net_host_meta") - }} - end - - def get("http://mamot.fr/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/mamot.fr_host_meta") - }} - end - - def get("http://mastodon.xyz/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/mastodon.xyz_host_meta") - }} - end - - def get("http://social.wxcafe.net/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/social.wxcafe.net_host_meta") - }} - end - - def get("http://squeet.me/.well-known/host-meta", [], follow_redirect: true) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/squeet.me_host_meta") - }} - end - - def get( - "http://social.stopwatchingus-heidelberg.de/.well-known/host-meta", - [], - follow_redirect: true - ) do - {:ok, - %Response{ - status_code: 200, - body: - File.read!("test/fixtures/httpoison_mock/social.stopwatchingus-heidelberg.de_host_meta") - }} - end - - def get("http://mastodon.example.org/users/admin", [Accept: "application/activity+json"], _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/admin@mastdon.example.org.json") - }} - end - - def get( - "https://hubzilla.example.org/channel/kaniini", - [Accept: "application/activity+json"], - _ - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/kaniini@hubzilla.example.org.json") - }} - end - - def get("https://masto.quad.moe/users/_HellPie", [Accept: "application/activity+json"], _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/hellpie.json") - }} - end - - def get("https://niu.moe/users/rye", [Accept: "application/activity+json"], _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/rye.json") - }} - end - - def get("https://n1u.moe/users/rye", [Accept: "application/activity+json"], _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/rye.json") - }} - end - - def get( - "https://mst3k.interlinked.me/users/luciferMysticus", - [Accept: "application/activity+json"], - _ - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/lucifermysticus.json") - }} - end - - def get("https://mstdn.io/users/mayuutann", [Accept: "application/activity+json"], _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/mayumayu.json") - }} - end - - def get( - "http://mastodon.example.org/@admin/99541947525187367", - [Accept: "application/activity+json"], - _ - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/mastodon-note-object.json") - }} - end - - def get( - "https://mstdn.io/users/mayuutann/statuses/99568293732299394", - [Accept: "application/activity+json"], - _ - ) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/mayumayupost.json") - }} - end - - def get("https://shitposter.club/notice/7369654", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/7369654.html") - }} - end - - def get("https://shitposter.club/api/statuses/show/7369654.atom", _body, _headers) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/7369654.atom") - }} - end - - def get("https://baptiste.gelez.xyz/~/PlumeDevelopment/this-month-in-plume-june-2018/", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/baptiste.gelex.xyz-article.json") - }} - end - - def get("https://baptiste.gelez.xyz/@/BaptisteGelez", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/baptiste.gelex.xyz-user.json") - }} - end - - def get("https://peertube.moe/videos/watch/df5f464b-be8d-46fb-ad81-2d4c2d1630e3", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/peertube.moe-vid.json") - }} - end - - def get("https://peertube.moe/accounts/7even", _, _) do - {:ok, - %Response{ - status_code: 200, - body: File.read!("test/fixtures/httpoison_mock/7even.json") - }} - end - - def get(url, body, headers) do - {:error, - "Not implemented the mock response for get #{inspect(url)}, #{inspect(body)}, #{ - inspect(headers) - }"} - end - - def post(url, _body, _headers) do - {:error, "Not implemented the mock response for post #{inspect(url)}"} - end - - def post(url, _body, _headers, _options) do - {:error, "Not implemented the mock response for post #{inspect(url)}"} - end -end diff --git a/test/support/ostatus_mock.ex b/test/support/ostatus_mock.ex index 36865ae02..9c0f2f323 100644 --- a/test/support/ostatus_mock.ex +++ b/test/support/ostatus_mock.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatusMock do import Pleroma.Factory diff --git a/test/support/websocket_client.ex b/test/support/websocket_client.ex new file mode 100644 index 000000000..121231452 --- /dev/null +++ b/test/support/websocket_client.ex @@ -0,0 +1,62 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Integration.WebsocketClient do + # https://github.com/phoenixframework/phoenix/blob/master/test/support/websocket_client.exs + + @doc """ + Starts the WebSocket server for given ws URL. Received Socket.Message's + are forwarded to the sender pid + """ + def start_link(sender, url, headers \\ []) do + :crypto.start() + :ssl.start() + + :websocket_client.start_link( + String.to_charlist(url), + __MODULE__, + [sender], + extra_headers: headers + ) + end + + @doc """ + Closes the socket + """ + def close(socket) do + send(socket, :close) + end + + @doc """ + Sends a low-level text message to the client. + """ + def send_text(server_pid, msg) do + send(server_pid, {:text, msg}) + end + + @doc false + def init([sender], _conn_state) do + {:ok, %{sender: sender}} + end + + @doc false + def websocket_handle(frame, _conn_state, state) do + send(state.sender, frame) + {:ok, state} + end + + @doc false + def websocket_info({:text, msg}, _conn_state, state) do + {:reply, {:text, msg}, state} + end + + def websocket_info(:close, _conn_state, _state) do + {:close, <<>>, "done"} + end + + @doc false + def websocket_terminate(_reason, _conn_state, _state) do + :ok + end +end diff --git a/test/support/websub_mock.ex b/test/support/websub_mock.ex new file mode 100644 index 000000000..e3d5a5b16 --- /dev/null +++ b/test/support/websub_mock.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 Pleroma.Web.WebsubMock do + def verify(sub) do + {:ok, sub} + end +end diff --git a/test/tasks/relay_test.exs b/test/tasks/relay_test.exs new file mode 100644 index 000000000..96fac4811 --- /dev/null +++ b/test/tasks/relay_test.exs @@ -0,0 +1,69 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Mix.Tasks.Pleroma.RelayTest do + alias Pleroma.Activity + alias Pleroma.Web.ActivityPub.{ActivityPub, Relay, Utils} + alias Pleroma.User + use Pleroma.DataCase + + setup_all do + Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) + + Mix.shell(Mix.Shell.Process) + + on_exit(fn -> + Mix.shell(Mix.Shell.IO) + end) + + :ok + end + + describe "running follow" do + test "relay is followed" do + target_instance = "http://mastodon.example.org/users/admin" + + Mix.Tasks.Pleroma.Relay.run(["follow", target_instance]) + + local_user = Relay.get_actor() + assert local_user.ap_id =~ "/relay" + + target_user = User.get_by_ap_id(target_instance) + refute target_user.local + + activity = Utils.fetch_latest_follow(local_user, target_user) + assert activity.data["type"] == "Follow" + assert activity.data["actor"] == local_user.ap_id + assert activity.data["object"] == target_user.ap_id + end + end + + describe "running unfollow" do + test "relay is unfollowed" do + target_instance = "http://mastodon.example.org/users/admin" + + Mix.Tasks.Pleroma.Relay.run(["follow", target_instance]) + + %User{ap_id: follower_id} = local_user = Relay.get_actor() + target_user = User.get_by_ap_id(target_instance) + follow_activity = Utils.fetch_latest_follow(local_user, target_user) + + Mix.Tasks.Pleroma.Relay.run(["unfollow", target_instance]) + + cancelled_activity = Activity.get_by_ap_id(follow_activity.data["id"]) + assert cancelled_activity.data["state"] == "cancelled" + + [undo_activity] = + ActivityPub.fetch_activities([], %{ + "type" => "Undo", + "actor_id" => follower_id, + "limit" => 1 + }) + + assert undo_activity.data["type"] == "Undo" + assert undo_activity.data["actor"] == local_user.ap_id + assert undo_activity.data["object"] == cancelled_activity.data + end + end +end diff --git a/test/tasks/uploads_test.exs b/test/tasks/uploads_test.exs new file mode 100644 index 000000000..b0b8eda11 --- /dev/null +++ b/test/tasks/uploads_test.exs @@ -0,0 +1,56 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Mix.Tasks.Pleroma.UploadsTest do + alias Pleroma.Upload + use Pleroma.DataCase + + import Mock + + setup_all do + Mix.shell(Mix.Shell.Process) + + on_exit(fn -> + Mix.shell(Mix.Shell.IO) + end) + + :ok + end + + describe "running migrate_local" do + test "uploads migrated" do + with_mock Upload, + store: fn %Upload{name: _file, path: _path}, _opts -> {:ok, %{}} end do + Mix.Tasks.Pleroma.Uploads.run(["migrate_local", "S3"]) + + assert_received {:mix_shell, :info, [message]} + assert message =~ "Migrating files from local" + + assert_received {:mix_shell, :info, [message]} + + assert %{"total_count" => total_count} = + Regex.named_captures(~r"^Found (?<total_count>\d+) uploads$", message) + + assert_received {:mix_shell, :info, [message]} + + # @logevery in Mix.Tasks.Pleroma.Uploads + count = + min(50, String.to_integer(total_count)) + |> to_string() + + assert %{"count" => ^count, "total_count" => ^total_count} = + Regex.named_captures( + ~r"^Uploaded (?<count>\d+)/(?<total_count>\d+) files$", + message + ) + end + end + + test "nonexistent uploader" do + assert_raise RuntimeError, ~r/The uploader .* is not an existing/, fn -> + Mix.Tasks.Pleroma.Uploads.run(["migrate_local", "nonexistent"]) + end + end + end +end diff --git a/test/tasks/user_test.exs b/test/tasks/user_test.exs new file mode 100644 index 000000000..44271898c --- /dev/null +++ b/test/tasks/user_test.exs @@ -0,0 +1,251 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Mix.Tasks.Pleroma.UserTest do + alias Pleroma.User + use Pleroma.DataCase + + import Pleroma.Factory + import ExUnit.CaptureIO + + setup_all do + Mix.shell(Mix.Shell.Process) + + on_exit(fn -> + Mix.shell(Mix.Shell.IO) + end) + + :ok + end + + describe "running new" do + test "user is created" do + # just get random data + unsaved = build(:user) + + # prepare to answer yes + send(self(), {:mix_shell_input, :yes?, true}) + + Mix.Tasks.Pleroma.User.run([ + "new", + unsaved.nickname, + unsaved.email, + "--name", + unsaved.name, + "--bio", + unsaved.bio, + "--password", + "test", + "--moderator", + "--admin" + ]) + + assert_received {:mix_shell, :info, [message]} + assert message =~ "user will be created" + + assert_received {:mix_shell, :yes?, [message]} + assert message =~ "Continue" + + assert_received {:mix_shell, :info, [message]} + assert message =~ "created" + + user = User.get_by_nickname(unsaved.nickname) + assert user.name == unsaved.name + assert user.email == unsaved.email + assert user.bio == unsaved.bio + assert user.info.is_moderator + assert user.info.is_admin + end + + test "user is not created" do + unsaved = build(:user) + + # prepare to answer no + send(self(), {:mix_shell_input, :yes?, false}) + + Mix.Tasks.Pleroma.User.run(["new", unsaved.nickname, unsaved.email]) + + assert_received {:mix_shell, :info, [message]} + assert message =~ "user will be created" + + assert_received {:mix_shell, :yes?, [message]} + assert message =~ "Continue" + + assert_received {:mix_shell, :info, [message]} + assert message =~ "will not be created" + + refute User.get_by_nickname(unsaved.nickname) + end + end + + describe "running rm" do + test "user is deleted" do + user = insert(:user) + + Mix.Tasks.Pleroma.User.run(["rm", user.nickname]) + + assert_received {:mix_shell, :info, [message]} + assert message =~ " deleted" + + user = User.get_by_nickname(user.nickname) + assert user.info.deactivated + end + + test "no user to delete" do + Mix.Tasks.Pleroma.User.run(["rm", "nonexistent"]) + + assert_received {:mix_shell, :error, [message]} + assert message =~ "No local user" + end + end + + describe "running toggle_activated" do + test "user is deactivated" do + user = insert(:user) + + Mix.Tasks.Pleroma.User.run(["toggle_activated", user.nickname]) + + assert_received {:mix_shell, :info, [message]} + assert message =~ " deactivated" + + user = User.get_by_nickname(user.nickname) + assert user.info.deactivated + end + + test "user is activated" do + user = insert(:user, info: %{deactivated: true}) + + Mix.Tasks.Pleroma.User.run(["toggle_activated", user.nickname]) + + assert_received {:mix_shell, :info, [message]} + assert message =~ " activated" + + user = User.get_by_nickname(user.nickname) + refute user.info.deactivated + end + + test "no user to toggle" do + Mix.Tasks.Pleroma.User.run(["toggle_activated", "nonexistent"]) + + assert_received {:mix_shell, :error, [message]} + assert message =~ "No user" + end + end + + describe "running unsubscribe" do + test "user is unsubscribed" do + followed = insert(:user) + user = insert(:user, %{following: [User.ap_followers(followed)]}) + + Mix.Tasks.Pleroma.User.run(["unsubscribe", user.nickname]) + + assert_received {:mix_shell, :info, [message]} + assert message =~ "Deactivating" + + assert_received {:mix_shell, :info, [message]} + assert message =~ "Unsubscribing" + + # Note that the task has delay :timer.sleep(500) + assert_received {:mix_shell, :info, [message]} + assert message =~ "Successfully unsubscribed" + + user = User.get_by_nickname(user.nickname) + assert length(user.following) == 0 + assert user.info.deactivated + end + + test "no user to unsubscribe" do + Mix.Tasks.Pleroma.User.run(["unsubscribe", "nonexistent"]) + + assert_received {:mix_shell, :error, [message]} + assert message =~ "No user" + end + end + + describe "running set" do + test "All statuses set" do + user = insert(:user) + + Mix.Tasks.Pleroma.User.run(["set", user.nickname, "--moderator", "--admin", "--locked"]) + + assert_received {:mix_shell, :info, [message]} + assert message =~ ~r/Moderator status .* true/ + + assert_received {:mix_shell, :info, [message]} + assert message =~ ~r/Locked status .* true/ + + assert_received {:mix_shell, :info, [message]} + assert message =~ ~r/Admin status .* true/ + + user = User.get_by_nickname(user.nickname) + assert user.info.is_moderator + assert user.info.locked + assert user.info.is_admin + end + + test "All statuses unset" do + user = insert(:user, info: %{is_moderator: true, locked: true, is_admin: true}) + + Mix.Tasks.Pleroma.User.run([ + "set", + user.nickname, + "--no-moderator", + "--no-admin", + "--no-locked" + ]) + + assert_received {:mix_shell, :info, [message]} + assert message =~ ~r/Moderator status .* false/ + + assert_received {:mix_shell, :info, [message]} + assert message =~ ~r/Locked status .* false/ + + assert_received {:mix_shell, :info, [message]} + assert message =~ ~r/Admin status .* false/ + + user = User.get_by_nickname(user.nickname) + refute user.info.is_moderator + refute user.info.locked + refute user.info.is_admin + end + + test "no user to set status" do + Mix.Tasks.Pleroma.User.run(["set", "nonexistent", "--moderator"]) + + assert_received {:mix_shell, :error, [message]} + assert message =~ "No local user" + end + end + + describe "running reset_password" do + test "password reset token is generated" do + user = insert(:user) + + assert capture_io(fn -> + Mix.Tasks.Pleroma.User.run(["reset_password", user.nickname]) + end) =~ "URL:" + + assert_received {:mix_shell, :info, [message]} + assert message =~ "Generated" + end + + test "no user to reset password" do + Mix.Tasks.Pleroma.User.run(["reset_password", "nonexistent"]) + + assert_received {:mix_shell, :error, [message]} + assert message =~ "No local user" + end + end + + describe "running invite" do + test "invite token is generated" do + assert capture_io(fn -> + Mix.Tasks.Pleroma.User.run(["invite"]) + end) =~ "http" + + assert_received {:mix_shell, :info, [message]} + assert message =~ "Generated" + end + end +end diff --git a/test/test_helper.exs b/test/test_helper.exs index 94ba68ff8..f604ba63d 100644 --- a/test/test_helper.exs +++ b/test/test_helper.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + ExUnit.start() Ecto.Adapters.SQL.Sandbox.mode(Pleroma.Repo, :manual) diff --git a/test/upload_test.exs b/test/upload_test.exs index d273ea5f6..d4ea3a573 100644 --- a/test/upload_test.exs +++ b/test/upload_test.exs @@ -1,8 +1,48 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.UploadTest do alias Pleroma.Upload use Pleroma.DataCase - describe "Storing a file" do + describe "Storing a file with the Local uploader" do + setup [:ensure_local_uploader] + + test "returns a media url" do + File.cp!("test/fixtures/image.jpg", "test/fixtures/image_tmp.jpg") + + file = %Plug.Upload{ + content_type: "image/jpg", + path: Path.absname("test/fixtures/image_tmp.jpg"), + filename: "image.jpg" + } + + {:ok, data} = Upload.store(file) + + assert %{"url" => [%{"href" => url}]} = data + + assert String.starts_with?(url, Pleroma.Web.base_url() <> "/media/") + end + + test "returns a media url with configured base_url" do + base_url = "https://cache.pleroma.social" + + File.cp!("test/fixtures/image.jpg", "test/fixtures/image_tmp.jpg") + + file = %Plug.Upload{ + content_type: "image/jpg", + path: Path.absname("test/fixtures/image_tmp.jpg"), + filename: "image.jpg" + } + + {:ok, data} = Upload.store(file, base_url: base_url) + + assert %{"url" => [%{"href" => url}]} = data + + assert String.starts_with?(url, base_url <> "/media/") + end + test "copies the file to the configured folder with deduping" do File.cp!("test/fixtures/image.jpg", "test/fixtures/image_tmp.jpg") @@ -12,10 +52,11 @@ defmodule Pleroma.UploadTest do filename: "an [image.jpg" } - data = Upload.store(file, true) + {:ok, data} = Upload.store(file, filters: [Pleroma.Upload.Filter.Dedupe]) - assert data["name"] == - "e7a6d0cf595bff76f14c9a98b6c199539559e8b844e02e51e5efcfd1f614a2df.jpeg" + assert List.first(data["url"])["href"] == + Pleroma.Web.base_url() <> + "/media/e7a6d0cf595bff76f14c9a98b6c199539559e8b844e02e51e5efcfd1f614a2df.jpg" end test "copies the file to the configured folder without deduping" do @@ -27,7 +68,7 @@ defmodule Pleroma.UploadTest do filename: "an [image.jpg" } - data = Upload.store(file, false) + {:ok, data} = Upload.store(file) assert data["name"] == "an [image.jpg" end @@ -40,7 +81,7 @@ defmodule Pleroma.UploadTest do filename: "an [image.jpg" } - data = Upload.store(file, true) + {:ok, data} = Upload.store(file, filters: [Pleroma.Upload.Filter.Dedupe]) assert hd(data["url"])["mediaType"] == "image/jpeg" end @@ -53,7 +94,7 @@ defmodule Pleroma.UploadTest do filename: "an [image" } - data = Upload.store(file, false) + {:ok, data} = Upload.store(file) assert data["name"] == "an [image.jpg" end @@ -66,7 +107,7 @@ defmodule Pleroma.UploadTest do filename: "an [image.blah" } - data = Upload.store(file, false) + {:ok, data} = Upload.store(file) assert data["name"] == "an [image.jpg" end @@ -79,8 +120,22 @@ defmodule Pleroma.UploadTest do filename: "test.txt" } - data = Upload.store(file, false) + {:ok, data} = Upload.store(file) assert data["name"] == "test.txt" end + + test "copies the file to the configured folder with anonymizing filename" do + File.cp!("test/fixtures/image.jpg", "test/fixtures/image_tmp.jpg") + + file = %Plug.Upload{ + content_type: "image/jpg", + path: Path.absname("test/fixtures/image_tmp.jpg"), + filename: "an [image.jpg" + } + + {:ok, data} = Upload.store(file, filters: [Pleroma.Upload.Filter.AnonymizeFilename]) + + refute data["name"] == "an [image.jpg" + end end end diff --git a/test/user_test.exs b/test/user_test.exs index 231f1d94d..8c7e1594b 100644 --- a/test/user_test.exs +++ b/test/user_test.exs @@ -1,13 +1,36 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.UserTest do alias Pleroma.Builders.UserBuilder alias Pleroma.{User, Repo, Activity} - alias Pleroma.Web.OStatus - alias Pleroma.Web.Websub.WebsubClientSubscription alias Pleroma.Web.CommonAPI use Pleroma.DataCase import Pleroma.Factory - import Ecto.Query + + setup_all do + Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + + describe "when tags are nil" do + test "tagging a user" do + user = insert(:user, %{tags: nil}) + user = User.tag(user, ["cool", "dude"]) + + assert "cool" in user.tags + assert "dude" in user.tags + end + + test "untagging a user" do + user = insert(:user, %{tags: nil}) + user = User.untag(user, ["cool", "dude"]) + + assert user.tags == [] + end + end test "ap_id returns the activity pub id for the user" do user = UserBuilder.build() @@ -34,14 +57,14 @@ defmodule Pleroma.UserTest do user = Repo.get(User, user.id) followed = User.get_by_ap_id(followed.ap_id) - assert followed.info["follower_count"] == 1 + assert followed.info.follower_count == 1 assert User.ap_followers(followed) in user.following end test "can't follow a deactivated users" do user = insert(:user) - followed = insert(:user, info: %{"deactivated" => true}) + followed = insert(:user, info: %{deactivated: true}) {:error, _} = User.follow(user, followed) end @@ -56,8 +79,8 @@ defmodule Pleroma.UserTest do end test "local users do not automatically follow local locked accounts" do - follower = insert(:user, info: %{"locked" => true}) - followed = insert(:user, info: %{"locked" => true}) + follower = insert(:user, info: %{locked: true}) + followed = insert(:user, info: %{locked: true}) {:ok, follower} = User.maybe_direct_follow(follower, followed) @@ -130,6 +153,20 @@ defmodule Pleroma.UserTest do end) end + test "it restricts certain nicknames" do + [restricted_name | _] = Pleroma.Config.get([Pleroma.User, :restricted_nicknames]) + + assert is_bitstring(restricted_name) + + params = + @full_user_data + |> Map.put(:nickname, restricted_name) + + changeset = User.register_changeset(%User{}, params) + + refute changeset.valid? + end + test "it sets the password_hash, ap_id and following fields" do changeset = User.register_changeset(%User{}, @full_user_data) @@ -144,6 +181,86 @@ defmodule Pleroma.UserTest do assert changeset.changes.follower_address == "#{changeset.changes.ap_id}/followers" end + + test "it ensures info is not nil" do + changeset = User.register_changeset(%User{}, @full_user_data) + + assert changeset.valid? + + {:ok, user} = + changeset + |> Repo.insert() + + refute is_nil(user.info) + end + end + + describe "user registration, with :account_activation_required" do + @full_user_data %{ + bio: "A guy", + name: "my name", + nickname: "nick", + password: "test", + password_confirmation: "test", + email: "email@example.com" + } + + setup do + setting = Pleroma.Config.get([:instance, :account_activation_required]) + + unless setting do + Pleroma.Config.put([:instance, :account_activation_required], true) + on_exit(fn -> Pleroma.Config.put([:instance, :account_activation_required], setting) end) + end + + :ok + end + + test "it creates unconfirmed user" do + changeset = User.register_changeset(%User{}, @full_user_data) + assert changeset.valid? + + {:ok, user} = Repo.insert(changeset) + + assert user.info.confirmation_pending + assert user.info.confirmation_token + end + + test "it creates confirmed user if :confirmed option is given" do + changeset = User.register_changeset(%User{}, @full_user_data, confirmed: true) + assert changeset.valid? + + {:ok, user} = Repo.insert(changeset) + + refute user.info.confirmation_pending + refute user.info.confirmation_token + end + end + + describe "get_or_fetch/1" do + test "gets an existing user by nickname" do + user = insert(:user) + fetched_user = User.get_or_fetch(user.nickname) + + assert user == fetched_user + end + + test "gets an existing user by ap_id" do + ap_id = "http://mastodon.example.org/users/admin" + + user = + insert( + :user, + local: false, + nickname: "admin@mastodon.example.org", + ap_id: ap_id, + info: %{} + ) + + fetched_user = User.get_or_fetch(ap_id) + freshed_user = refresh_record(user) + assert freshed_user == fetched_user + end end describe "fetching a user from nickname or trying to build one" do @@ -185,12 +302,14 @@ defmodule Pleroma.UserTest do local: false, nickname: "admin@mastodon.example.org", ap_id: "http://mastodon.example.org/users/admin", - last_refreshed_at: a_week_ago + last_refreshed_at: a_week_ago, + info: %{} ) assert orig_user.last_refreshed_at == a_week_ago user = User.get_or_fetch_by_ap_id("http://mastodon.example.org/users/admin") + assert user.info.source_data["endpoints"] refute user.last_refreshed_at == orig_user.last_refreshed_at end @@ -311,45 +430,45 @@ defmodule Pleroma.UserTest do user = User.get_by_ap_id(note.data["actor"]) - assert user.info["note_count"] == nil + assert user.info.note_count == 0 {:ok, user} = User.update_note_count(user) - assert user.info["note_count"] == 1 + assert user.info.note_count == 1 end test "it increases the info->note_count property" do note = insert(:note) user = User.get_by_ap_id(note.data["actor"]) - assert user.info["note_count"] == nil + assert user.info.note_count == 0 {:ok, user} = User.increase_note_count(user) - assert user.info["note_count"] == 1 + assert user.info.note_count == 1 {:ok, user} = User.increase_note_count(user) - assert user.info["note_count"] == 2 + assert user.info.note_count == 2 end test "it decreases the info->note_count property" do note = insert(:note) user = User.get_by_ap_id(note.data["actor"]) - assert user.info["note_count"] == nil + assert user.info.note_count == 0 {:ok, user} = User.increase_note_count(user) - assert user.info["note_count"] == 1 + assert user.info.note_count == 1 {:ok, user} = User.decrease_note_count(user) - assert user.info["note_count"] == 0 + assert user.info.note_count == 0 {:ok, user} = User.decrease_note_count(user) - assert user.info["note_count"] == 0 + assert user.info.note_count == 0 end test "it sets the info->follower_count property" do @@ -358,11 +477,11 @@ defmodule Pleroma.UserTest do User.follow(follower, user) - assert user.info["follower_count"] == nil + assert user.info.follower_count == 0 {:ok, user} = User.update_follower_count(user) - assert user.info["follower_count"] == 1 + assert user.info.follower_count == 1 end end @@ -489,11 +608,11 @@ defmodule Pleroma.UserTest do test ".deactivate can de-activate then re-activate a user" do user = insert(:user) - assert false == !!user.info["deactivated"] + assert false == user.info.deactivated {:ok, user} = User.deactivate(user) - assert true == user.info["deactivated"] + assert true == user.info.deactivated {:ok, user} = User.deactivate(user, false) - assert false == !!user.info["deactivated"] + assert false == user.info.deactivated end test ".delete deactivates a user, all follow relationships and all create activities" do @@ -517,7 +636,7 @@ defmodule Pleroma.UserTest do follower = Repo.get(User, follower.id) user = Repo.get(User, user.id) - assert user.info["deactivated"] + assert user.info.deactivated refute User.following?(user, followed) refute User.following?(followed, follower) @@ -546,7 +665,7 @@ defmodule Pleroma.UserTest do end test "html_filter_policy returns TwitterText scrubber when rich-text is disabled" do - user = insert(:user, %{info: %{"no_rich_text" => true}}) + user = insert(:user, %{info: %{no_rich_text: true}}) assert Pleroma.HTML.Scrubber.TwitterText == User.html_filter_policy(user) end @@ -555,7 +674,7 @@ defmodule Pleroma.UserTest do describe "caching" do test "invalidate_cache works" do user = insert(:user) - user_info = User.get_cached_user_info(user) + _user_info = User.get_cached_user_info(user) User.invalidate_cache(user) @@ -581,9 +700,9 @@ defmodule Pleroma.UserTest do describe "User.search" do test "finds a user, ranking by similarity" do - user = insert(:user, %{name: "lain"}) - user_two = insert(:user, %{name: "ean"}) - user_three = insert(:user, %{name: "ebn", nickname: "lain@mastodon.social"}) + _user = insert(:user, %{name: "lain"}) + _user_two = insert(:user, %{name: "ean"}) + _user_three = insert(:user, %{name: "ebn", nickname: "lain@mastodon.social"}) user_four = insert(:user, %{nickname: "lain@pleroma.soykaf.com"}) assert user_four == diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs index 1c24b348c..9fdf15505 100644 --- a/test/web/activity_pub/activity_pub_controller_test.exs +++ b/test/web/activity_pub/activity_pub_controller_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do use Pleroma.Web.ConnCase import Pleroma.Factory @@ -5,6 +9,11 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do alias Pleroma.{Repo, User} alias Pleroma.Activity + setup_all do + Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + describe "/relay" do test "with the relay active, it returns the relay user", %{conn: conn} do res = @@ -18,10 +27,10 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do test "with the relay disabled, it returns 404", %{conn: conn} do Pleroma.Config.put([:instance, :allow_relay], false) - res = - conn - |> get(activity_pub_path(conn, :relay)) - |> json_response(404) + conn + |> get(activity_pub_path(conn, :relay)) + |> json_response(404) + |> assert Pleroma.Config.put([:instance, :allow_relay], true) end @@ -145,6 +154,20 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do assert result["first"]["orderedItems"] == [user.ap_id] end + test "it returns returns empty if the user has 'hide_network' set", %{conn: conn} do + user = insert(:user) + user_two = insert(:user, %{info: %{hide_network: true}}) + User.follow(user, user_two) + + result = + conn + |> get("/users/#{user_two.nickname}/followers") + |> json_response(200) + + assert result["first"]["orderedItems"] == [] + assert result["totalItems"] == 1 + end + test "it works for more than 10 users", %{conn: conn} do user = insert(:user) @@ -186,6 +209,20 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do assert result["first"]["orderedItems"] == [user_two.ap_id] end + test "it returns returns empty if the user has 'hide_network' set", %{conn: conn} do + user = insert(:user, %{info: %{hide_network: true}}) + user_two = insert(:user) + User.follow(user, user_two) + + result = + conn + |> get("/users/#{user.nickname}/following") + |> json_response(200) + + assert result["first"]["orderedItems"] == [] + assert result["totalItems"] == 1 + end + test "it works for more than 10 users", %{conn: conn} do user = insert(:user) diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs index 35c381ac3..7bccd7500 100644 --- a/test/web/activity_pub/activity_pub_test.exs +++ b/test/web/activity_pub/activity_pub_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.ActivityPubTest do use Pleroma.DataCase alias Pleroma.Web.ActivityPub.ActivityPub @@ -7,6 +11,12 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do alias Pleroma.Builders.ActivityBuilder import Pleroma.Factory + import Tesla.Mock + + setup do + mock(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end describe "building a user from his ap id" do test "it returns a user" do @@ -14,8 +24,8 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do {:ok, user} = ActivityPub.make_user_from_ap_id(user_id) assert user.ap_id == user_id assert user.nickname == "admin@mastodon.example.org" - assert user.info["source_data"] - assert user.info["ap_enabled"] + assert user.info.source_data + assert user.info.ap_enabled assert user.follower_address == "http://mastodon.example.org/users/admin/followers" end end @@ -170,11 +180,21 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do assert Enum.member?(activities, activity_one) end + test "excludes reblogs on request" do + user = insert(:user) + {:ok, expected_activity} = ActivityBuilder.insert(%{"type" => "Create"}, %{:user => user}) + {:ok, _} = ActivityBuilder.insert(%{"type" => "Announce"}, %{:user => user}) + + [activity] = ActivityPub.fetch_user_activities(user, nil, %{"exclude_reblogs" => "true"}) + + assert activity == expected_activity + end + describe "public fetch activities" do test "doesn't retrieve unlisted activities" do user = insert(:user) - {:ok, unlisted_activity} = + {:ok, _unlisted_activity} = CommonAPI.post(user, %{"status" => "yeah", "visibility" => "unlisted"}) {:ok, listed_activity} = CommonAPI.post(user, %{"status" => "yeah"}) @@ -472,7 +492,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do assert Repo.get(Activity, delete.id) != nil - assert Repo.get(Object, object.id) == nil + assert Repo.get(Object, object.id).data["type"] == "Tombstone" end end diff --git a/test/web/activity_pub/relay_test.exs b/test/web/activity_pub/relay_test.exs index 41d13e055..21a63c493 100644 --- a/test/web/activity_pub/relay_test.exs +++ b/test/web/activity_pub/relay_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.RelayTest do use Pleroma.DataCase diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs index 829da0a65..a5fd87ed4 100644 --- a/test/web/activity_pub/transmogrifier_test.exs +++ b/test/web/activity_pub/transmogrifier_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do use Pleroma.DataCase alias Pleroma.Web.ActivityPub.Transmogrifier @@ -12,6 +16,11 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do import Pleroma.Factory alias Pleroma.Web.CommonAPI + setup_all do + Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + describe "handle_incoming" do test "it ignores an incoming notice if we already have it" do activity = insert(:note_activity) @@ -92,7 +101,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do user = User.get_by_ap_id(object["actor"]) - assert user.info["note_count"] == 1 + assert user.info.note_count == 1 end test "it works for incoming notices with hashtags" do @@ -307,7 +316,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do } ] - assert user.info["banner"]["url"] == [ + assert user.info.banner["url"] == [ %{ "href" => "https://cd.niu.moe/accounts/headers/000/033/323/original/850b3448fa5fd477.png" @@ -337,7 +346,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(update_data) user = User.get_cached_by_ap_id(data["actor"]) - assert user.info["locked"] == true + assert user.info.locked == true end test "it works for incoming deletes" do @@ -543,7 +552,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do test "it works for incoming accepts which were orphaned" do follower = insert(:user) - followed = insert(:user, %{info: %{"locked" => true}}) + followed = insert(:user, %{info: %User.Info{locked: true}}) {:ok, follow_activity} = ActivityPub.follow(follower, followed) @@ -565,7 +574,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do test "it works for incoming accepts which are referenced by IRI only" do follower = insert(:user) - followed = insert(:user, %{info: %{"locked" => true}}) + followed = insert(:user, %{info: %User.Info{locked: true}}) {:ok, follow_activity} = ActivityPub.follow(follower, followed) @@ -585,7 +594,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do test "it fails for incoming accepts which cannot be correlated" do follower = insert(:user) - followed = insert(:user, %{info: %{"locked" => true}}) + followed = insert(:user, %{info: %User.Info{locked: true}}) accept_data = File.read!("test/fixtures/mastodon-accept-activity.json") @@ -604,7 +613,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do test "it fails for incoming rejects which cannot be correlated" do follower = insert(:user) - followed = insert(:user, %{info: %{"locked" => true}}) + followed = insert(:user, %{info: %User.Info{locked: true}}) accept_data = File.read!("test/fixtures/mastodon-reject-activity.json") @@ -623,7 +632,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do test "it works for incoming rejects which are orphaned" do follower = insert(:user) - followed = insert(:user, %{info: %{"locked" => true}}) + followed = insert(:user, %{info: %User.Info{locked: true}}) {:ok, follower} = User.follow(follower, followed) {:ok, _follow_activity} = ActivityPub.follow(follower, followed) @@ -648,7 +657,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do test "it works for incoming rejects which are referenced by IRI only" do follower = insert(:user) - followed = insert(:user, %{info: %{"locked" => true}}) + followed = insert(:user, %{info: %User.Info{locked: true}}) {:ok, follower} = User.follow(follower, followed) {:ok, follow_activity} = ActivityPub.follow(follower, followed) @@ -679,6 +688,36 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do :error = Transmogrifier.handle_incoming(data) end + + test "it remaps video URLs as attachments if necessary" do + {:ok, object} = + ActivityPub.fetch_object_from_id( + "https://peertube.moe/videos/watch/df5f464b-be8d-46fb-ad81-2d4c2d1630e3" + ) + + attachment = %{ + "type" => "Link", + "mediaType" => "video/mp4", + "href" => + "https://peertube.moe/static/webseed/df5f464b-be8d-46fb-ad81-2d4c2d1630e3-480.mp4", + "mimeType" => "video/mp4", + "size" => 5_015_880, + "url" => [ + %{ + "href" => + "https://peertube.moe/static/webseed/df5f464b-be8d-46fb-ad81-2d4c2d1630e3-480.mp4", + "mediaType" => "video/mp4", + "type" => "Link" + } + ], + "width" => 480 + } + + assert object.data["url"] == + "https://peertube.moe/videos/watch/df5f464b-be8d-46fb-ad81-2d4c2d1630e3" + + assert object.data["attachment"] == [attachment] + end end describe "prepare outgoing" do @@ -815,18 +854,18 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do assert "http://localhost:4001/users/rye@niu.moe/followers" in activity.recipients user = Repo.get(User, user.id) - assert user.info["note_count"] == 1 + assert user.info.note_count == 1 {:ok, user} = Transmogrifier.upgrade_user_from_ap_id("https://niu.moe/users/rye") - assert user.info["ap_enabled"] - assert user.info["note_count"] == 1 + assert user.info.ap_enabled + assert user.info.note_count == 1 assert user.follower_address == "https://niu.moe/users/rye/followers" # Wait for the background task :timer.sleep(1000) user = Repo.get(User, user.id) - assert user.info["note_count"] == 1 + assert user.info.note_count == 1 activity = Repo.get(Activity, activity.id) assert user.follower_address in activity.recipients @@ -847,7 +886,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do "https://cdn.niu.moe/accounts/headers/000/033/323/original/850b3448fa5fd477.png" } ] - } = user.info["banner"] + } = user.info.banner refute "..." in activity.recipients @@ -977,13 +1016,12 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do end test "users cannot be collided through fake direction spoofing attempts" do - user = - insert(:user, %{ - nickname: "rye@niu.moe", - local: false, - ap_id: "https://niu.moe/users/rye", - follower_address: User.ap_followers(%User{nickname: "rye@niu.moe"}) - }) + insert(:user, %{ + nickname: "rye@niu.moe", + local: false, + ap_id: "https://niu.moe/users/rye", + follower_address: User.ap_followers(%User{nickname: "rye@niu.moe"}) + }) {:error, _} = User.get_or_fetch_by_ap_id("https://n1u.moe/users/rye") end diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs index fa0cb71bf..42450a7b6 100644 --- a/test/web/admin_api/admin_api_controller_test.exs +++ b/test/web/admin_api/admin_api_controller_test.exs @@ -1,14 +1,16 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do use Pleroma.Web.ConnCase alias Pleroma.{Repo, User} - import Pleroma.Factory - import ExUnit.CaptureLog describe "/api/pleroma/admin/user" do test "Delete" do - admin = insert(:user, info: %{"is_admin" => true}) + admin = insert(:user, info: %{is_admin: true}) user = insert(:user) conn = @@ -21,7 +23,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end test "Create" do - admin = insert(:user, info: %{"is_admin" => true}) + admin = insert(:user, info: %{is_admin: true}) conn = build_conn() @@ -37,9 +39,81 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end end + describe "PUT /api/pleroma/admin/users/tag" do + setup do + admin = insert(:user, info: %{is_admin: true}) + user1 = insert(:user, %{tags: ["x"]}) + user2 = insert(:user, %{tags: ["y"]}) + user3 = insert(:user, %{tags: ["unchanged"]}) + + conn = + build_conn() + |> assign(:user, admin) + |> put_req_header("accept", "application/json") + |> put( + "/api/pleroma/admin/users/tag?nicknames[]=#{user1.nickname}&nicknames[]=#{ + user2.nickname + }&tags[]=foo&tags[]=bar" + ) + + %{conn: conn, user1: user1, user2: user2, user3: user3} + end + + test "it appends specified tags to users with specified nicknames", %{ + conn: conn, + user1: user1, + user2: user2 + } do + assert json_response(conn, :no_content) + assert Repo.get(User, user1.id).tags == ["x", "foo", "bar"] + assert Repo.get(User, user2.id).tags == ["y", "foo", "bar"] + end + + test "it does not modify tags of not specified users", %{conn: conn, user3: user3} do + assert json_response(conn, :no_content) + assert Repo.get(User, user3.id).tags == ["unchanged"] + end + end + + describe "DELETE /api/pleroma/admin/users/tag" do + setup do + admin = insert(:user, info: %{is_admin: true}) + user1 = insert(:user, %{tags: ["x"]}) + user2 = insert(:user, %{tags: ["y", "z"]}) + user3 = insert(:user, %{tags: ["unchanged"]}) + + conn = + build_conn() + |> assign(:user, admin) + |> put_req_header("accept", "application/json") + |> delete( + "/api/pleroma/admin/users/tag?nicknames[]=#{user1.nickname}&nicknames[]=#{ + user2.nickname + }&tags[]=x&tags[]=z" + ) + + %{conn: conn, user1: user1, user2: user2, user3: user3} + end + + test "it removes specified tags from users with specified nicknames", %{ + conn: conn, + user1: user1, + user2: user2 + } do + assert json_response(conn, :no_content) + assert Repo.get(User, user1.id).tags == [] + assert Repo.get(User, user2.id).tags == ["y"] + end + + test "it does not modify tags of not specified users", %{conn: conn, user3: user3} do + assert json_response(conn, :no_content) + assert Repo.get(User, user3.id).tags == ["unchanged"] + end + end + describe "/api/pleroma/admin/permission_group" do test "GET is giving user_info" do - admin = insert(:user, info: %{"is_admin" => true}) + admin = insert(:user, info: %{is_admin: true}) conn = build_conn() @@ -47,33 +121,30 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do |> put_req_header("accept", "application/json") |> get("/api/pleroma/admin/permission_group/#{admin.nickname}") - assert json_response(conn, 200) == admin.info + assert json_response(conn, 200) == %{ + "is_admin" => true, + "is_moderator" => false + } end test "/:right POST, can add to a permission group" do - admin = insert(:user, info: %{"is_admin" => true}) + admin = insert(:user, info: %{is_admin: true}) user = insert(:user) - user_info = - user.info - |> Map.put("is_admin", true) - conn = build_conn() |> assign(:user, admin) |> put_req_header("accept", "application/json") |> post("/api/pleroma/admin/permission_group/#{user.nickname}/admin") - assert json_response(conn, 200) == user_info + assert json_response(conn, 200) == %{ + "is_admin" => true + } end test "/:right DELETE, can remove from a permission group" do - admin = insert(:user, info: %{"is_admin" => true}) - user = insert(:user, info: %{"is_admin" => true}) - - user_info = - user.info - |> Map.put("is_admin", false) + admin = insert(:user, info: %{is_admin: true}) + user = insert(:user, info: %{is_admin: true}) conn = build_conn() @@ -81,12 +152,113 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do |> put_req_header("accept", "application/json") |> delete("/api/pleroma/admin/permission_group/#{user.nickname}/admin") - assert json_response(conn, 200) == user_info + assert json_response(conn, 200) == %{ + "is_admin" => false + } + end + end + + describe "POST /api/pleroma/admin/email_invite, with valid config" do + setup do + registrations_open = Pleroma.Config.get([:instance, :registrations_open]) + invites_enabled = Pleroma.Config.get([:instance, :invites_enabled]) + Pleroma.Config.put([:instance, :registrations_open], false) + Pleroma.Config.put([:instance, :invites_enabled], true) + + on_exit(fn -> + Pleroma.Config.put([:instance, :registrations_open], registrations_open) + Pleroma.Config.put([:instance, :invites_enabled], invites_enabled) + :ok + end) + + [user: insert(:user, info: %{is_admin: true})] + end + + test "sends invitation and returns 204", %{conn: conn, user: user} do + recipient_email = "foo@bar.com" + recipient_name = "J. D." + + conn = + conn + |> assign(:user, user) + |> post("/api/pleroma/admin/email_invite?email=#{recipient_email}&name=#{recipient_name}") + + assert json_response(conn, :no_content) + + token_record = List.last(Pleroma.Repo.all(Pleroma.UserInviteToken)) + assert token_record + refute token_record.used + + Swoosh.TestAssertions.assert_email_sent( + Pleroma.UserEmail.user_invitation_email( + user, + token_record, + recipient_email, + recipient_name + ) + ) + end + + test "it returns 403 if requested by a non-admin", %{conn: conn} do + non_admin_user = insert(:user) + + conn = + conn + |> assign(:user, non_admin_user) + |> post("/api/pleroma/admin/email_invite?email=foo@bar.com&name=JD") + + assert json_response(conn, :forbidden) + end + end + + describe "POST /api/pleroma/admin/email_invite, with invalid config" do + setup do + [user: insert(:user, info: %{is_admin: true})] + end + + test "it returns 500 if `invites_enabled` is not enabled", %{conn: conn, user: user} do + registrations_open = Pleroma.Config.get([:instance, :registrations_open]) + invites_enabled = Pleroma.Config.get([:instance, :invites_enabled]) + Pleroma.Config.put([:instance, :registrations_open], false) + Pleroma.Config.put([:instance, :invites_enabled], false) + + on_exit(fn -> + Pleroma.Config.put([:instance, :registrations_open], registrations_open) + Pleroma.Config.put([:instance, :invites_enabled], invites_enabled) + :ok + end) + + conn = + conn + |> assign(:user, user) + |> post("/api/pleroma/admin/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 + registrations_open = Pleroma.Config.get([:instance, :registrations_open]) + invites_enabled = Pleroma.Config.get([:instance, :invites_enabled]) + Pleroma.Config.put([:instance, :registrations_open], true) + Pleroma.Config.put([:instance, :invites_enabled], true) + + on_exit(fn -> + Pleroma.Config.put([:instance, :registrations_open], registrations_open) + Pleroma.Config.put([:instance, :invites_enabled], invites_enabled) + :ok + end) + + conn = + conn + |> assign(:user, user) + |> post("/api/pleroma/admin/email_invite?email=foo@bar.com&name=JD") + + assert json_response(conn, :internal_server_error) end end test "/api/pleroma/admin/invite_token" do - admin = insert(:user, info: %{"is_admin" => true}) + admin = insert(:user, info: %{is_admin: true}) conn = build_conn() @@ -98,8 +270,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do end test "/api/pleroma/admin/password_reset" do - admin = insert(:user, info: %{"is_admin" => true}) - user = insert(:user, info: %{"is_admin" => true}) + admin = insert(:user, info: %{is_admin: true}) + user = insert(:user) conn = build_conn() diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs index cd36e409c..c3674711a 100644 --- a/test/web/common_api/common_api_test.exs +++ b/test/web/common_api/common_api_test.exs @@ -1,7 +1,12 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.CommonAPI.Test do use Pleroma.DataCase alias Pleroma.Web.CommonAPI alias Pleroma.User + alias Pleroma.Activity import Pleroma.Factory @@ -17,7 +22,7 @@ defmodule Pleroma.Web.CommonAPI.Test do CommonAPI.update(user) user = User.get_cached_by_ap_id(user.ap_id) - [karjalanpiirakka] = user.info["source_data"]["tag"] + [karjalanpiirakka] = user.info.source_data["tag"] assert karjalanpiirakka["name"] == ":karjalanpiirakka:" end @@ -53,4 +58,42 @@ defmodule Pleroma.Web.CommonAPI.Test do assert content == "<p><b>2hu</b></p>alert('xss')" end end + + describe "reactions" do + test "repeating a status" do + user = insert(:user) + other_user = insert(:user) + + {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"}) + + {:ok, %Activity{}, _} = CommonAPI.repeat(activity.id, user) + end + + test "favoriting a status" do + user = insert(:user) + other_user = insert(:user) + + {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"}) + + {:ok, %Activity{}, _} = CommonAPI.favorite(activity.id, user) + end + + test "retweeting a status twice returns an error" 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) + end + + test "favoriting a status twice returns an error" 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) + end + 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 b01ce04f8..fc89e3116 100644 --- a/test/web/common_api/common_api_utils_test.exs +++ b/test/web/common_api/common_api_utils_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.CommonAPI.UtilsTest do alias Pleroma.Web.CommonAPI.Utils alias Pleroma.Web.Endpoint diff --git a/test/web/federator_test.exs b/test/web/federator_test.exs index 02e1ca76e..a49265c0c 100644 --- a/test/web/federator_test.exs +++ b/test/web/federator_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.FederatorTest do alias Pleroma.Web.Federator alias Pleroma.Web.CommonAPI @@ -5,6 +9,11 @@ defmodule Pleroma.Web.FederatorTest do import Pleroma.Factory import Mock + setup_all do + Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + test "enqueues an element according to priority" do queue = [%{item: 1, priority: 2}] diff --git a/test/web/http_sigs/http_sig_test.exs b/test/web/http_sigs/http_sig_test.exs index b2bf8d61b..c4d2eaf78 100644 --- a/test/web/http_sigs/http_sig_test.exs +++ b/test/web/http_sigs/http_sig_test.exs @@ -1,12 +1,19 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + # http signatures # Test data from https://tools.ietf.org/html/draft-cavage-http-signatures-08#appendix-C defmodule Pleroma.Web.HTTPSignaturesTest do use Pleroma.DataCase alias Pleroma.Web.HTTPSignatures import Pleroma.Factory + import Tesla.Mock - @private_key hd(:public_key.pem_decode(File.read!("test/web/http_sigs/priv.key"))) - |> :public_key.pem_entry_decode() + setup do + mock(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end @public_key hd(:public_key.pem_decode(File.read!("test/web/http_sigs/pub.key"))) |> :public_key.pem_entry_decode() @@ -20,8 +27,6 @@ defmodule Pleroma.Web.HTTPSignaturesTest do "content-length" => "18" } - @body "{\"hello\": \"world\"}" - @default_signature """ keyId="Test",algorithm="rsa-sha256",signature="jKyvPcxB4JbmYY4mByyBY7cZfNl4OW9HpFQlG7N4YcJPteKTu4MWCLyk+gIr0wDgqtLWf9NLpMAMimdfsH7FSWGfbMFSrsVTHNTk0rK3usrfFnti1dxsM4jl0kYJCKTGI/UWkqiaxwNiKqGcdlEDrTcUhhsFsOIo8VhddmZTZ8w=" """ diff --git a/test/web/mastodon_api/account_view_test.exs b/test/web/mastodon_api/account_view_test.exs index dc52b92bc..d53e11963 100644 --- a/test/web/mastodon_api/account_view_test.exs +++ b/test/web/mastodon_api/account_view_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.MastodonAPI.AccountViewTest do use Pleroma.DataCase import Pleroma.Factory @@ -17,7 +21,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do user = insert(:user, %{ - info: %{"note_count" => 5, "follower_count" => 3, "source_data" => source_data}, + info: %{note_count: 5, follower_count: 3, source_data: source_data}, nickname: "shp@shitposter.club", name: ":karjalanpiirakka: shp", bio: "<script src=\"invalid-html\"></script><span>valid html</span>", @@ -54,6 +58,10 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do note: "", privacy: "public", sensitive: false + }, + pleroma: %{ + confirmation_pending: false, + tags: [] } } @@ -63,7 +71,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do test "Represent a Service(bot) account" do user = insert(:user, %{ - info: %{"note_count" => 5, "follower_count" => 3, "source_data" => %{"type" => "Service"}}, + info: %{note_count: 5, follower_count: 3, source_data: %{"type" => "Service"}}, nickname: "shp@shitposter.club", inserted_at: ~N[2017-08-15 15:47:06.597036] }) @@ -91,6 +99,10 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do note: "", privacy: "public", sensitive: false + }, + pleroma: %{ + confirmation_pending: false, + tags: [] } } diff --git a/test/web/mastodon_api/list_view_test.exs b/test/web/mastodon_api/list_view_test.exs index 5e36872ed..73143467f 100644 --- a/test/web/mastodon_api/list_view_test.exs +++ b/test/web/mastodon_api/list_view_test.exs @@ -1,8 +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.Web.MastodonAPI.ListViewTest do use Pleroma.DataCase import Pleroma.Factory alias Pleroma.Web.MastodonAPI.ListView - alias Pleroma.List test "Represent a list" do user = 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 ad67cae6b..0136acf8c 100644 --- a/test/web/mastodon_api/mastodon_api_controller_test.exs +++ b/test/web/mastodon_api/mastodon_api_controller_test.exs @@ -1,13 +1,23 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do use Pleroma.Web.ConnCase alias Pleroma.Web.TwitterAPI.TwitterAPI - alias Pleroma.{Repo, User, Activity, Notification} + alias Pleroma.{Repo, User, Object, Activity, Notification} alias Pleroma.Web.{OStatus, CommonAPI} alias Pleroma.Web.ActivityPub.ActivityPub - + alias Pleroma.Web.MastodonAPI.FilterView import Pleroma.Factory import ExUnit.CaptureLog + import Tesla.Mock + + setup do + mock(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end test "the home timeline", %{conn: conn} do user = insert(:user) @@ -252,7 +262,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do end test "verify_credentials default scope unlisted", %{conn: conn} do - user = insert(:user, %{info: %{"default_scope" => "unlisted"}}) + user = insert(:user, %{info: %Pleroma.User.Info{default_scope: "unlisted"}}) conn = conn @@ -286,7 +296,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do assert %{} = json_response(conn, 200) - assert Repo.get(Activity, activity.id) == nil + refute Repo.get(Activity, activity.id) end test "when you didn't create it", %{conn: conn} do @@ -345,12 +355,18 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do {:ok, filter_one} = Pleroma.Filter.create(query_one) {:ok, filter_two} = Pleroma.Filter.create(query_two) - conn = + response = conn |> assign(:user, user) |> get("/api/v1/filters") - - assert response = json_response(conn, 200) + |> json_response(200) + + assert response == + render_json( + FilterView, + "filters.json", + filters: [filter_two, filter_one] + ) end test "get a filter", %{conn: conn} do @@ -383,7 +399,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do context: ["home"] } - {:ok, filter} = Pleroma.Filter.create(query) + {:ok, _filter} = Pleroma.Filter.create(query) new = %Pleroma.Filter{ phrase: "nii", @@ -548,7 +564,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do other_user = insert(:user) {:ok, activity_one} = TwitterAPI.create_status(other_user, %{"status" => "Marisa is cute."}) - {:ok, activity_two} = + {:ok, _activity_two} = TwitterAPI.create_status(other_user, %{ "status" => "Marisa is cute.", "visibility" => "private" @@ -584,7 +600,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do |> get("/api/v1/notifications") expected_response = - "hi <span><a href=\"#{user.ap_id}\">@<span>#{user.nickname}</span></a></span>" + "hi <span><a data-user=\"#{user.id}\" href=\"#{user.ap_id}\">@<span>#{user.nickname}</span></a></span>" assert [%{"status" => %{"content" => response}} | _rest] = json_response(conn, 200) assert response == expected_response @@ -605,7 +621,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do |> get("/api/v1/notifications/#{notification.id}") expected_response = - "hi <span><a href=\"#{user.ap_id}\">@<span>#{user.nickname}</span></a></span>" + "hi <span><a data-user=\"#{user.id}\" href=\"#{user.ap_id}\">@<span>#{user.nickname}</span></a></span>" assert %{"status" => %{"content" => response}} = json_response(conn, 200) assert response == expected_response @@ -804,7 +820,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do } media = - TwitterAPI.upload(file, "json") + TwitterAPI.upload(file, user, "json") |> Poison.decode!() {:ok, image_post} = @@ -824,6 +840,26 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do 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) + {: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"}) + + 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"}) + + assert [%{"id" => id}] = json_response(conn, 200) + assert id == to_string(post.id) + end end describe "user relationships" do @@ -845,10 +881,10 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do describe "locked accounts" do test "/api/v1/follow_requests works" do - user = insert(:user, %{info: %{"locked" => true}}) + user = insert(:user, %{info: %Pleroma.User.Info{locked: true}}) other_user = insert(:user) - {:ok, activity} = ActivityPub.follow(other_user, user) + {:ok, _activity} = ActivityPub.follow(other_user, user) user = Repo.get(User, user.id) other_user = Repo.get(User, other_user.id) @@ -865,10 +901,10 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do end test "/api/v1/follow_requests/:id/authorize works" do - user = insert(:user, %{info: %{"locked" => true}}) + user = insert(:user, %{info: %Pleroma.User.Info{locked: true}}) other_user = insert(:user) - {:ok, activity} = ActivityPub.follow(other_user, user) + {:ok, _activity} = ActivityPub.follow(other_user, user) user = Repo.get(User, user.id) other_user = Repo.get(User, other_user.id) @@ -890,7 +926,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do end test "verify_credentials", %{conn: conn} do - user = insert(:user, %{info: %{"default_scope" => "private"}}) + user = insert(:user, %{info: %Pleroma.User.Info{default_scope: "private"}}) conn = conn @@ -902,10 +938,10 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do end test "/api/v1/follow_requests/:id/reject works" do - user = insert(:user, %{info: %{"locked" => true}}) + user = insert(:user, %{info: %Pleroma.User.Info{locked: true}}) other_user = insert(:user) - {:ok, activity} = ActivityPub.follow(other_user, user) + {:ok, _activity} = ActivityPub.follow(other_user, user) conn = build_conn() @@ -959,6 +995,10 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do assert media["type"] == "image" assert media["description"] == desc + assert media["id"] + + object = Repo.get(Object, media["id"]) + assert object.data["actor"] == User.ap_id(user) end test "hashtag timeline", %{conn: conn} do @@ -1002,6 +1042,31 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do assert id == to_string(user.id) end + test "getting followers, hide_network", %{conn: conn} do + user = insert(:user) + other_user = insert(:user, %{info: %{hide_network: true}}) + {:ok, _user} = User.follow(user, other_user) + + conn = + conn + |> get("/api/v1/accounts/#{other_user.id}/followers") + + assert [] == json_response(conn, 200) + end + + test "getting followers, hide_network, same user requesting", %{conn: conn} do + user = insert(:user) + other_user = insert(:user, %{info: %{hide_network: true}}) + {:ok, _user} = User.follow(user, other_user) + + conn = + conn + |> assign(:user, other_user) + |> get("/api/v1/accounts/#{other_user.id}/followers") + + refute [] == json_response(conn, 200) + end + test "getting following", %{conn: conn} do user = insert(:user) other_user = insert(:user) @@ -1015,6 +1080,31 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do assert id == to_string(other_user.id) end + test "getting following, hide_network", %{conn: conn} do + user = insert(:user, %{info: %{hide_network: true}}) + other_user = insert(:user) + {:ok, user} = User.follow(user, other_user) + + conn = + conn + |> get("/api/v1/accounts/#{user.id}/following") + + assert [] == json_response(conn, 200) + end + + test "getting following, hide_network, same user requesting", %{conn: conn} do + user = insert(:user, %{info: %{hide_network: true}}) + other_user = insert(:user) + {:ok, user} = User.follow(user, other_user) + + conn = + conn + |> assign(:user, user) + |> get("/api/v1/accounts/#{user.id}/following") + + refute [] == json_response(conn, 200) + end + test "following / unfollowing a user", %{conn: conn} do user = insert(:user) other_user = insert(:user) @@ -1105,7 +1195,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do refute User.blocks?(user, other_user) end - test "getting a list of domain blocks" do + test "getting a list of domain blocks", %{conn: conn} do user = insert(:user) {:ok, user} = User.block_domain(user, "bad.site") @@ -1253,14 +1343,33 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do describe "updating credentials" do 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", %{ + "note" => "I drink #cofe with @#{user2.nickname}" + }) + + assert user = json_response(conn, 200) + + assert user["note"] == + "I drink <a data-tag=\"cofe\" href=\"http://localhost:4001/tag/cofe\">#cofe</a> with <span><a data-user=\"#{ + user2.id + }\" href=\"#{user2.ap_id}\">@<span>#{user2.nickname}</span></a></span>" + end + + test "updates the user's locking status", %{conn: conn} do + user = insert(:user) conn = conn |> assign(:user, user) - |> patch("/api/v1/accounts/update_credentials", %{"note" => "I drink #cofe"}) + |> patch("/api/v1/accounts/update_credentials", %{locked: "true"}) assert user = json_response(conn, 200) - assert user["note"] == "I drink #cofe" + assert user["locked"] == true end test "updates the user's name", %{conn: conn} do @@ -1289,8 +1398,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do |> assign(:user, user) |> patch("/api/v1/accounts/update_credentials", %{"avatar" => new_avatar}) - assert user = json_response(conn, 200) - assert user["avatar"] != "https://placehold.it/48x48" + 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 @@ -1307,8 +1416,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do |> assign(:user, user) |> patch("/api/v1/accounts/update_credentials", %{"header" => new_header}) - assert user = json_response(conn, 200) - assert user["header"] != "https://placehold.it/700x335" + assert user_response = json_response(conn, 200) + assert user_response["header"] != User.banner_url(user) end end @@ -1330,4 +1439,18 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do assert result["stats"]["user_count"] == 2 assert result["stats"]["status_count"] == 1 end + + test "put settings", %{conn: conn} do + user = insert(:user) + + conn = + conn + |> assign(:user, user) + |> put("/api/web/settings", %{"data" => %{"programming" => "socks"}}) + + assert result = json_response(conn, 200) + + user = User.get_cached_by_ap_id(user.ap_id) + assert user.info.settings == %{"programming" => "socks"} + end end diff --git a/test/web/mastodon_api/mastodon_socket_test.exs b/test/web/mastodon_api/mastodon_socket_test.exs deleted file mode 100644 index c7d71defc..000000000 --- a/test/web/mastodon_api/mastodon_socket_test.exs +++ /dev/null @@ -1,33 +0,0 @@ -defmodule Pleroma.Web.MastodonApi.MastodonSocketTest do - use Pleroma.DataCase - - alias Pleroma.Web.MastodonApi.MastodonSocket - alias Pleroma.Web.{Streamer, CommonAPI} - alias Pleroma.User - - import Pleroma.Factory - - test "public is working when non-authenticated" do - user = insert(:user) - - task = - Task.async(fn -> - assert_receive {:text, _}, 4_000 - end) - - fake_socket = %{ - transport_pid: task.pid, - assigns: %{} - } - - topics = %{ - "public" => [fake_socket] - } - - {:ok, activity} = CommonAPI.post(user, %{"status" => "Test"}) - - Streamer.push_to_socket(topics, "public", activity) - - Task.await(task) - end -end diff --git a/test/web/mastodon_api/status_view_test.exs b/test/web/mastodon_api/status_view_test.exs index 31554a07d..b953ccd76 100644 --- a/test/web/mastodon_api/status_view_test.exs +++ b/test/web/mastodon_api/status_view_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.MastodonAPI.StatusViewTest do use Pleroma.DataCase @@ -5,7 +9,15 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do alias Pleroma.User alias Pleroma.Web.OStatus alias Pleroma.Web.CommonAPI + alias Pleroma.Web.ActivityPub.ActivityPub + alias Pleroma.Activity import Pleroma.Factory + import Tesla.Mock + + setup do + mock(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end test "a note with null content" do note = insert(:note_activity) @@ -18,7 +30,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do note |> Map.put(:data, data) - user = User.get_cached_by_ap_id(note.data["actor"]) + User.get_cached_by_ap_id(note.data["actor"]) status = StatusView.render("status.json", %{activity: note}) @@ -56,7 +68,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do visibility: "public", media_attachments: [], mentions: [], - tags: [], + tags: [ + %{ + name: "#{note.data["object"]["tag"]}", + url: "/tag/#{note.data["object"]["tag"]}" + } + ], application: %{ name: "Web", website: nil @@ -145,4 +162,41 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do assert represented[:reblog][:id] == to_string(activity.id) assert represented[:emojis] == [] end + + test "a peertube video" do + user = insert(:user) + + {:ok, object} = + ActivityPub.fetch_object_from_id( + "https://peertube.moe/videos/watch/df5f464b-be8d-46fb-ad81-2d4c2d1630e3" + ) + + %Activity{} = activity = Activity.get_create_activity_by_object_ap_id(object.data["id"]) + + represented = StatusView.render("status.json", %{for: user, activity: activity}) + + assert represented[:id] == to_string(activity.id) + assert length(represented[:media_attachments]) == 1 + end + + describe "build_tags/1" do + test "it returns a a dictionary tags" do + object_tags = [ + "fediverse", + "mastodon", + "nextcloud", + %{ + "href" => "https://kawen.space/users/lain", + "name" => "@lain@kawen.space", + "type" => "Mention" + } + ] + + assert StatusView.build_tags(object_tags) == [ + %{name: "fediverse", url: "/tag/fediverse"}, + %{name: "mastodon", url: "/tag/mastodon"}, + %{name: "nextcloud", url: "/tag/nextcloud"} + ] + end + end end diff --git a/test/web/node_info_test.exs b/test/web/node_info_test.exs index a6376453c..5981c70a7 100644 --- a/test/web/node_info_test.exs +++ b/test/web/node_info_test.exs @@ -1,10 +1,14 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.NodeInfoTest do use Pleroma.Web.ConnCase import Pleroma.Factory test "nodeinfo shows staff accounts", %{conn: conn} do - user = insert(:user, %{local: true, info: %{"is_moderator" => true}}) + user = insert(:user, %{local: true, info: %{is_moderator: true}}) conn = conn @@ -15,7 +19,18 @@ defmodule Pleroma.Web.NodeInfoTest do assert user.ap_id in result["metadata"]["staffAccounts"] end - test "returns 404 when federation is disabled" do + test "nodeinfo shows restricted nicknames", %{conn: conn} do + conn = + conn + |> get("/nodeinfo/2.0.json") + + assert result = json_response(conn, 200) + + assert Pleroma.Config.get([Pleroma.User, :restricted_nicknames]) == + result["metadata"]["restrictedNicknames"] + end + + test "returns 404 when federation is disabled", %{conn: conn} do instance = Application.get_env(:pleroma, :instance) |> Keyword.put(:federating, false) @@ -37,7 +52,7 @@ defmodule Pleroma.Web.NodeInfoTest do Application.put_env(:pleroma, :instance, instance) end - test "returns 200 when federation is enabled" do + test "returns 200 when federation is enabled", %{conn: conn} do conn |> get("/.well-known/nodeinfo") |> json_response(200) diff --git a/test/web/oauth/authorization_test.exs b/test/web/oauth/authorization_test.exs index 98c7c4133..3b1ddada8 100644 --- a/test/web/oauth/authorization_test.exs +++ b/test/web/oauth/authorization_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OAuth.AuthorizationTest do use Pleroma.DataCase alias Pleroma.Web.OAuth.{Authorization, App} @@ -71,7 +75,7 @@ defmodule Pleroma.Web.OAuth.AuthorizationTest do {:ok, auth} = Authorization.create_authorization(app, user) {:ok, auth} = Authorization.use_token(auth) - {auths, _} = Authorization.delete_user_authorizations(user) + Authorization.delete_user_authorizations(user) {_, invalid} = Authorization.use_token(auth) diff --git a/test/web/oauth/oauth_controller_test.exs b/test/web/oauth/oauth_controller_test.exs index 3a902f128..ccd552258 100644 --- a/test/web/oauth/oauth_controller_test.exs +++ b/test/web/oauth/oauth_controller_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OAuth.OAuthControllerTest do use Pleroma.Web.ConnCase import Pleroma.Factory @@ -50,6 +54,26 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do assert Repo.get_by(Token, token: token) end + test "issues a token for `password` grant_type with valid credentials" do + password = "testpassword" + user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password)) + + app = insert(:oauth_app) + + conn = + build_conn() + |> post("/oauth/token", %{ + "grant_type" => "password", + "username" => user.nickname, + "password" => password, + "client_id" => app.client_id, + "client_secret" => app.client_secret + }) + + assert %{"access_token" => token} = json_response(conn, 200) + assert Repo.get_by(Token, token: token) + end + test "issues a token for request with HTTP basic auth client credentials" do user = insert(:user) app = insert(:oauth_app) @@ -93,6 +117,43 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do refute Map.has_key?(resp, "access_token") end + test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do + setting = Pleroma.Config.get([:instance, :account_activation_required]) + + unless setting do + Pleroma.Config.put([:instance, :account_activation_required], true) + on_exit(fn -> Pleroma.Config.put([:instance, :account_activation_required], setting) end) + end + + password = "testpassword" + user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password)) + info_change = Pleroma.User.Info.confirmation_changeset(user.info, :unconfirmed) + + {:ok, user} = + user + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_embed(:info, info_change) + |> Repo.update() + + refute Pleroma.User.auth_active?(user) + + app = insert(:oauth_app) + + conn = + build_conn() + |> post("/oauth/token", %{ + "grant_type" => "password", + "username" => user.nickname, + "password" => password, + "client_id" => app.client_id, + "client_secret" => app.client_secret + }) + + assert resp = json_response(conn, 403) + assert %{"error" => _} = resp + refute Map.has_key?(resp, "access_token") + end + test "rejects an invalid authorization code" do app = insert(:oauth_app) diff --git a/test/web/oauth/token_test.exs b/test/web/oauth/token_test.exs index f926ff50b..9a241d61a 100644 --- a/test/web/oauth/token_test.exs +++ b/test/web/oauth/token_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OAuth.TokenTest do use Pleroma.DataCase alias Pleroma.Web.OAuth.{App, Token, Authorization} @@ -54,8 +58,8 @@ defmodule Pleroma.Web.OAuth.TokenTest do {:ok, auth1} = Authorization.create_authorization(app1, user) {:ok, auth2} = Authorization.create_authorization(app2, user) - {:ok, token1} = Token.exchange_token(app1, auth1) - {:ok, token2} = Token.exchange_token(app2, auth2) + {:ok, _token1} = Token.exchange_token(app1, auth1) + {:ok, _token2} = Token.exchange_token(app2, auth2) {tokens, _} = Token.delete_user_tokens(user) diff --git a/test/web/ostatus/activity_representer_test.exs b/test/web/ostatus/activity_representer_test.exs index 8bf3bc775..0869f2fd5 100644 --- a/test/web/ostatus/activity_representer_test.exs +++ b/test/web/ostatus/activity_representer_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.ActivityRepresenterTest do use Pleroma.DataCase @@ -7,6 +11,12 @@ defmodule Pleroma.Web.OStatus.ActivityRepresenterTest do alias Pleroma.Web.OStatus import Pleroma.Factory + import Tesla.Mock + + setup do + mock(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end test "an external note activity" do incoming = File.read!("test/fixtures/mastodon-note-cw.xml") diff --git a/test/web/ostatus/feed_representer_test.exs b/test/web/ostatus/feed_representer_test.exs index bf3feb14e..55717dec7 100644 --- a/test/web/ostatus/feed_representer_test.exs +++ b/test/web/ostatus/feed_representer_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.FeedRepresenterTest do use Pleroma.DataCase import Pleroma.Factory diff --git a/test/web/ostatus/incoming_documents/delete_handling_test.exs b/test/web/ostatus/incoming_documents/delete_handling_test.exs index 1e041e5b0..c8fbff6cc 100644 --- a/test/web/ostatus/incoming_documents/delete_handling_test.exs +++ b/test/web/ostatus/incoming_documents/delete_handling_test.exs @@ -25,7 +25,7 @@ defmodule Pleroma.Web.OStatus.DeleteHandlingTest do refute Repo.get(Activity, note.id) refute Repo.get(Activity, like.id) - refute Object.get_by_ap_id(note.data["object"]["id"]) + assert Object.get_by_ap_id(note.data["object"]["id"]).data["type"] == "Tombstone" assert Repo.get(Activity, second_note.id) assert Object.get_by_ap_id(second_note.data["object"]["id"]) diff --git a/test/web/ostatus/ostatus_controller_test.exs b/test/web/ostatus/ostatus_controller_test.exs index 371c835c0..995cc00d6 100644 --- a/test/web/ostatus/ostatus_controller_test.exs +++ b/test/web/ostatus/ostatus_controller_test.exs @@ -1,10 +1,19 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.OStatusControllerTest do use Pleroma.Web.ConnCase import Pleroma.Factory - alias Pleroma.{User, Repo} + alias Pleroma.{User, Repo, Object} alias Pleroma.Web.CommonAPI alias Pleroma.Web.OStatus.ActivityRepresenter + setup_all do + Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + test "decodes a salmon", %{conn: conn} do user = insert(:user) salmon = File.read!("test/fixtures/salmon.xml") @@ -31,14 +40,16 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do # Set a wrong magic-key for a user so it has to refetch salmon_user = User.get_by_ap_id("http://gs.example.org:4040/index.php/user/1") # Wrong key - info = - salmon_user.info - |> Map.put( - "magic_key", - "RSA.pu0s-halox4tu7wmES1FVSx6u-4wc0YrUFXcqWXZG4-27UmbCOpMQftRCldNRfyA-qLbz-eqiwrong1EwUvjsD4cYbAHNGHwTvDOyx5AKthQUP44ykPv7kjKGh3DWKySJvcs9tlUG87hlo7AvnMo9pwRS_Zz2CacQ-MKaXyDepk=.AQAB" - ) + info_cng = + User.Info.remote_user_creation(salmon_user.info, %{ + magic_key: + "RSA.pu0s-halox4tu7wmES1FVSx6u-4wc0YrUFXcqWXZG4-27UmbCOpMQftRCldNRfyA-qLbz-eqiwrong1EwUvjsD4cYbAHNGHwTvDOyx5AKthQUP44ykPv7kjKGh3DWKySJvcs9tlUG87hlo7AvnMo9pwRS_Zz2CacQ-MKaXyDepk=.AQAB" + }) - Repo.update(User.info_changeset(salmon_user, %{info: info})) + salmon_user + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_embed(:info, info_cng) + |> Repo.update() conn = build_conn() @@ -90,82 +101,74 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do test "404s on private objects", %{conn: conn} do note_activity = insert(:direct_note_activity) - user = User.get_by_ap_id(note_activity.data["actor"]) [_, uuid] = hd(Regex.scan(~r/.+\/([\w-]+)$/, note_activity.data["object"]["id"])) - url = "/objects/#{uuid}" - conn = - conn - |> get(url) - - assert response(conn, 404) + conn + |> get("/objects/#{uuid}") + |> response(404) end test "404s on nonexisting objects", %{conn: conn} do - url = "/objects/123" + conn + |> get("/objects/123") + |> response(404) + end - conn = - conn - |> get(url) + test "404s on deleted objects", %{conn: conn} do + note_activity = insert(:note_activity) + [_, uuid] = hd(Regex.scan(~r/.+\/([\w-]+)$/, note_activity.data["object"]["id"])) + object = Object.get_by_ap_id(note_activity.data["object"]["id"]) - assert response(conn, 404) + conn + |> get("/objects/#{uuid}") + |> response(200) + + Object.delete(object) + + conn + |> get("/objects/#{uuid}") + |> response(404) end test "gets an activity", %{conn: conn} do note_activity = insert(:note_activity) [_, uuid] = hd(Regex.scan(~r/.+\/([\w-]+)$/, note_activity.data["id"])) - url = "/activities/#{uuid}" - - conn = - conn - |> get(url) - assert response(conn, 200) + conn + |> get("/activities/#{uuid}") + |> response(200) end test "404s on private activities", %{conn: conn} do note_activity = insert(:direct_note_activity) [_, uuid] = hd(Regex.scan(~r/.+\/([\w-]+)$/, note_activity.data["id"])) - url = "/activities/#{uuid}" - conn = - conn - |> get(url) - - assert response(conn, 404) + conn + |> get("/activities/#{uuid}") + |> response(404) end test "404s on nonexistent activities", %{conn: conn} do - url = "/activities/123" - - conn = - conn - |> get(url) - - assert response(conn, 404) + conn + |> get("/activities/123") + |> response(404) end test "gets a notice", %{conn: conn} do note_activity = insert(:note_activity) - url = "/notice/#{note_activity.id}" - conn = - conn - |> get(url) - - assert response(conn, 200) + conn + |> get("/notice/#{note_activity.id}") + |> response(200) end test "gets a notice in AS2 format", %{conn: conn} do note_activity = insert(:note_activity) - url = "/notice/#{note_activity.id}" - conn = - conn - |> put_req_header("accept", "application/activity+json") - |> get(url) - - assert json_response(conn, 200) + conn + |> put_req_header("accept", "application/activity+json") + |> get("/notice/#{note_activity.id}") + |> json_response(200) end test "only gets a notice in AS2 format for Create messages", %{conn: conn} do diff --git a/test/web/ostatus/ostatus_test.exs b/test/web/ostatus/ostatus_test.exs index f95da8b0a..403cc7095 100644 --- a/test/web/ostatus/ostatus_test.exs +++ b/test/web/ostatus/ostatus_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatusTest do use Pleroma.DataCase alias Pleroma.Web.OStatus @@ -6,6 +10,11 @@ defmodule Pleroma.Web.OStatusTest do import Pleroma.Factory import ExUnit.CaptureLog + setup_all do + Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + test "don't insert create notes twice" do incoming = File.read!("test/fixtures/incoming_note_activity.xml") {:ok, [activity]} = OStatus.handle_incoming(incoming) @@ -17,7 +26,7 @@ defmodule Pleroma.Web.OStatusTest do {:ok, [activity]} = OStatus.handle_incoming(incoming) user = User.get_by_ap_id(activity.data["actor"]) - assert user.info["note_count"] == 1 + assert user.info.note_count == 1 assert activity.data["type"] == "Create" assert activity.data["object"]["type"] == "Note" @@ -319,7 +328,7 @@ defmodule Pleroma.Web.OStatusTest do assert user.name == "Constance Variable" assert user.nickname == "lambadalambda@social.heldscal.la" assert user.local == false - assert user.info["uri"] == uri + assert user.info.uri == uri assert user.ap_id == uri assert user.bio == "Call me Deacon Blues." assert user.avatar["type"] == "Image" @@ -329,6 +338,38 @@ defmodule Pleroma.Web.OStatusTest do assert user == user_again end + test "find_or_make_user sets all the nessary input fields" do + uri = "https://social.heldscal.la/user/23211" + {:ok, user} = OStatus.find_or_make_user(uri) + + assert user.info == + %Pleroma.User.Info{ + id: user.info.id, + ap_enabled: false, + background: %{}, + banner: %{}, + blocks: [], + deactivated: false, + default_scope: "public", + domain_blocks: [], + follower_count: 0, + is_admin: false, + is_moderator: false, + keys: nil, + locked: false, + no_rich_text: false, + note_count: 0, + settings: nil, + source_data: %{}, + hub: "https://social.heldscal.la/main/push/hub", + magic_key: + "RSA.uzg6r1peZU0vXGADWxGJ0PE34WvmhjUmydbX5YYdOiXfODVLwCMi1umGoqUDm-mRu4vNEdFBVJU1CpFA7dKzWgIsqsa501i2XqElmEveXRLvNRWFB6nG03Q5OUY2as8eE54BJm0p20GkMfIJGwP6TSFb-ICp3QjzbatuSPJ6xCE=.AQAB", + salmon: "https://social.heldscal.la/main/salmon/user/23211", + topic: "https://social.heldscal.la/api/statuses/user_timeline/23211.atom", + uri: "https://social.heldscal.la/user/23211" + } + end + test "find_make_or_update_user takes an author element and returns an updated user" do uri = "https://social.heldscal.la/user/23211" @@ -447,7 +488,7 @@ defmodule Pleroma.Web.OStatusTest do end end - test "it doesn't add nil in the do field" do + test "it doesn't add nil in the to field" do incoming = File.read!("test/fixtures/nil_mention_entry.xml") {:ok, [activity]} = OStatus.handle_incoming(incoming) @@ -474,7 +515,7 @@ defmodule Pleroma.Web.OStatusTest do |> Map.put("type", "Article") cs = Object.change(note_object, %{data: note_data}) - {:ok, article_object} = Repo.update(cs) + {:ok, _article_object} = Repo.update(cs) # the underlying object is now an Article instead of a note, so this should fail refute OStatus.is_representable?(note_activity) diff --git a/test/web/ostatus/user_representer_test.exs b/test/web/ostatus/user_representer_test.exs index e41dfeb3d..e3863d2e9 100644 --- a/test/web/ostatus/user_representer_test.exs +++ b/test/web/ostatus/user_representer_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.UserRepresenterTest do use Pleroma.DataCase alias Pleroma.Web.OStatus.UserRepresenter @@ -6,7 +10,7 @@ defmodule Pleroma.Web.OStatus.UserRepresenterTest do alias Pleroma.User test "returns a user with id, uri, name and link" do - user = build(:user, nickname: "レイン") + user = insert(:user, %{nickname: "レイン"}) tuple = UserRepresenter.to_simple_form(user) res = :xmerl.export_simple_content(tuple, :xmerl_xml) |> to_string diff --git a/test/web/plugs/federating_plug_test.exs b/test/web/plugs/federating_plug_test.exs index 1455a1c46..612db7e32 100644 --- a/test/web/plugs/federating_plug_test.exs +++ b/test/web/plugs/federating_plug_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.FederatingPlugTest do use Pleroma.Web.ConnCase diff --git a/test/web/retry_queue_test.exs b/test/web/retry_queue_test.exs index ce2964993..9351b6c24 100644 --- a/test/web/retry_queue_test.exs +++ b/test/web/retry_queue_test.exs @@ -1,10 +1,14 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule MockActivityPub do def publish_one(ret) do {ret, "success"} end end -defmodule Pleroma.ActivityTest do +defmodule Pleroma.Web.Federator.RetryQueueTest do use Pleroma.DataCase alias Pleroma.Web.Federator.RetryQueue diff --git a/test/web/salmon/salmon_test.exs b/test/web/salmon/salmon_test.exs index 1b39b4b2d..c539a28b2 100644 --- a/test/web/salmon/salmon_test.exs +++ b/test/web/salmon/salmon_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Salmon.SalmonTest do use Pleroma.DataCase alias Pleroma.Web.Salmon @@ -10,6 +14,11 @@ defmodule Pleroma.Web.Salmon.SalmonTest do @magickey_friendica "RSA.AMwa8FUs2fWEjX0xN7yRQgegQffhBpuKNC6fa5VNSVorFjGZhRrlPMn7TQOeihlc9lBz2OsHlIedbYn2uJ7yCs0.AQAB" + setup_all do + Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + test "decodes a salmon" do {:ok, salmon} = File.read("test/fixtures/salmon.xml") {:ok, doc} = Salmon.decode_and_validate(@magickey, salmon) @@ -69,7 +78,7 @@ defmodule Pleroma.Web.Salmon.SalmonTest do test "it pushes an activity to remote accounts it's addressed to" do user_data = %{ info: %{ - "salmon" => "http://example.org/salmon" + salmon: "http://test-example.org/salmon" }, local: false } @@ -91,8 +100,8 @@ defmodule Pleroma.Web.Salmon.SalmonTest do user = Repo.get_by(User, ap_id: activity.data["actor"]) {:ok, user} = Pleroma.Web.WebFinger.ensure_keys_present(user) - poster = fn url, _data, _headers, _options -> - assert url == "http://example.org/salmon" + poster = fn url, _data, _headers -> + assert url == "http://test-example.org/salmon" end Salmon.publish(user, activity, poster) diff --git a/test/web/streamer_test.exs b/test/web/streamer_test.exs index 47d491d1b..905e29d06 100644 --- a/test/web/streamer_test.exs +++ b/test/web/streamer_test.exs @@ -1,8 +1,12 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.StreamerTest do use Pleroma.DataCase alias Pleroma.Web.Streamer - alias Pleroma.User + alias Pleroma.{List, User} alias Pleroma.Web.CommonAPI import Pleroma.Factory @@ -60,4 +64,111 @@ defmodule Pleroma.Web.StreamerTest do Task.await(task) end + + test "it doesn't send unwanted DMs to list" do + user_a = insert(:user) + user_b = insert(:user) + user_c = insert(:user) + + {:ok, user_a} = User.follow(user_a, user_b) + + {:ok, list} = List.create("Test", user_a) + {:ok, list} = List.follow(list, user_b) + + task = + Task.async(fn -> + refute_receive {:text, _}, 1_000 + end) + + fake_socket = %{ + transport_pid: task.pid, + assigns: %{ + user: user_a + } + } + + {:ok, activity} = + CommonAPI.post(user_b, %{ + "status" => "@#{user_c.nickname} Test", + "visibility" => "direct" + }) + + topics = %{ + "list:#{list.id}" => [fake_socket] + } + + Streamer.handle_cast(%{action: :stream, topic: "list", item: activity}, topics) + + Task.await(task) + end + + test "it doesn't send unwanted private posts to list" do + user_a = insert(:user) + user_b = insert(:user) + + {:ok, list} = List.create("Test", user_a) + {:ok, list} = List.follow(list, user_b) + + task = + Task.async(fn -> + refute_receive {:text, _}, 1_000 + end) + + fake_socket = %{ + transport_pid: task.pid, + assigns: %{ + user: user_a + } + } + + {:ok, activity} = + CommonAPI.post(user_b, %{ + "status" => "Test", + "visibility" => "private" + }) + + topics = %{ + "list:#{list.id}" => [fake_socket] + } + + Streamer.handle_cast(%{action: :stream, topic: "list", item: activity}, topics) + + Task.await(task) + end + + test "it send wanted private posts to list" do + user_a = insert(:user) + user_b = insert(:user) + + {:ok, user_a} = User.follow(user_a, user_b) + + {:ok, list} = List.create("Test", user_a) + {:ok, list} = List.follow(list, user_b) + + task = + Task.async(fn -> + assert_receive {:text, _}, 1_000 + end) + + fake_socket = %{ + transport_pid: task.pid, + assigns: %{ + user: user_a + } + } + + {:ok, activity} = + CommonAPI.post(user_b, %{ + "status" => "Test", + "visibility" => "private" + }) + + topics = %{ + "list:#{list.id}" => [fake_socket] + } + + Streamer.handle_cast(%{action: :stream, topic: "list", item: activity}, topics) + + Task.await(task) + end end diff --git a/test/web/twitter_api/representers/activity_representer_test.exs b/test/web/twitter_api/representers/activity_representer_test.exs index 291fd5237..2ac32aeb2 100644 --- a/test/web/twitter_api/representers/activity_representer_test.exs +++ b/test/web/twitter_api/representers/activity_representer_test.exs @@ -1,9 +1,12 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.Representers.ActivityRepresenterTest do use Pleroma.DataCase alias Pleroma.{User, Activity, Object} alias Pleroma.Web.TwitterAPI.Representers.{ActivityRepresenter, ObjectRepresenter} alias Pleroma.Web.ActivityPub.ActivityPub - alias Pleroma.Builders.UserBuilder alias Pleroma.Web.TwitterAPI.UserView import Pleroma.Factory @@ -58,7 +61,7 @@ defmodule Pleroma.Web.TwitterAPI.Representers.ActivityRepresenterTest do end test "an activity" do - {:ok, user} = UserBuilder.insert() + user = insert(:user) # {:ok, mentioned_user } = UserBuilder.insert(%{nickname: "shp", ap_id: "shp"}) mentioned_user = insert(:user, %{nickname: "shp"}) diff --git a/test/web/twitter_api/representers/object_representer_test.exs b/test/web/twitter_api/representers/object_representer_test.exs index 228b2ac42..c3cf330f1 100644 --- a/test/web/twitter_api/representers/object_representer_test.exs +++ b/test/web/twitter_api/representers/object_representer_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.Representers.ObjectReprenterTest do use Pleroma.DataCase diff --git a/test/web/twitter_api/twitter_api_controller_test.exs b/test/web/twitter_api/twitter_api_controller_test.exs index 6bdcb4fd8..a4526eeda 100644 --- a/test/web/twitter_api/twitter_api_controller_test.exs +++ b/test/web/twitter_api/twitter_api_controller_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.ControllerTest do use Pleroma.Web.ConnCase alias Pleroma.Web.TwitterAPI.Representers.ActivityRepresenter @@ -9,45 +13,56 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do alias Pleroma.Web.CommonAPI alias Pleroma.Web.TwitterAPI.TwitterAPI alias Comeonin.Pbkdf2 + alias Ecto.Changeset import Pleroma.Factory - describe "POST /api/account/verify_credentials" do - setup [:valid_user] + @banner "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7" - test "without valid credentials", %{conn: conn} do - conn = post(conn, "/api/account/verify_credentials.json") - assert json_response(conn, 403) == %{"error" => "Invalid credentials."} + describe "POST /api/account/update_profile_banner" do + test "it updates the banner", %{conn: conn} do + user = insert(:user) + + conn + |> assign(:user, user) + |> post(authenticated_twitter_api__path(conn, :update_banner), %{"banner" => @banner}) + |> json_response(200) + + user = refresh_record(user) + assert user.info.banner["type"] == "Image" end + end - test "with credentials", %{conn: conn, user: user} do - conn = - conn - |> with_credentials(user.nickname, "test") - |> post("/api/account/verify_credentials.json") + describe "POST /api/qvitter/update_background_image" do + test "it updates the background", %{conn: conn} do + user = insert(:user) - assert response = json_response(conn, 200) - assert response == UserView.render("show.json", %{user: user, token: response["token"]}) + conn + |> assign(:user, user) + |> post(authenticated_twitter_api__path(conn, :update_background), %{"img" => @banner}) + |> json_response(200) + + user = refresh_record(user) + assert user.info.background["type"] == "Image" end end - describe "POST /api/account/most_recent_notification" do + describe "POST /api/account/verify_credentials" do setup [:valid_user] test "without valid credentials", %{conn: conn} do - conn = post(conn, "/api/account/most_recent_notification.json") + conn = post(conn, "/api/account/verify_credentials.json") assert json_response(conn, 403) == %{"error" => "Invalid credentials."} end test "with credentials", %{conn: conn, user: user} do - conn = + response = conn |> with_credentials(user.nickname, "test") - |> post("/api/account/most_recent_notification.json", %{id: "200"}) + |> post("/api/account/verify_credentials.json") + |> json_response(200) - assert json_response(conn, 200) - user = User.get_by_nickname(user.nickname) - assert user.info["most_recent_notification"] == 200 + assert response == UserView.render("show.json", %{user: user, token: response["token"]}) end end @@ -68,17 +83,28 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do "error" => "Client must provide a 'status' parameter with a value." } - conn = conn_with_creds |> post(request_path) + conn = + conn_with_creds + |> post(request_path) + assert json_response(conn, 400) == error_response - conn = conn_with_creds |> post(request_path, %{status: ""}) + conn = + conn_with_creds + |> post(request_path, %{status: ""}) + assert json_response(conn, 400) == error_response - conn = conn_with_creds |> post(request_path, %{status: " "}) + conn = + conn_with_creds + |> post(request_path, %{status: " "}) + assert json_response(conn, 400) == error_response # we post with visibility private in order to avoid triggering relay - conn = conn_with_creds |> post(request_path, %{status: "Nice meme.", visibility: "private"}) + conn = + conn_with_creds + |> post(request_path, %{status: "Nice meme.", visibility: "private"}) assert json_response(conn, 200) == ActivityRepresenter.to_map(Repo.one(Activity), %{user: user}) @@ -86,8 +112,10 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do end describe "GET /statuses/public_timeline.json" do + setup [:valid_user] + test "returns statuses", %{conn: conn} do - {:ok, user} = UserBuilder.insert() + user = insert(:user) activities = ActivityBuilder.insert_list(30, %{}, %{user: user}) ActivityBuilder.insert_list(10, %{}, %{user: user}) since_id = List.last(activities).id @@ -101,7 +129,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do assert length(response) == 10 end - test "returns 403 to unauthenticated request when the instance is not public" do + test "returns 403 to unauthenticated request when the instance is not public", %{conn: conn} do instance = Application.get_env(:pleroma, :instance) |> Keyword.put(:public, false) @@ -119,15 +147,45 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do Application.put_env(:pleroma, :instance, instance) end - test "returns 200 to unauthenticated request when the instance is public" do + test "returns 200 to authenticated request when the instance is not public", + %{conn: conn, user: user} do + instance = + Application.get_env(:pleroma, :instance) + |> Keyword.put(:public, false) + + Application.put_env(:pleroma, :instance, instance) + conn + |> with_credentials(user.nickname, "test") + |> get("/api/statuses/public_timeline.json") + |> json_response(200) + + instance = + Application.get_env(:pleroma, :instance) + |> Keyword.put(:public, true) + + Application.put_env(:pleroma, :instance, instance) + end + + test "returns 200 to unauthenticated request when the instance is public", %{conn: conn} do + conn + |> get("/api/statuses/public_timeline.json") + |> json_response(200) + end + + test "returns 200 to authenticated request when the instance is public", + %{conn: conn, user: user} do + conn + |> with_credentials(user.nickname, "test") |> get("/api/statuses/public_timeline.json") |> json_response(200) end end describe "GET /statuses/public_and_external_timeline.json" do - test "returns 403 to unauthenticated request when the instance is not public" do + setup [:valid_user] + + test "returns 403 to unauthenticated request when the instance is not public", %{conn: conn} do instance = Application.get_env(:pleroma, :instance) |> Keyword.put(:public, false) @@ -145,11 +203,39 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do Application.put_env(:pleroma, :instance, instance) end - test "returns 200 to unauthenticated request when the instance is public" do + test "returns 200 to authenticated request when the instance is not public", + %{conn: conn, user: user} do + instance = + Application.get_env(:pleroma, :instance) + |> Keyword.put(:public, false) + + Application.put_env(:pleroma, :instance, instance) + + conn + |> with_credentials(user.nickname, "test") + |> get("/api/statuses/public_and_external_timeline.json") + |> json_response(200) + + instance = + Application.get_env(:pleroma, :instance) + |> Keyword.put(:public, true) + + Application.put_env(:pleroma, :instance, instance) + end + + test "returns 200 to unauthenticated request when the instance is public", %{conn: conn} do conn |> get("/api/statuses/public_and_external_timeline.json") |> json_response(200) end + + test "returns 200 to authenticated request when the instance is public", + %{conn: conn, user: user} do + conn + |> with_credentials(user.nickname, "test") + |> get("/api/statuses/public_and_external_timeline.json") + |> json_response(200) + end end describe "GET /statuses/show/:id.json" do @@ -249,7 +335,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do since_id = List.last(activities).id current_user = - Ecto.Changeset.change(current_user, following: [User.ap_followers(user)]) + Changeset.change(current_user, following: [User.ap_followers(user)]) |> Repo.update!() conn = @@ -493,6 +579,34 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do assert length(response) == 1 assert Enum.at(response, 0) == ActivityRepresenter.to_map(activity, %{user: user}) end + + test "with credentials with user_id, excluding RTs", %{conn: conn, user: current_user} do + user = insert(:user) + {:ok, activity} = ActivityBuilder.insert(%{"id" => 1, "type" => "Create"}, %{user: user}) + {:ok, _} = ActivityBuilder.insert(%{"id" => 2, "type" => "Announce"}, %{user: user}) + + conn = + conn + |> with_credentials(current_user.nickname, "test") + |> get("/api/statuses/user_timeline.json", %{ + "user_id" => user.id, + "include_rts" => "false" + }) + + response = json_response(conn, 200) + + assert length(response) == 1 + assert Enum.at(response, 0) == ActivityRepresenter.to_map(activity, %{user: user}) + + conn = + conn + |> get("/api/statuses/user_timeline.json", %{"user_id" => user.id, "include_rts" => "0"}) + + response = json_response(conn, 200) + + assert length(response) == 1 + assert Enum.at(response, 0) == ActivityRepresenter.to_map(activity, %{user: user}) + end end describe "POST /friendships/create.json" do @@ -591,7 +705,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do |> post("/api/blocks/destroy.json", %{user_id: blocked.id}) current_user = Repo.get(User, current_user.id) - assert current_user.info["blocks"] == [] + assert current_user.info.blocks == [] assert json_response(conn, 200) == UserView.render("show.json", %{user: blocked, for: current_user}) @@ -638,14 +752,13 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do end test "unimplemented mutes with credentials", %{conn: conn, user: current_user} do - conn = + response = conn |> with_credentials(current_user.nickname, "test") |> get("/api/qvitter/mutes.json") + |> json_response(200) - current_user = Repo.get(User, current_user.id) - - assert [] = json_response(conn, 200) + assert [] = response end end @@ -812,6 +925,129 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do end end + describe "POST /api/account/password_reset, with valid parameters" do + setup %{conn: conn} do + user = insert(:user) + conn = post(conn, "/api/account/password_reset?email=#{user.email}") + %{conn: conn, user: user} + end + + test "it returns 204", %{conn: conn} do + assert json_response(conn, :no_content) + end + + test "it creates a PasswordResetToken record for user", %{user: user} do + token_record = Repo.get_by(Pleroma.PasswordResetToken, user_id: user.id) + assert token_record + end + + test "it sends an email to user", %{user: user} do + token_record = Repo.get_by(Pleroma.PasswordResetToken, user_id: user.id) + + Swoosh.TestAssertions.assert_email_sent( + Pleroma.UserEmail.password_reset_email(user, token_record.token) + ) + end + end + + describe "POST /api/account/password_reset, with invalid parameters" do + setup [:valid_user] + + test "it returns 500 when user is not found", %{conn: conn, user: user} do + conn = post(conn, "/api/account/password_reset?email=nonexisting_#{user.email}") + assert json_response(conn, :internal_server_error) + end + + test "it returns 500 when user is not local", %{conn: conn, user: user} do + {:ok, user} = Repo.update(Changeset.change(user, local: false)) + conn = post(conn, "/api/account/password_reset?email=#{user.email}") + assert json_response(conn, :internal_server_error) + end + end + + describe "GET /api/account/confirm_email/:id/:token" do + setup do + user = insert(:user) + info_change = User.Info.confirmation_changeset(user.info, :unconfirmed) + + {:ok, user} = + user + |> Changeset.change() + |> Changeset.put_embed(:info, info_change) + |> Repo.update() + + assert user.info.confirmation_pending + + [user: user] + end + + test "it redirects to root url", %{conn: conn, user: user} do + conn = get(conn, "/api/account/confirm_email/#{user.id}/#{user.info.confirmation_token}") + + assert 302 == conn.status + end + + test "it confirms the user account", %{conn: conn, user: user} do + get(conn, "/api/account/confirm_email/#{user.id}/#{user.info.confirmation_token}") + + user = Repo.get(User, user.id) + + refute user.info.confirmation_pending + refute user.info.confirmation_token + end + + test "it returns 500 if user cannot be found by id", %{conn: conn, user: user} do + conn = get(conn, "/api/account/confirm_email/0/#{user.info.confirmation_token}") + + assert 500 == conn.status + end + + test "it returns 500 if token is invalid", %{conn: conn, user: user} do + conn = get(conn, "/api/account/confirm_email/#{user.id}/wrong_token") + + assert 500 == conn.status + end + end + + describe "POST /api/account/resend_confirmation_email" do + setup do + setting = Pleroma.Config.get([:instance, :account_activation_required]) + + unless setting do + Pleroma.Config.put([:instance, :account_activation_required], true) + on_exit(fn -> Pleroma.Config.put([:instance, :account_activation_required], setting) end) + end + + user = insert(:user) + info_change = User.Info.confirmation_changeset(user.info, :unconfirmed) + + {:ok, user} = + user + |> Changeset.change() + |> Changeset.put_embed(:info, info_change) + |> Repo.update() + + assert user.info.confirmation_pending + + [user: user] + end + + test "it returns 204 No Content", %{conn: conn, user: user} do + conn + |> assign(:user, user) + |> post("/api/account/resend_confirmation_email?email=#{user.email}") + |> json_response(:no_content) + end + + test "it sends confirmation email", %{conn: conn, user: user} do + conn + |> assign(:user, user) + |> post("/api/account/resend_confirmation_email?email=#{user.email}") + + Swoosh.TestAssertions.assert_email_sent(Pleroma.UserEmail.account_confirmation_email(user)) + end + end + describe "GET /api/externalprofile/show" do test "it returns the user", %{conn: conn} do user = insert(:user) @@ -845,6 +1081,68 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do result = json_response(conn, 200) assert Enum.sort(expected) == Enum.sort(result) end + + test "it returns a given user's followers with user_id", %{conn: conn} do + user = insert(:user) + follower_one = insert(:user) + follower_two = insert(:user) + not_follower = insert(:user) + + {:ok, follower_one} = User.follow(follower_one, user) + {:ok, follower_two} = User.follow(follower_two, user) + + conn = + conn + |> assign(:user, not_follower) + |> get("/api/statuses/followers", %{"user_id" => user.id}) + + assert MapSet.equal?( + MapSet.new(json_response(conn, 200)), + MapSet.new( + UserView.render("index.json", %{ + users: [follower_one, follower_two], + for: not_follower + }) + ) + ) + end + + test "it returns empty for a hidden network", %{conn: conn} do + user = insert(:user, %{info: %{hide_network: true}}) + follower_one = insert(:user) + follower_two = insert(:user) + not_follower = insert(:user) + + {:ok, _follower_one} = User.follow(follower_one, user) + {:ok, _follower_two} = User.follow(follower_two, user) + + response = + conn + |> assign(:user, not_follower) + |> get("/api/statuses/followers", %{"user_id" => user.id}) + |> json_response(200) + + assert [] == response + end + + test "it returns the followers for a hidden network if requested by the user themselves", %{ + conn: conn + } do + user = insert(:user, %{info: %{hide_network: true}}) + follower_one = insert(:user) + follower_two = insert(:user) + _not_follower = insert(:user) + + {:ok, _follower_one} = User.follow(follower_one, user) + {:ok, _follower_two} = User.follow(follower_two, user) + + conn = + conn + |> assign(:user, user) + |> get("/api/statuses/followers", %{"user_id" => user.id}) + + refute [] == json_response(conn, 200) + end end describe "GET /api/statuses/friends" do @@ -889,6 +1187,43 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do ) end + test "it returns empty for a hidden network", %{conn: conn} do + user = insert(:user, %{info: %{hide_network: true}}) + followed_one = insert(:user) + followed_two = insert(:user) + not_followed = insert(:user) + + {:ok, user} = User.follow(user, followed_one) + {:ok, user} = User.follow(user, followed_two) + + conn = + conn + |> assign(:user, not_followed) + |> get("/api/statuses/friends", %{"user_id" => user.id}) + + assert [] == json_response(conn, 200) + end + + test "it returns friends for a hidden network if the user themselves request it", %{ + conn: conn + } do + user = insert(:user, %{info: %{hide_network: true}}) + followed_one = insert(:user) + followed_two = insert(:user) + _not_followed = insert(:user) + + {:ok, _user} = User.follow(user, followed_one) + {:ok, _user} = User.follow(user, followed_two) + + response = + conn + |> assign(:user, user) + |> get("/api/statuses/friends", %{"user_id" => user.id}) + |> json_response(200) + + refute [] == response + end + test "it returns a given user's friends with screen_name", %{conn: conn} do user = insert(:user) followed_one = insert(:user) @@ -939,22 +1274,51 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do describe "POST /api/account/update_profile.json" do test "it updates a user's profile", %{conn: conn} do user = insert(:user) + user2 = insert(:user) conn = conn |> assign(:user, user) |> post("/api/account/update_profile.json", %{ "name" => "new name", - "description" => "new description" + "description" => "hi @#{user2.nickname}" }) user = Repo.get!(User, user.id) assert user.name == "new name" - assert user.bio == "new description" + + assert user.bio == + "hi <span><a data-user='#{user2.id}' class='mention' href='#{user2.ap_id}'>@<span>#{ + user2.nickname + }</span></a></span>" assert json_response(conn, 200) == UserView.render("user.json", %{user: user, for: user}) end + test "it sets and un-sets hide_network", %{conn: conn} do + user = insert(:user) + + conn + |> assign(:user, user) + |> post("/api/account/update_profile.json", %{ + "hide_network" => "true" + }) + + user = Repo.get!(User, user.id) + assert user.info.hide_network == true + + conn = + conn + |> assign(:user, user) + |> post("/api/account/update_profile.json", %{ + "hide_network" => "false" + }) + + user = Repo.get!(User, user.id) + assert user.info.hide_network == false + assert json_response(conn, 200) == UserView.render("user.json", %{user: user, for: user}) + end + test "it locks an account", %{conn: conn} do user = insert(:user) @@ -966,7 +1330,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do }) user = Repo.get!(User, user.id) - assert user.info["locked"] == true + assert user.info.locked == true assert json_response(conn, 200) == UserView.render("user.json", %{user: user, for: user}) end @@ -982,7 +1346,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do }) user = Repo.get!(User, user.id) - assert user.info["locked"] == false + assert user.info.locked == false assert json_response(conn, 200) == UserView.render("user.json", %{user: user, for: user}) end @@ -1153,10 +1517,10 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do describe "GET /api/pleroma/friend_requests" do test "it lists friend requests" do - user = insert(:user, %{info: %{"locked" => true}}) + user = insert(:user) other_user = insert(:user) - {:ok, activity} = ActivityPub.follow(other_user, user) + {:ok, _activity} = ActivityPub.follow(other_user, user) user = Repo.get(User, user.id) other_user = Repo.get(User, other_user.id) @@ -1175,10 +1539,10 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do describe "POST /api/pleroma/friendships/approve" do test "it approves a friend request" do - user = insert(:user, %{info: %{"locked" => true}}) + user = insert(:user) other_user = insert(:user) - {:ok, activity} = ActivityPub.follow(other_user, user) + {:ok, _activity} = ActivityPub.follow(other_user, user) user = Repo.get(User, user.id) other_user = Repo.get(User, other_user.id) @@ -1198,10 +1562,10 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do describe "POST /api/pleroma/friendships/deny" do test "it denies a friend request" do - user = insert(:user, %{info: %{"locked" => true}}) + user = insert(:user) other_user = insert(:user) - {:ok, activity} = ActivityPub.follow(other_user, user) + {:ok, _activity} = ActivityPub.follow(other_user, user) user = Repo.get(User, user.id) other_user = Repo.get(User, other_user.id) @@ -1234,4 +1598,82 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do assert [user.id, user_two.id, user_three.id] == Enum.map(resp, fn %{"id" => id} -> id end) end end + + describe "POST /api/media/upload" do + setup context do + Pleroma.DataCase.ensure_local_uploader(context) + end + + test "it performs the upload and sets `data[actor]` with AP id of uploader user", %{ + conn: conn + } do + user = insert(:user) + + upload_filename = "test/fixtures/image_tmp.jpg" + File.cp!("test/fixtures/image.jpg", upload_filename) + + file = %Plug.Upload{ + content_type: "image/jpg", + path: Path.absname(upload_filename), + filename: "image.jpg" + } + + response = + conn + |> assign(:user, user) + |> put_req_header("content-type", "application/octet-stream") + |> post("/api/media/upload", %{ + "media" => file + }) + |> json_response(:ok) + + assert response["media_id"] + object = Repo.get(Object, response["media_id"]) + assert object + assert object.data["actor"] == User.ap_id(user) + end + end + + describe "POST /api/media/metadata/create" do + setup do + object = insert(:note) + user = User.get_by_ap_id(object.data["actor"]) + %{object: object, user: user} + end + + test "it returns :forbidden status on attempt to modify someone else's upload", %{ + conn: conn, + object: object + } do + initial_description = object.data["name"] + another_user = insert(:user) + + conn + |> assign(:user, another_user) + |> post("/api/media/metadata/create", %{"media_id" => object.id}) + |> json_response(:forbidden) + + object = Repo.get(Object, object.id) + assert object.data["name"] == initial_description + end + + test "it updates `data[name]` of referenced Object with provided value", %{ + conn: conn, + object: object, + user: user + } do + description = "Informative description of the image. Initial value: #{object.data["name"]}}" + + conn + |> assign(:user, user) + |> post("/api/media/metadata/create", %{ + "media_id" => object.id, + "alt_text" => %{"text" => description} + }) + |> json_response(:no_content) + + object = Repo.get(Object, object.id) + assert object.data["name"] == description + end + end end diff --git a/test/web/twitter_api/twitter_api_test.exs b/test/web/twitter_api/twitter_api_test.exs index 8b9920bd9..b9feb23d4 100644 --- a/test/web/twitter_api/twitter_api_test.exs +++ b/test/web/twitter_api/twitter_api_test.exs @@ -1,6 +1,9 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do use Pleroma.DataCase - alias Pleroma.Builders.UserBuilder alias Pleroma.Web.TwitterAPI.{TwitterAPI, UserView} alias Pleroma.{Activity, User, Object, Repo, UserInviteToken} alias Pleroma.Web.ActivityPub.ActivityPub @@ -10,7 +13,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do test "create a status" do user = insert(:user) - _mentioned_user = UserBuilder.insert(%{nickname: "shp", ap_id: "shp"}) + mentioned_user = insert(:user, %{nickname: "shp", ap_id: "shp"}) object_data = %{ "type" => "Image", @@ -35,7 +38,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do {:ok, activity = %Activity{}} = TwitterAPI.create_status(user, input) expected_text = - "Hello again, <span><a class='mention' href='shp'>@<span>shp</span></a></span>.<script></script><br>This is on another :moominmamma: line. <a href='http://localhost:4001/tag/2hu' rel='tag'>#2hu</a> <a href='http://localhost:4001/tag/epic' rel='tag'>#epic</a> <a href='http://localhost:4001/tag/phantasmagoric' rel='tag'>#phantasmagoric</a><br><a href=\"http://example.org/image.jpg\" class='attachment'>image.jpg</a>" + "Hello again, <span><a data-user='#{mentioned_user.id}' class='mention' href='shp'>@<span>shp</span></a></span>.<script></script><br>This is on another :moominmamma: line. <a data-tag='2hu' href='http://localhost:4001/tag/2hu' rel='tag'>#2hu</a> <a data-tag='epic' href='http://localhost:4001/tag/epic' rel='tag'>#epic</a> <a data-tag='phantasmagoric' href='http://localhost:4001/tag/phantasmagoric' rel='tag'>#phantasmagoric</a><br><a href=\"http://example.org/image.jpg\" class='attachment'>image.jpg</a>" assert get_in(activity.data, ["object", "content"]) == expected_text assert get_in(activity.data, ["object", "type"]) == "Note" @@ -67,7 +70,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do user = User.get_by_ap_id(user.ap_id) - assert user.info["note_count"] == 1 + assert user.info.note_count == 1 end test "create a status that is a reply" do @@ -116,7 +119,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do assert User.ap_followers(followed) in user.following followed = User.get_by_ap_id(followed.ap_id) - assert followed.info["follower_count"] == 1 + assert followed.info.follower_count == 1 {:error, msg} = TwitterAPI.follow(user, %{"screen_name" => followed.nickname}) assert msg == "Could not follow user: #{followed.nickname} is already on your list." @@ -169,7 +172,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do {:ok, user, _unblocked} = TwitterAPI.block(user, %{"user_id" => unblocked.id}) {:ok, user, _unblocked} = TwitterAPI.unblock(user, %{"user_id" => unblocked.id}) - assert user.info["blocks"] == [] + assert user.info.blocks == [] end test "Unblock another user using screen_name" do @@ -178,17 +181,19 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do {:ok, user, _unblocked} = TwitterAPI.block(user, %{"screen_name" => unblocked.nickname}) {:ok, user, _unblocked} = TwitterAPI.unblock(user, %{"screen_name" => unblocked.nickname}) - assert user.info["blocks"] == [] + assert user.info.blocks == [] end test "upload a file" do + user = insert(:user) + file = %Plug.Upload{ content_type: "image/jpg", path: Path.absname("test/fixtures/image.jpg"), filename: "an_image.jpg" } - response = TwitterAPI.upload(file) + response = TwitterAPI.upload(file, user) assert is_binary(response) end @@ -244,7 +249,6 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do "nickname" => "lain", "email" => "lain@wired.jp", "fullname" => "lain iwakura", - "bio" => "close the world.", "password" => "bear", "confirm" => "bear" } @@ -257,6 +261,78 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do UserView.render("show.json", %{user: fetched_user}) end + test "it registers a new user with empty string in bio and returns the user." do + data = %{ + "nickname" => "lain", + "email" => "lain@wired.jp", + "fullname" => "lain iwakura", + "bio" => "", + "password" => "bear", + "confirm" => "bear" + } + + {:ok, user} = TwitterAPI.register_user(data) + + fetched_user = Repo.get_by(User, nickname: "lain") + + assert UserView.render("show.json", %{user: user}) == + UserView.render("show.json", %{user: fetched_user}) + end + + @moduletag skip: "needs 'account_activation_required: true' in config" + test "it sends confirmation email if :account_activation_required is specified in instance config" do + setting = Pleroma.Config.get([:instance, :account_activation_required]) + + unless setting do + Pleroma.Config.put([:instance, :account_activation_required], true) + on_exit(fn -> Pleroma.Config.put([:instance, :account_activation_required], setting) end) + end + + data = %{ + "nickname" => "lain", + "email" => "lain@wired.jp", + "fullname" => "lain iwakura", + "bio" => "", + "password" => "bear", + "confirm" => "bear" + } + + {:ok, user} = TwitterAPI.register_user(data) + + assert user.info.confirmation_pending + + Swoosh.TestAssertions.assert_email_sent(Pleroma.UserEmail.account_confirmation_email(user)) + end + + test "it registers a new user and parses mentions in the bio" do + data1 = %{ + "nickname" => "john", + "email" => "john@gmail.com", + "fullname" => "John Doe", + "bio" => "test", + "password" => "bear", + "confirm" => "bear" + } + + {:ok, user1} = TwitterAPI.register_user(data1) + + data2 = %{ + "nickname" => "lain", + "email" => "lain@wired.jp", + "fullname" => "lain iwakura", + "bio" => "@john test", + "password" => "bear", + "confirm" => "bear" + } + + {:ok, user2} = TwitterAPI.register_user(data2) + + expected_text = + "<span><a data-user='#{user1.id}' class='mention' href='#{user1.ap_id}'>@<span>john</span></a></span> test" + + assert user2.bio == expected_text + end + @moduletag skip: "needs 'registrations_open: false' in config" test "it registers a new user via invite token and returns the user." do {:ok, token} = UserInviteToken.create_token() diff --git a/test/web/twitter_api/views/activity_view_test.exs b/test/web/twitter_api/views/activity_view_test.exs index 5cef06f88..013245033 100644 --- a/test/web/twitter_api/views/activity_view_test.exs +++ b/test/web/twitter_api/views/activity_view_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.ActivityViewTest do use Pleroma.DataCase @@ -12,8 +16,31 @@ defmodule Pleroma.Web.TwitterAPI.ActivityViewTest do alias Pleroma.Web.ActivityPub.ActivityPub import Pleroma.Factory + import Tesla.Mock + + setup do + mock(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + import Mock + test "a create activity with a html status" do + text = """ + #Bike log - Commute Tuesday\nhttps://pla.bike/posts/20181211/\n#cycling #CHScycling #commute\nMVIMG_20181211_054020.jpg + """ + + {:ok, activity} = CommonAPI.post(insert(:user), %{"status" => text}) + + result = ActivityView.render("activity.json", activity: activity) + + assert result["statusnet_html"] == + "<a data-tag=\"bike\" href=\"http://localhost:4001/tag/bike\">#Bike</a> log - Commute Tuesday<br /><a href=\"https://pla.bike/posts/20181211/\">https://pla.bike/posts/20181211/</a><br /><a data-tag=\"cycling\" href=\"http://localhost:4001/tag/cycling\">#cycling</a> <a data-tag=\"chscycling\" href=\"http://localhost:4001/tag/chscycling\">#CHScycling</a> <a data-tag=\"commute\" href=\"http://localhost:4001/tag/commute\">#commute</a><br />MVIMG_20181211_054020.jpg" + + assert result["text"] == + "#Bike log - Commute Tuesday\nhttps://pla.bike/posts/20181211/\n#cycling #CHScycling #commute\nMVIMG_20181211_054020.jpg" + end + test "a create activity with a note" do user = insert(:user) other_user = insert(:user, %{nickname: "shp"}) @@ -47,7 +74,7 @@ defmodule Pleroma.Web.TwitterAPI.ActivityViewTest do "repeated" => false, "statusnet_conversation_id" => convo_id, "statusnet_html" => - "Hey <span><a href=\"#{other_user.ap_id}\">@<span>shp</span></a></span>!", + "Hey <span><a data-user=\"#{other_user.id}\" href=\"#{other_user.ap_id}\">@<span>shp</span></a></span>!", "tags" => [], "text" => "Hey @shp!", "uri" => activity.data["object"]["id"], @@ -112,6 +139,7 @@ defmodule Pleroma.Web.TwitterAPI.ActivityViewTest do {:ok, like, _object} = CommonAPI.favorite(activity.id, other_user) result = ActivityView.render("activity.json", activity: like) + activity = Pleroma.Activity.get_by_ap_id(activity.data["id"]) expected = %{ "activity_type" => "like", @@ -121,6 +149,7 @@ defmodule Pleroma.Web.TwitterAPI.ActivityViewTest do "in_reply_to_status_id" => activity.id, "is_local" => true, "is_post_verb" => false, + "favorited_status" => ActivityView.render("activity.json", activity: activity), "statusnet_html" => "shp favorited a status.", "text" => "shp favorited a status.", "uri" => "tag:#{like.data["id"]}:objectType=Favourite", @@ -148,6 +177,7 @@ defmodule Pleroma.Web.TwitterAPI.ActivityViewTest do "in_reply_to_status_id" => nil, "is_local" => true, "is_post_verb" => false, + "favorited_status" => nil, "statusnet_html" => "shp favorited a status.", "text" => "shp favorited a status.", "uri" => "tag:#{like.data["id"]}:objectType=Favourite", @@ -239,4 +269,18 @@ defmodule Pleroma.Web.TwitterAPI.ActivityViewTest do assert result == expected end + + test "a peertube video" do + {:ok, object} = + ActivityPub.fetch_object_from_id( + "https://peertube.moe/videos/watch/df5f464b-be8d-46fb-ad81-2d4c2d1630e3" + ) + + %Activity{} = activity = Activity.get_create_activity_by_object_ap_id(object.data["id"]) + + result = ActivityView.render("activity.json", activity: activity) + + assert length(result["attachments"]) == 1 + assert result["summary"] == "Friday Night" + end end diff --git a/test/web/twitter_api/views/notification_view_test.exs b/test/web/twitter_api/views/notification_view_test.exs index 79eafda7d..8367fc6c7 100644 --- a/test/web/twitter_api/views/notification_view_test.exs +++ b/test/web/twitter_api/views/notification_view_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.NotificationViewTest do use Pleroma.DataCase @@ -8,7 +12,6 @@ defmodule Pleroma.Web.TwitterAPI.NotificationViewTest do alias Pleroma.Web.TwitterAPI.ActivityView alias Pleroma.Web.CommonAPI.Utils alias Pleroma.Web.ActivityPub.ActivityPub - alias Pleroma.Builders.UserBuilder import Pleroma.Factory @@ -67,7 +70,7 @@ defmodule Pleroma.Web.TwitterAPI.NotificationViewTest do user = User.get_cached_by_ap_id(note_activity.data["actor"]) repeater = insert(:user) - {:ok, activity} = TwitterAPI.repeat(repeater, note_activity.id) + {:ok, _activity} = TwitterAPI.repeat(repeater, note_activity.id) [notification] = Notification.for_user(user) represented = %{ @@ -89,7 +92,7 @@ defmodule Pleroma.Web.TwitterAPI.NotificationViewTest do user = User.get_cached_by_ap_id(note_activity.data["actor"]) liker = insert(:user) - {:ok, activity} = TwitterAPI.fav(liker, note_activity.id) + {:ok, _activity} = TwitterAPI.fav(liker, note_activity.id) [notification] = Notification.for_user(user) represented = %{ diff --git a/test/web/twitter_api/views/user_view_test.exs b/test/web/twitter_api/views/user_view_test.exs index 2c583c0d3..32e9466e1 100644 --- a/test/web/twitter_api/views/user_view_test.exs +++ b/test/web/twitter_api/views/user_view_test.exs @@ -1,10 +1,13 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.UserViewTest do use Pleroma.DataCase alias Pleroma.User alias Pleroma.Web.TwitterAPI.UserView alias Pleroma.Web.CommonAPI.Utils - alias Pleroma.Builders.UserBuilder import Pleroma.Factory @@ -27,14 +30,14 @@ defmodule Pleroma.Web.TwitterAPI.UserViewTest do assert represented["profile_image_url"] == image end - test "A user with emoji in username", %{user: user} do + test "A user with emoji in username" do expected = "<img height=\"32px\" width=\"32px\" alt=\"karjalanpiirakka\" title=\"karjalanpiirakka\" src=\"/file.png\" /> man" - user = %{ - user - | info: %{ - "source_data" => %{ + user = + insert(:user, %{ + info: %{ + source_data: %{ "tag" => [ %{ "type" => "Emoji", @@ -43,10 +46,10 @@ defmodule Pleroma.Web.TwitterAPI.UserViewTest do } ] } - } - } + }, + name: ":karjalanpiirakka: man" + }) - user = %{user | name: ":karjalanpiirakka: man"} represented = UserView.render("show.json", %{user: user}) assert represented["name_html"] == expected end @@ -96,14 +99,18 @@ defmodule Pleroma.Web.TwitterAPI.UserViewTest do "locked" => false, "default_scope" => "public", "no_rich_text" => false, - "fields" => [] + "fields" => [], + "pleroma" => %{ + "confirmation_pending" => false, + "tags" => [] + } } assert represented == UserView.render("show.json", %{user: user}) end test "A user for a given other follower", %{user: user} do - {:ok, follower} = UserBuilder.insert(%{following: [User.ap_followers(user)]}) + follower = insert(:user, %{following: [User.ap_followers(user)]}) {:ok, user} = User.update_follower_count(user) image = "http://localhost:4001/images/avi.png" banner = "http://localhost:4001/images/banner.png" @@ -137,7 +144,11 @@ defmodule Pleroma.Web.TwitterAPI.UserViewTest do "locked" => false, "default_scope" => "public", "no_rich_text" => false, - "fields" => [] + "fields" => [], + "pleroma" => %{ + "confirmation_pending" => false, + "tags" => [] + } } assert represented == UserView.render("show.json", %{user: user, for: follower}) @@ -179,14 +190,18 @@ defmodule Pleroma.Web.TwitterAPI.UserViewTest do "locked" => false, "default_scope" => "public", "no_rich_text" => false, - "fields" => [] + "fields" => [], + "pleroma" => %{ + "confirmation_pending" => false, + "tags" => [] + } } assert represented == UserView.render("show.json", %{user: follower, for: user}) end test "a user that is a moderator" do - user = insert(:user, %{info: %{"is_moderator" => true}}) + user = insert(:user, %{info: %{is_moderator: true}}) represented = UserView.render("show.json", %{user: user, for: user}) assert represented["rights"]["delete_others_notice"] @@ -228,7 +243,11 @@ defmodule Pleroma.Web.TwitterAPI.UserViewTest do "locked" => false, "default_scope" => "public", "no_rich_text" => false, - "fields" => [] + "fields" => [], + "pleroma" => %{ + "confirmation_pending" => false, + "tags" => [] + } } blocker = Repo.get(User, blocker.id) @@ -250,7 +269,7 @@ defmodule Pleroma.Web.TwitterAPI.UserViewTest do user = insert(:user, %{ info: %{ - "source_data" => %{ + source_data: %{ "attachment" => Enum.map(fields, fn field -> Map.put(field, "type", "PropertyValue") end) } diff --git a/test/web/views/error_view_test.exs b/test/web/views/error_view_test.exs index 1d443b187..16a0c8cef 100644 --- a/test/web/views/error_view_test.exs +++ b/test/web/views/error_view_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ErrorViewTest do use Pleroma.Web.ConnCase, async: true diff --git a/test/web/web_finger/web_finger_controller_test.exs b/test/web/web_finger/web_finger_controller_test.exs new file mode 100644 index 000000000..43fccfc7a --- /dev/null +++ b/test/web/web_finger/web_finger_controller_test.exs @@ -0,0 +1,46 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.WebFinger.WebFingerControllerTest do + use Pleroma.Web.ConnCase + + import Pleroma.Factory + import Tesla.Mock + + setup do + mock(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + + test "Webfinger JRD" do + user = insert(:user) + + response = + build_conn() + |> put_req_header("accept", "application/jrd+json") + |> get("/.well-known/webfinger?resource=acct:#{user.nickname}@localhost") + + assert json_response(response, 200)["subject"] == "acct:#{user.nickname}@localhost" + end + + test "Webfinger XML" do + user = insert(:user) + + response = + build_conn() + |> put_req_header("accept", "application/xrd+xml") + |> get("/.well-known/webfinger?resource=acct:#{user.nickname}@localhost") + + assert response(response, 200) + end + + test "Sends a 400 when resource param is missing" do + response = + build_conn() + |> put_req_header("accept", "application/xrd+xml,application/jrd+json") + |> get("/.well-known/webfinger") + + assert response(response, 400) + end +end diff --git a/test/web/web_finger/web_finger_test.exs b/test/web/web_finger/web_finger_test.exs index 99bf210ea..6b20d8d56 100644 --- a/test/web/web_finger/web_finger_test.exs +++ b/test/web/web_finger/web_finger_test.exs @@ -1,7 +1,17 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.WebFingerTest do use Pleroma.DataCase alias Pleroma.Web.WebFinger import Pleroma.Factory + import Tesla.Mock + + setup do + mock(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end describe "host meta" do test "returns a link to the xml lrdd" do @@ -99,15 +109,15 @@ defmodule Pleroma.Web.WebFingerTest do describe "ensure_keys_present" do test "it creates keys for a user and stores them in info" do user = insert(:user) - refute is_binary(user.info["keys"]) + refute is_binary(user.info.keys) {:ok, user} = WebFinger.ensure_keys_present(user) - assert is_binary(user.info["keys"]) + assert is_binary(user.info.keys) end test "it doesn't create keys if there already are some" do - user = insert(:user, %{info: %{"keys" => "xxx"}}) + user = insert(:user, %{info: %{keys: "xxx"}}) {:ok, user} = WebFinger.ensure_keys_present(user) - assert user.info["keys"] == "xxx" + assert user.info.keys == "xxx" end end end diff --git a/test/web/websub/websub_controller_test.exs b/test/web/websub/websub_controller_test.exs index d861c241f..9cbcda063 100644 --- a/test/web/websub/websub_controller_test.exs +++ b/test/web/websub/websub_controller_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Websub.WebsubControllerTest do use Pleroma.Web.ConnCase import Pleroma.Factory diff --git a/test/web/websub/websub_test.exs b/test/web/websub/websub_test.exs index 5914a37fc..9751d161d 100644 --- a/test/web/websub/websub_test.exs +++ b/test/web/websub/websub_test.exs @@ -1,8 +1,6 @@ -defmodule Pleroma.Web.WebsubMock do - def verify(sub) do - {:ok, sub} - end -end +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only defmodule Pleroma.Web.WebsubTest do use Pleroma.DataCase @@ -10,6 +8,12 @@ defmodule Pleroma.Web.WebsubTest do alias Pleroma.Web.Websub.{WebsubServerSubscription, WebsubClientSubscription} import Pleroma.Factory alias Pleroma.Web.Router.Helpers + import Tesla.Mock + + setup do + mock(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end test "a verification of a request that is accepted" do sub = insert(:websub_subscription) @@ -26,8 +30,8 @@ defmodule Pleroma.Web.WebsubTest do assert String.to_integer(seconds) > 0 {:ok, - %HTTPoison.Response{ - status_code: 200, + %Tesla.Env{ + status: 200, body: challenge }} end @@ -41,8 +45,8 @@ defmodule Pleroma.Web.WebsubTest do getter = fn _path, _headers, _options -> {:ok, - %HTTPoison.Response{ - status_code: 500, + %Tesla.Env{ + status: 500, body: "" }} end @@ -99,7 +103,7 @@ defmodule Pleroma.Web.WebsubTest do test "initiate a subscription for a given user and topic" do subscriber = insert(:user) - user = insert(:user, %{info: %{"topic" => "some_topic", "hub" => "some_hub"}}) + user = insert(:user, %{info: %Pleroma.User.Info{topic: "some_topic", hub: "some_hub"}}) {:ok, websub} = Websub.subscribe(subscriber, user, &accepting_verifier/1) assert websub.subscribers == [subscriber.ap_id] @@ -113,12 +117,7 @@ defmodule Pleroma.Web.WebsubTest do test "discovers the hub and canonical url" do topic = "https://mastodon.social/users/lambadalambda.atom" - getter = fn ^topic -> - doc = File.read!("test/fixtures/lambadalambda.atom") - {:ok, %{status_code: 200, body: doc}} - end - - {:ok, discovered} = Websub.gather_feed_data(topic, getter) + {:ok, discovered} = Websub.gather_feed_data(topic) expected = %{ "hub" => "https://mastodon.social/api/push", @@ -158,7 +157,7 @@ defmodule Pleroma.Web.WebsubTest do websub.id ) - {:ok, %{status_code: 202}} + {:ok, %{status: 202}} end task = Task.async(fn -> Websub.request_subscription(websub, poster) end) @@ -177,7 +176,7 @@ defmodule Pleroma.Web.WebsubTest do websub = insert(:websub_client_subscription, %{hub: hub, topic: topic}) poster = fn ^hub, {:form, _data}, _headers -> - {:ok, %{status_code: 202}} + {:ok, %{status: 202}} end {:error, websub} = Websub.request_subscription(websub, poster, 1000) @@ -186,7 +185,7 @@ defmodule Pleroma.Web.WebsubTest do websub = insert(:websub_client_subscription, %{hub: hub, topic: topic}) poster = fn ^hub, {:form, _data}, _headers -> - {:ok, %{status_code: 400}} + {:ok, %{status: 400}} end {:error, websub} = Websub.request_subscription(websub, poster, 1000) @@ -209,6 +208,7 @@ defmodule Pleroma.Web.WebsubTest do insert(:websub_client_subscription, %{ valid_until: NaiveDateTime.add(now, 2 * day), topic: "http://example.org/still_good", + hub: "http://example.org/still_good", state: "accepted" }) @@ -216,6 +216,7 @@ defmodule Pleroma.Web.WebsubTest do insert(:websub_client_subscription, %{ valid_until: NaiveDateTime.add(now, day - 100), topic: "http://example.org/needs_refresh", + hub: "http://example.org/needs_refresh", state: "accepted" }) diff --git a/test/xml_builder_test.exs b/test/xml_builder_test.exs index 4be7bbd01..a7742f339 100644 --- a/test/xml_builder_test.exs +++ b/test/xml_builder_test.exs @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.XmlBuilderTest do use Pleroma.DataCase alias Pleroma.XmlBuilder |