From 6e4f52f8a2e510273149acbaf629521d1b4aec2e Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 16 Oct 2019 16:16:39 +0200
Subject: Introduce new ingestion pipeline structure, implement internal Likes
with it.
---
test/notification_test.exs | 8 +++---
test/object_test.exs | 3 +-
test/tasks/database_test.exs | 2 +-
test/user_test.exs | 4 +--
test/web/activity_pub/activity_validator_test.exs | 21 ++++++++++++++
test/web/activity_pub/side_effects_test.exs | 32 ++++++++++++++++++++++
test/web/activity_pub/transmogrifier_test.exs | 2 +-
test/web/activity_pub/views/object_view_test.exs | 2 +-
test/web/common_api/common_api_test.exs | 11 +++++---
.../controllers/notification_controller_test.exs | 2 +-
.../controllers/status_controller_test.exs | 16 +++++------
.../mastodon_api/views/notification_view_test.exs | 2 +-
test/web/ostatus/ostatus_controller_test.exs | 4 +--
.../controllers/account_controller_test.exs | 16 +++++------
test/web/push/impl_test.exs | 2 +-
test/web/streamer/streamer_test.exs | 6 ++--
16 files changed, 95 insertions(+), 38 deletions(-)
create mode 100644 test/web/activity_pub/activity_validator_test.exs
create mode 100644 test/web/activity_pub/side_effects_test.exs
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 54c0f9877..940913aa6 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -431,7 +431,7 @@ defmodule Pleroma.NotificationTest do
"status" => "hey @#{other_user.nickname}!"
})
- {:ok, activity_two, _} = CommonAPI.favorite(activity_one.id, third_user)
+ {:ok, activity_two} = CommonAPI.favorite(third_user, activity_one.id)
assert other_user not in Notification.get_notified_from_activity(activity_two)
end
@@ -461,7 +461,7 @@ defmodule Pleroma.NotificationTest do
assert Enum.empty?(Notification.for_user(user))
- {:ok, _, _} = CommonAPI.favorite(activity.id, other_user)
+ {:ok, _} = CommonAPI.favorite(other_user, activity.id)
assert length(Notification.for_user(user)) == 1
@@ -478,7 +478,7 @@ defmodule Pleroma.NotificationTest do
assert Enum.empty?(Notification.for_user(user))
- {:ok, _, _} = CommonAPI.favorite(activity.id, other_user)
+ {:ok, _} = CommonAPI.favorite(other_user, activity.id)
assert length(Notification.for_user(user)) == 1
@@ -533,7 +533,7 @@ defmodule Pleroma.NotificationTest do
assert Enum.empty?(Notification.for_user(user))
- {:error, _} = CommonAPI.favorite(activity.id, other_user)
+ {:error, _} = CommonAPI.favorite(other_user, activity.id)
assert Enum.empty?(Notification.for_user(user))
end
diff --git a/test/object_test.exs b/test/object_test.exs
index dd228c32f..353bc388d 100644
--- a/test/object_test.exs
+++ b/test/object_test.exs
@@ -182,7 +182,8 @@ defmodule Pleroma.ObjectTest do
user = insert(:user)
activity = Activity.get_create_by_object_ap_id(object.data["id"])
- {:ok, _activity, object} = CommonAPI.favorite(activity.id, user)
+ {:ok, activity} = CommonAPI.favorite(user, activity.id)
+ object = Object.get_by_ap_id(activity.data["object"])
assert object.data["like_count"] == 1
diff --git a/test/tasks/database_test.exs b/test/tasks/database_test.exs
index b63dcac00..c0a313863 100644
--- a/test/tasks/database_test.exs
+++ b/test/tasks/database_test.exs
@@ -102,7 +102,7 @@ defmodule Mix.Tasks.Pleroma.DatabaseTest do
{:ok, %{id: id, object: object}} = CommonAPI.post(user, %{"status" => "test"})
{:ok, %{object: object2}} = CommonAPI.post(user, %{"status" => "test test"})
- CommonAPI.favorite(id, user2)
+ CommonAPI.favorite(user2, id)
likes = %{
"first" =>
diff --git a/test/user_test.exs b/test/user_test.exs
index 019e7b400..49c1eb02a 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -1059,8 +1059,8 @@ defmodule Pleroma.UserTest do
object_two = insert(:note, user: follower)
activity_two = insert(:note_activity, user: follower, note: object_two)
- {:ok, like, _} = CommonAPI.favorite(activity_two.id, user)
- {:ok, like_two, _} = CommonAPI.favorite(activity.id, follower)
+ {:ok, like} = CommonAPI.favorite(user, activity_two.id)
+ {:ok, like_two} = CommonAPI.favorite(follower, activity.id)
{:ok, repeat, _} = CommonAPI.repeat(activity_two.id, user)
{:ok, job} = User.delete(user)
diff --git a/test/web/activity_pub/activity_validator_test.exs b/test/web/activity_pub/activity_validator_test.exs
new file mode 100644
index 000000000..cb0895a81
--- /dev/null
+++ b/test/web/activity_pub/activity_validator_test.exs
@@ -0,0 +1,21 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
+ use Pleroma.DataCase
+
+ import Pleroma.Factory
+
+ describe "likes" do
+ test "it is well formed" do
+ _required_fields = [
+ "id",
+ "actor",
+ "object"
+ ]
+
+ _user = insert(:user)
+ end
+ end
+end
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
new file mode 100644
index 000000000..e505ab4dd
--- /dev/null
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -0,0 +1,32 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
+ use Pleroma.DataCase
+ alias Pleroma.Object
+ alias Pleroma.Web.CommonAPI
+ alias Pleroma.Web.ActivityPub.Builder
+ alias Pleroma.Web.ActivityPub.ActivityPub
+ alias Pleroma.Web.ActivityPub.SideEffects
+
+ import Pleroma.Factory
+ describe "like objects" do
+ setup do
+ user = insert(:user)
+ {:ok, post} = CommonAPI.post(user, %{"status" => "hey"})
+
+ {:ok, like_data, _meta} = Builder.like(user, post.object)
+ {:ok, like, _meta} = ActivityPub.persist(like_data, [])
+
+ %{like: like, user: user}
+ end
+
+ test "add the like to the original object", %{like: like, user: user} do
+ {:ok, like, _} = SideEffects.handle(like)
+ object = Object.get_by_ap_id(like.data["object"])
+ assert object.data["like_count"] == 1
+ assert user.ap_id in object.data["likes"]
+ end
+ end
+end
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 6c35a6f4d..28edc5508 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -1187,7 +1187,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
user = insert(:user)
- {:ok, activity, _} = CommonAPI.favorite(referent_activity.id, user)
+ {:ok, activity} = CommonAPI.favorite(user, referent_activity.id)
{:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
assert modified["object"] == "http://gs.example.org:4040/index.php/notice/29"
diff --git a/test/web/activity_pub/views/object_view_test.exs b/test/web/activity_pub/views/object_view_test.exs
index 13447dc29..998247c5c 100644
--- a/test/web/activity_pub/views/object_view_test.exs
+++ b/test/web/activity_pub/views/object_view_test.exs
@@ -41,7 +41,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectViewTest do
object = Object.normalize(note)
user = insert(:user)
- {:ok, like_activity, _} = CommonAPI.favorite(note.id, user)
+ {:ok, like_activity} = CommonAPI.favorite(user, note.id)
result = ObjectView.render("object.json", %{object: like_activity})
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index 83df44c36..d46a361c5 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -251,9 +251,12 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
+ {:ok, post_activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
- {:ok, %Activity{}, _} = CommonAPI.favorite(activity.id, user)
+ {:ok, %Activity{data: data}} = CommonAPI.favorite(user, post_activity.id)
+ assert data["type"] == "Like"
+ assert data["actor"] == user.ap_id
+ assert data["object"] == post_activity.data["object"]
end
test "retweeting a status twice returns an error" do
@@ -270,8 +273,8 @@ defmodule Pleroma.Web.CommonAPITest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
- {:ok, %Activity{}, _object} = CommonAPI.favorite(activity.id, user)
- {:error, _} = CommonAPI.favorite(activity.id, user)
+ {:ok, %Activity{}} = CommonAPI.favorite(user, activity.id)
+ {:error, _} = CommonAPI.favorite(user, activity.id)
end
end
diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs
index e4137e92c..6eadccb8e 100644
--- a/test/web/mastodon_api/controllers/notification_controller_test.exs
+++ b/test/web/mastodon_api/controllers/notification_controller_test.exs
@@ -143,7 +143,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
{:ok, mention_activity} = CommonAPI.post(other_user, %{"status" => "hey @#{user.nickname}"})
{:ok, create_activity} = CommonAPI.post(user, %{"status" => "hey"})
- {:ok, favorite_activity, _} = CommonAPI.favorite(create_activity.id, other_user)
+ {:ok, favorite_activity} = CommonAPI.favorite(other_user, create_activity.id)
{:ok, reblog_activity, _} = CommonAPI.repeat(create_activity.id, other_user)
{:ok, _, _, follow_activity} = CommonAPI.follow(other_user, user)
diff --git a/test/web/mastodon_api/controllers/status_controller_test.exs b/test/web/mastodon_api/controllers/status_controller_test.exs
index 2de2725e0..1414d9fed 100644
--- a/test/web/mastodon_api/controllers/status_controller_test.exs
+++ b/test/web/mastodon_api/controllers/status_controller_test.exs
@@ -589,7 +589,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
user1 = insert(:user)
user2 = insert(:user)
user3 = insert(:user)
- CommonAPI.favorite(activity.id, user2)
+ {:ok, _} = CommonAPI.favorite(user2, activity.id)
{:ok, _bookmark} = Pleroma.Bookmark.create(user2.id, activity.id)
{:ok, reblog_activity1, _object} = CommonAPI.repeat(activity.id, user1)
{:ok, _, _object} = CommonAPI.repeat(activity.id, user2)
@@ -695,7 +695,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
activity = insert(:note_activity)
user = insert(:user)
- {:ok, _, _} = CommonAPI.favorite(activity.id, user)
+ {:ok, _} = CommonAPI.favorite(user, activity.id)
conn =
conn
@@ -1047,7 +1047,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "returns users who have favorited the status", %{conn: conn, activity: activity} do
other_user = insert(:user)
- {:ok, _, _} = CommonAPI.favorite(activity.id, other_user)
+ {:ok, _} = CommonAPI.favorite(other_user, activity.id)
response =
conn
@@ -1078,7 +1078,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
other_user = insert(:user)
{:ok, user} = User.block(user, other_user)
- {:ok, _, _} = CommonAPI.favorite(activity.id, other_user)
+ {:ok, _} = CommonAPI.favorite(other_user, activity.id)
response =
conn
@@ -1091,7 +1091,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "does not fail on an unauthenticated request", %{conn: conn, activity: activity} do
other_user = insert(:user)
- {:ok, _, _} = CommonAPI.favorite(activity.id, other_user)
+ {:ok, _} = CommonAPI.favorite(other_user, activity.id)
response =
conn
@@ -1112,7 +1112,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
"visibility" => "direct"
})
- {:ok, _, _} = CommonAPI.favorite(activity.id, other_user)
+ {:ok, _} = CommonAPI.favorite(other_user, activity.id)
conn
|> assign(:user, nil)
@@ -1269,7 +1269,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
{:ok, _} = CommonAPI.post(other_user, %{"status" => "bla"})
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "traps are happy"})
- {:ok, _, _} = CommonAPI.favorite(activity.id, user)
+ {:ok, _} = CommonAPI.favorite(user, activity.id)
first_conn =
conn
@@ -1289,7 +1289,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
"Trees Are Never Sad Look At Them Every Once In Awhile They're Quite Beautiful."
})
- {:ok, _, _} = CommonAPI.favorite(second_activity.id, user)
+ {:ok, _} = CommonAPI.favorite(user, second_activity.id)
last_like = status["id"]
diff --git a/test/web/mastodon_api/views/notification_view_test.exs b/test/web/mastodon_api/views/notification_view_test.exs
index c9043a69a..d06809268 100644
--- a/test/web/mastodon_api/views/notification_view_test.exs
+++ b/test/web/mastodon_api/views/notification_view_test.exs
@@ -42,7 +42,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
user = insert(:user)
another_user = insert(:user)
{:ok, create_activity} = CommonAPI.post(user, %{"status" => "hey"})
- {:ok, favorite_activity, _object} = CommonAPI.favorite(create_activity.id, another_user)
+ {:ok, favorite_activity} = CommonAPI.favorite(another_user, create_activity.id)
{:ok, [notification]} = Notification.create_notifications(favorite_activity)
create_activity = Activity.get_by_id(create_activity.id)
diff --git a/test/web/ostatus/ostatus_controller_test.exs b/test/web/ostatus/ostatus_controller_test.exs
index b1af918d8..7aee16e2c 100644
--- a/test/web/ostatus/ostatus_controller_test.exs
+++ b/test/web/ostatus/ostatus_controller_test.exs
@@ -271,7 +271,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do
user = insert(:user)
- {:ok, like_activity, _} = CommonAPI.favorite(note_activity.id, user)
+ {:ok, like_activity} = CommonAPI.favorite(user, note_activity.id)
url = "/notice/#{like_activity.id}"
assert like_activity.data["type"] == "Like"
@@ -298,7 +298,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do
user = insert(:user)
- {:ok, like_activity, _} = CommonAPI.favorite(note_activity.id, user)
+ {:ok, like_activity} = CommonAPI.favorite(user, note_activity.id)
assert like_activity.data["type"] == "Like"
diff --git a/test/web/pleroma_api/controllers/account_controller_test.exs b/test/web/pleroma_api/controllers/account_controller_test.exs
index 3b4665afd..6a6135d02 100644
--- a/test/web/pleroma_api/controllers/account_controller_test.exs
+++ b/test/web/pleroma_api/controllers/account_controller_test.exs
@@ -165,7 +165,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
user: user
} do
[activity | _] = insert_pair(:note_activity)
- CommonAPI.favorite(activity.id, user)
+ CommonAPI.favorite(user, activity.id)
response =
conn
@@ -184,7 +184,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
user: user
} do
activity = insert(:note_activity)
- CommonAPI.favorite(activity.id, user)
+ CommonAPI.favorite(user, activity.id)
response =
conn
@@ -205,7 +205,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
"visibility" => "direct"
})
- CommonAPI.favorite(direct.id, user)
+ CommonAPI.favorite(user, direct.id)
response =
conn
@@ -236,7 +236,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
"visibility" => "direct"
})
- CommonAPI.favorite(direct.id, user)
+ CommonAPI.favorite(user, direct.id)
response =
conn
@@ -255,7 +255,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
activities = insert_list(10, :note_activity)
Enum.each(activities, fn activity ->
- CommonAPI.favorite(activity.id, user)
+ CommonAPI.favorite(user, activity.id)
end)
third_activity = Enum.at(activities, 2)
@@ -283,7 +283,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
7
|> insert_list(:note_activity)
|> Enum.each(fn activity ->
- CommonAPI.favorite(activity.id, user)
+ CommonAPI.favorite(user, activity.id)
end)
response =
@@ -321,7 +321,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
} do
user = insert(:user, %{info: %{hide_favorites: true}})
activity = insert(:note_activity)
- CommonAPI.favorite(activity.id, user)
+ CommonAPI.favorite(user, activity.id)
conn =
conn
@@ -334,7 +334,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
test "hides favorites for new users by default", %{conn: conn, current_user: current_user} do
user = insert(:user)
activity = insert(:note_activity)
- CommonAPI.favorite(activity.id, user)
+ CommonAPI.favorite(user, activity.id)
conn =
conn
diff --git a/test/web/push/impl_test.exs b/test/web/push/impl_test.exs
index 2f6ce4bd2..36c69c7c9 100644
--- a/test/web/push/impl_test.exs
+++ b/test/web/push/impl_test.exs
@@ -152,7 +152,7 @@ defmodule Pleroma.Web.Push.ImplTest do
"Lorem ipsum dolor sit amet, consectetur :firefox: adipiscing elit. Fusce sagittis finibus turpis."
})
- {:ok, activity, _} = CommonAPI.favorite(activity.id, user)
+ {:ok, activity} = CommonAPI.favorite(user, activity.id)
object = Object.normalize(activity)
assert Impl.format_body(%{activity: activity}, user, object) == "@Bob has favorited your post"
diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs
index d33eb1e42..b363935a2 100644
--- a/test/web/streamer/streamer_test.exs
+++ b/test/web/streamer/streamer_test.exs
@@ -68,7 +68,7 @@ defmodule Pleroma.Web.StreamerTest do
)
{:ok, activity} = CommonAPI.post(user, %{"status" => ":("})
- {:ok, notif, _} = CommonAPI.favorite(activity.id, blocked)
+ {:ok, notif} = CommonAPI.favorite(blocked, activity.id)
Streamer.stream("user:notification", notif)
Task.await(task)
@@ -87,7 +87,7 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
{:ok, activity} = CommonAPI.add_mute(user, activity)
- {:ok, notif, _} = CommonAPI.favorite(activity.id, user2)
+ {:ok, notif} = CommonAPI.favorite(user2, activity.id)
Streamer.stream("user:notification", notif)
Task.await(task)
end
@@ -105,7 +105,7 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, user} = User.block_domain(user, "hecking-lewd-place.com")
{:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
- {:ok, notif, _} = CommonAPI.favorite(activity.id, user2)
+ {:ok, notif} = CommonAPI.favorite(user2, activity.id)
Streamer.stream("user:notification", notif)
Task.await(task)
--
cgit v1.2.3
From 66452f518faa1f079f02006943b0c2cdc830b47f Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 17 Oct 2019 18:36:52 +0200
Subject: ObjectValidator: Rewrite LikeValidator with Ecto.
---
test/web/activity_pub/activity_validator_test.exs | 21 ------
test/web/activity_pub/object_validator_test.exs | 80 +++++++++++++++++++++++
test/web/activity_pub/side_effects_test.exs | 1 +
3 files changed, 81 insertions(+), 21 deletions(-)
delete mode 100644 test/web/activity_pub/activity_validator_test.exs
create mode 100644 test/web/activity_pub/object_validator_test.exs
(limited to 'test')
diff --git a/test/web/activity_pub/activity_validator_test.exs b/test/web/activity_pub/activity_validator_test.exs
deleted file mode 100644
index cb0895a81..000000000
--- a/test/web/activity_pub/activity_validator_test.exs
+++ /dev/null
@@ -1,21 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
- use Pleroma.DataCase
-
- import Pleroma.Factory
-
- describe "likes" do
- test "it is well formed" do
- _required_fields = [
- "id",
- "actor",
- "object"
- ]
-
- _user = insert(:user)
- end
- end
-end
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
new file mode 100644
index 000000000..374a7c0df
--- /dev/null
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -0,0 +1,80 @@
+defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
+ use Pleroma.DataCase
+
+ alias Pleroma.Web.CommonAPI
+ alias Pleroma.Web.ActivityPub.ObjectValidator
+ alias Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator
+ alias Pleroma.Web.ActivityPub.Utils
+ import Pleroma.Factory
+
+ describe "likes" do
+ setup do
+ user = insert(:user)
+ {:ok, post_activity} = CommonAPI.post(user, %{"status" => "uguu"})
+
+ valid_like = %{
+ "type" => "Like",
+ "id" => Utils.generate_activity_id(),
+ "object" => post_activity.data["object"],
+ "actor" => user.ap_id,
+ "context" => "a context"
+ }
+
+ %{valid_like: valid_like, user: user, post_activity: post_activity}
+ end
+
+ test "returns ok when called in the ObjectValidator", %{valid_like: valid_like} do
+ {:ok, object, _meta} = ObjectValidator.validate(valid_like, [])
+
+ assert "id" in Map.keys(object)
+ end
+
+ test "is valid for a valid object", %{valid_like: valid_like} do
+ assert LikeValidator.cast_and_validate(valid_like).valid?
+ end
+
+ test "it errors when the actor is missing or not known", %{valid_like: valid_like} do
+ without_actor = Map.delete(valid_like, "actor")
+
+ refute LikeValidator.cast_and_validate(without_actor).valid?
+
+ with_invalid_actor = Map.put(valid_like, "actor", "invalidactor")
+
+ refute LikeValidator.cast_and_validate(with_invalid_actor).valid?
+ end
+
+ test "it errors when the object is missing or not known", %{valid_like: valid_like} do
+ without_object = Map.delete(valid_like, "object")
+
+ refute LikeValidator.cast_and_validate(without_object).valid?
+
+ with_invalid_object = Map.put(valid_like, "object", "invalidobject")
+
+ refute LikeValidator.cast_and_validate(with_invalid_object).valid?
+ end
+
+ test "it errors when the actor has already like the object", %{
+ valid_like: valid_like,
+ user: user,
+ post_activity: post_activity
+ } do
+ _like = CommonAPI.favorite(user, post_activity.id)
+
+ refute LikeValidator.cast_and_validate(valid_like).valid?
+ end
+
+ test "it works when actor or object are wrapped in maps", %{valid_like: valid_like} do
+ wrapped_like =
+ valid_like
+ |> Map.put("actor", %{"id" => valid_like["actor"]})
+ |> Map.put("object", %{"id" => valid_like["object"]})
+
+ validated = LikeValidator.cast_and_validate(wrapped_like)
+
+ assert validated.valid?
+
+ assert {:actor, valid_like["actor"]} in validated.changes
+ assert {:object, valid_like["object"]} in validated.changes
+ end
+ end
+end
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index e505ab4dd..9d99e05a0 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -11,6 +11,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
alias Pleroma.Web.ActivityPub.SideEffects
import Pleroma.Factory
+
describe "like objects" do
setup do
user = insert(:user)
--
cgit v1.2.3
From 203d61b95012fd2cb8a8618f6f51a3748c940cc1 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 17 Oct 2019 19:35:31 +0200
Subject: Transmogrifier: Make proper use of the LikeValidator.
---
test/web/activity_pub/object_validator_test.exs | 2 ++
test/web/activity_pub/transmogrifier_test.exs | 4 +++-
2 files changed, 5 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 374a7c0df..2292db6d7 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -13,6 +13,8 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
{:ok, post_activity} = CommonAPI.post(user, %{"status" => "uguu"})
valid_like = %{
+ "to" => [user.ap_id],
+ "cc" => [],
"type" => "Like",
"id" => Utils.generate_activity_id(),
"object" => post_activity.data["object"],
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 28edc5508..e5d4dcd64 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -333,7 +333,9 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
|> Poison.decode!()
|> Map.put("object", activity.data["object"])
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+ {:ok, %Activity{data: data, local: false} = activity} = Transmogrifier.handle_incoming(data)
+
+ refute Enum.empty?(activity.recipients)
assert data["actor"] == "http://mastodon.example.org/users/admin"
assert data["type"] == "Like"
--
cgit v1.2.3
From 4ec299ea9c1cf45c42e98d7b33f33a72f5e7a9c0 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 18 Oct 2019 12:11:25 +0200
Subject: CommonAPI tests: Capture logs.
---
test/web/common_api/common_api_test.exs | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index d46a361c5..63d7ea79f 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -13,6 +13,7 @@ defmodule Pleroma.Web.CommonAPITest do
alias Pleroma.Web.CommonAPI
import Pleroma.Factory
+ import ExUnit.CaptureLog
require Pleroma.Constants
@@ -274,7 +275,9 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
{:ok, %Activity{}} = CommonAPI.favorite(user, activity.id)
- {:error, _} = CommonAPI.favorite(user, activity.id)
+ assert capture_log(fn ->
+ assert {:error, _} = CommonAPI.favorite(user, activity.id)
+ end) =~ "[error]"
end
end
--
cgit v1.2.3
From 15bbc34c079018f1c988fe9d445bec50e85bbeaf Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 18 Oct 2019 12:44:53 +0200
Subject: Tests: Capture log.
---
test/notification_test.exs | 6 +++++-
test/web/common_api/common_api_test.exs | 5 +++--
2 files changed, 8 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 940913aa6..480c9415b 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -14,6 +14,8 @@ defmodule Pleroma.NotificationTest do
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.Streamer
+ import ExUnit.CaptureLog
+
describe "create_notifications" do
test "notifies someone when they are directly addressed" do
user = insert(:user)
@@ -533,7 +535,9 @@ defmodule Pleroma.NotificationTest do
assert Enum.empty?(Notification.for_user(user))
- {:error, _} = CommonAPI.favorite(other_user, activity.id)
+ assert capture_log(fn ->
+ {:error, _} = CommonAPI.favorite(other_user, activity.id)
+ end) =~ "[error]"
assert Enum.empty?(Notification.for_user(user))
end
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index 63d7ea79f..8195b1910 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -275,9 +275,10 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
{:ok, %Activity{}} = CommonAPI.favorite(user, activity.id)
+
assert capture_log(fn ->
- assert {:error, _} = CommonAPI.favorite(user, activity.id)
- end) =~ "[error]"
+ assert {:error, _} = CommonAPI.favorite(user, activity.id)
+ end) =~ "[error]"
end
end
--
cgit v1.2.3
From f1381d68e740daf4c341359a2b5837bc2bd3a051 Mon Sep 17 00:00:00 2001
From: lain
Date: Sat, 19 Oct 2019 14:46:14 +0200
Subject: StatusControllerTest: Capture log.
---
.../web/mastodon_api/controllers/status_controller_test.exs | 13 ++++++++-----
1 file changed, 8 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/status_controller_test.exs b/test/web/mastodon_api/controllers/status_controller_test.exs
index 1414d9fed..2bbd8a151 100644
--- a/test/web/mastodon_api/controllers/status_controller_test.exs
+++ b/test/web/mastodon_api/controllers/status_controller_test.exs
@@ -17,6 +17,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
alias Pleroma.Web.CommonAPI
import Pleroma.Factory
+ import ExUnit.CaptureLog
describe "posting statuses" do
setup do
@@ -681,12 +682,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "returns 400 error for a wrong id", %{conn: conn} do
user = insert(:user)
- conn =
- conn
- |> assign(:user, user)
- |> post("/api/v1/statuses/1/favourite")
+ assert capture_log(fn ->
+ conn =
+ conn
+ |> assign(:user, user)
+ |> post("/api/v1/statuses/1/favourite")
- assert json_response(conn, 400) == %{"error" => "Could not favorite"}
+ assert json_response(conn, 400) == %{"error" => "Could not favorite"}
+ end) =~ "[error]"
end
end
--
cgit v1.2.3
From d4270397dcb2aebde8ed14fd89998ab57aaae545 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Tue, 22 Oct 2019 13:42:59 +0300
Subject: Marker: added unread_count field
---
test/web/mastodon_api/controllers/marker_controller_test.exs | 7 +++++--
test/web/mastodon_api/views/marker_view_test.exs | 4 +++-
2 files changed, 8 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/marker_controller_test.exs b/test/web/mastodon_api/controllers/marker_controller_test.exs
index 1fcad873d..5e7b4001f 100644
--- a/test/web/mastodon_api/controllers/marker_controller_test.exs
+++ b/test/web/mastodon_api/controllers/marker_controller_test.exs
@@ -15,7 +15,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
{:ok, %{"notifications" => marker}} =
Pleroma.Marker.upsert(
user,
- %{"notifications" => %{"last_read_id" => "69420"}}
+ %{"notifications" => %{"last_read_id" => "69420", "unread_count" => 7}}
)
response =
@@ -28,6 +28,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
assert response == %{
"notifications" => %{
"last_read_id" => "69420",
+ "unread_count" => 7,
"updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
"version" => 0
}
@@ -70,7 +71,8 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"notifications" => %{
"last_read_id" => "69420",
"updated_at" => _,
- "version" => 0
+ "version" => 0,
+ "unread_count" => 0
}
} = response
end
@@ -98,6 +100,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
assert response == %{
"notifications" => %{
"last_read_id" => "69888",
+ "unread_count" => 0,
"updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
"version" => 0
}
diff --git a/test/web/mastodon_api/views/marker_view_test.exs b/test/web/mastodon_api/views/marker_view_test.exs
index 8a5c89d56..3ce794617 100644
--- a/test/web/mastodon_api/views/marker_view_test.exs
+++ b/test/web/mastodon_api/views/marker_view_test.exs
@@ -8,17 +8,19 @@ defmodule Pleroma.Web.MastodonAPI.MarkerViewTest do
import Pleroma.Factory
test "returns markers" do
- marker1 = insert(:marker, timeline: "notifications", last_read_id: "17")
+ marker1 = insert(:marker, timeline: "notifications", last_read_id: "17", unread_count: 5)
marker2 = insert(:marker, timeline: "home", last_read_id: "42")
assert MarkerView.render("markers.json", %{markers: [marker1, marker2]}) == %{
"home" => %{
last_read_id: "42",
+ unread_count: 0,
updated_at: NaiveDateTime.to_iso8601(marker2.updated_at),
version: 0
},
"notifications" => %{
last_read_id: "17",
+ unread_count: 5,
updated_at: NaiveDateTime.to_iso8601(marker1.updated_at),
version: 0
}
--
cgit v1.2.3
From 9a4afbd2a0486238bfaf4047d91376d32635514a Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Tue, 22 Oct 2019 16:13:22 +0300
Subject: added update unread_count for notifications
---
test/notification_test.exs | 7 +++++++
1 file changed, 7 insertions(+)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 96316f8dd..558ac358c 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -310,6 +310,13 @@ defmodule Pleroma.NotificationTest do
assert n1.seen == true
assert n2.seen == true
assert n3.seen == false
+
+ assert %Pleroma.Marker{unread_count: 1} =
+ Pleroma.Repo.get_by(
+ Pleroma.Marker,
+ user_id: other_user.id,
+ timeline: "notifications"
+ )
end
end
--
cgit v1.2.3
From 97d5c79aa07bfe836cd676424ce1b5a298c72b60 Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 23 Oct 2019 11:52:27 +0200
Subject: Add Pipeline module, test for federation.
---
test/web/activity_pub/pipeline_test.exs | 87 +++++++++++++++++++++++++++++++++
1 file changed, 87 insertions(+)
create mode 100644 test/web/activity_pub/pipeline_test.exs
(limited to 'test')
diff --git a/test/web/activity_pub/pipeline_test.exs b/test/web/activity_pub/pipeline_test.exs
new file mode 100644
index 000000000..318d306af
--- /dev/null
+++ b/test/web/activity_pub/pipeline_test.exs
@@ -0,0 +1,87 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.PipelineTest do
+ use Pleroma.DataCase
+
+ import Mock
+ import Pleroma.Factory
+
+ describe "common_pipeline/2" do
+ test "it goes through validation, filtering, persisting, side effects and federation for local activities" do
+ activity = insert(:note_activity)
+ meta = [local: true]
+
+ with_mocks([
+ {Pleroma.Web.ActivityPub.ObjectValidator, [], [validate: fn o, m -> {:ok, o, m} end]},
+ {
+ Pleroma.Web.ActivityPub.MRF,
+ [],
+ [filter: fn o -> {:ok, o} end]
+ },
+ {
+ Pleroma.Web.ActivityPub.ActivityPub,
+ [],
+ [persist: fn o, m -> {:ok, o, m} end]
+ },
+ {
+ Pleroma.Web.ActivityPub.SideEffects,
+ [],
+ [handle: fn o, m -> {:ok, o, m} end]
+ },
+ {
+ Pleroma.Web.Federator,
+ [],
+ [publish: fn _o -> :ok end]
+ }
+ ]) do
+ assert {:ok, ^activity, ^meta} =
+ Pleroma.Web.ActivityPub.Pipeline.common_pipeline(activity, meta)
+
+ assert_called(Pleroma.Web.ActivityPub.ObjectValidator.validate(activity, meta))
+ assert_called(Pleroma.Web.ActivityPub.MRF.filter(activity))
+ assert_called(Pleroma.Web.ActivityPub.ActivityPub.persist(activity, meta))
+ assert_called(Pleroma.Web.ActivityPub.SideEffects.handle(activity, meta))
+ assert_called(Pleroma.Web.Federator.publish(activity))
+ end
+ end
+
+ test "it goes through validation, filtering, persisting, side effects without federation for remote activities" do
+ activity = insert(:note_activity)
+ meta = [local: false]
+
+ with_mocks([
+ {Pleroma.Web.ActivityPub.ObjectValidator, [], [validate: fn o, m -> {:ok, o, m} end]},
+ {
+ Pleroma.Web.ActivityPub.MRF,
+ [],
+ [filter: fn o -> {:ok, o} end]
+ },
+ {
+ Pleroma.Web.ActivityPub.ActivityPub,
+ [],
+ [persist: fn o, m -> {:ok, o, m} end]
+ },
+ {
+ Pleroma.Web.ActivityPub.SideEffects,
+ [],
+ [handle: fn o, m -> {:ok, o, m} end]
+ },
+ {
+ Pleroma.Web.Federator,
+ [],
+ []
+ }
+ ]) do
+ assert {:ok, ^activity, ^meta} =
+ Pleroma.Web.ActivityPub.Pipeline.common_pipeline(activity, meta)
+
+ assert_called(Pleroma.Web.ActivityPub.ObjectValidator.validate(activity, meta))
+ assert_called(Pleroma.Web.ActivityPub.MRF.filter(activity))
+ assert_called(Pleroma.Web.ActivityPub.ActivityPub.persist(activity, meta))
+ assert_called(Pleroma.Web.ActivityPub.SideEffects.handle(activity, meta))
+ end
+ end
+ end
+end
--
cgit v1.2.3
From 1adafa096653c4538e4162a2dffba982ee6c6d8e Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 23 Oct 2019 12:18:05 +0200
Subject: Credo fixes.
---
test/web/activity_pub/object_validator_test.exs | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 2292db6d7..3c5c3696e 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -1,10 +1,11 @@
defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
use Pleroma.DataCase
- alias Pleroma.Web.CommonAPI
alias Pleroma.Web.ActivityPub.ObjectValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator
alias Pleroma.Web.ActivityPub.Utils
+ alias Pleroma.Web.CommonAPI
+
import Pleroma.Factory
describe "likes" do
--
cgit v1.2.3
From 25077812bfc8a7a94c3fa953b2924003296470c2 Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 23 Oct 2019 12:25:20 +0200
Subject: SideEffectsTest: Fix test.
---
test/web/activity_pub/side_effects_test.exs | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index 9d99e05a0..b34e45a7f 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -4,11 +4,12 @@
defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
use Pleroma.DataCase
+
alias Pleroma.Object
- alias Pleroma.Web.CommonAPI
- alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.ActivityPub
+ alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.SideEffects
+ alias Pleroma.Web.CommonAPI
import Pleroma.Factory
@@ -18,7 +19,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
{:ok, post} = CommonAPI.post(user, %{"status" => "hey"})
{:ok, like_data, _meta} = Builder.like(user, post.object)
- {:ok, like, _meta} = ActivityPub.persist(like_data, [])
+ {:ok, like, _meta} = ActivityPub.persist(like_data, [local: true])
%{like: like, user: user}
end
--
cgit v1.2.3
From d3fb9e02cc0ce7dc462e587e639e117aaef5fbc5 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Wed, 23 Oct 2019 22:48:04 +0300
Subject: add tests
---
test/marker_test.exs | 15 +++++++++++++++
test/notification_test.exs | 3 +++
2 files changed, 18 insertions(+)
(limited to 'test')
diff --git a/test/marker_test.exs b/test/marker_test.exs
index 04bd67fe6..1900ed08b 100644
--- a/test/marker_test.exs
+++ b/test/marker_test.exs
@@ -8,6 +8,21 @@ defmodule Pleroma.MarkerTest do
import Pleroma.Factory
+ describe "multi_set_unread_count/3" do
+ test "returns multi" do
+ user = insert(:user)
+
+ assert %Ecto.Multi{
+ operations: [marker: {:run, _}, counters: {:run, _}]
+ } =
+ Marker.multi_set_unread_count(
+ Ecto.Multi.new(),
+ user,
+ "notifications"
+ )
+ end
+ end
+
describe "get_markers/2" do
test "returns user markers" do
user = insert(:user)
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 558ac358c..1e8a9ca98 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -31,6 +31,9 @@ defmodule Pleroma.NotificationTest do
assert notified_ids == [other_user.id, third_user.id]
assert notification.activity_id == activity.id
assert other_notification.activity_id == activity.id
+
+ assert [%Pleroma.Marker{unread_count: 2}] =
+ Pleroma.Marker.get_markers(other_user, ["notifications"])
end
test "it creates a notification for subscribed users" do
--
cgit v1.2.3
From 922e3d082c38ccd108710e21d4bda8e65b551f9c Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Thu, 24 Oct 2019 09:50:41 +0300
Subject: add test
---
test/marker_test.exs | 6 ++++++
1 file changed, 6 insertions(+)
(limited to 'test')
diff --git a/test/marker_test.exs b/test/marker_test.exs
index 1900ed08b..5d03db48e 100644
--- a/test/marker_test.exs
+++ b/test/marker_test.exs
@@ -21,6 +21,12 @@ defmodule Pleroma.MarkerTest do
"notifications"
)
end
+
+ test "return empty multi" do
+ user = insert(:user)
+ multi = Ecto.Multi.new()
+ assert Marker.multi_set_unread_count(multi, user, "home") == multi
+ end
end
describe "get_markers/2" do
--
cgit v1.2.3
From 209319c8d289564653f73cbf15fb6449d91cf3ca Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Wed, 30 Oct 2019 23:49:05 +0300
Subject: update marker api
---
.../controllers/marker_controller_test.exs | 20 ++++++++++----------
test/web/mastodon_api/views/marker_view_test.exs | 8 ++++----
2 files changed, 14 insertions(+), 14 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/marker_controller_test.exs b/test/web/mastodon_api/controllers/marker_controller_test.exs
index 5e7b4001f..e0aacccb4 100644
--- a/test/web/mastodon_api/controllers/marker_controller_test.exs
+++ b/test/web/mastodon_api/controllers/marker_controller_test.exs
@@ -26,13 +26,13 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
|> json_response(200)
assert response == %{
- "notifications" => %{
- "last_read_id" => "69420",
- "unread_count" => 7,
- "updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
- "version" => 0
- }
- }
+ "notifications" => %{
+ "last_read_id" => "69420",
+ "updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
+ "version" => 0,
+ "pleroma" => %{ "unread_count" => 7 }
+ }
+ }
end
test "gets markers with missed scopes", %{conn: conn} do
@@ -72,7 +72,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"last_read_id" => "69420",
"updated_at" => _,
"version" => 0,
- "unread_count" => 0
+ "pleroma" => %{ "unread_count" => 0 }
}
} = response
end
@@ -100,9 +100,9 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
assert response == %{
"notifications" => %{
"last_read_id" => "69888",
- "unread_count" => 0,
"updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
- "version" => 0
+ "version" => 0,
+ "pleroma" => %{ "unread_count" => 0 }
}
}
end
diff --git a/test/web/mastodon_api/views/marker_view_test.exs b/test/web/mastodon_api/views/marker_view_test.exs
index 3ce794617..f172e5023 100644
--- a/test/web/mastodon_api/views/marker_view_test.exs
+++ b/test/web/mastodon_api/views/marker_view_test.exs
@@ -14,15 +14,15 @@ defmodule Pleroma.Web.MastodonAPI.MarkerViewTest do
assert MarkerView.render("markers.json", %{markers: [marker1, marker2]}) == %{
"home" => %{
last_read_id: "42",
- unread_count: 0,
updated_at: NaiveDateTime.to_iso8601(marker2.updated_at),
- version: 0
+ version: 0,
+ pleroma: %{unread_count: 0}
},
"notifications" => %{
last_read_id: "17",
- unread_count: 5,
updated_at: NaiveDateTime.to_iso8601(marker1.updated_at),
- version: 0
+ version: 0,
+ pleroma: %{unread_count: 5}
}
}
end
--
cgit v1.2.3
From 1b3a942a84b8b612e07e3bf34801137741926911 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Thu, 31 Oct 2019 17:36:59 +0300
Subject: fix format
---
.../controllers/marker_controller_test.exs | 18 +++++++++---------
1 file changed, 9 insertions(+), 9 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/marker_controller_test.exs b/test/web/mastodon_api/controllers/marker_controller_test.exs
index e0aacccb4..8bcfcb7e1 100644
--- a/test/web/mastodon_api/controllers/marker_controller_test.exs
+++ b/test/web/mastodon_api/controllers/marker_controller_test.exs
@@ -26,13 +26,13 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
|> json_response(200)
assert response == %{
- "notifications" => %{
- "last_read_id" => "69420",
- "updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
- "version" => 0,
- "pleroma" => %{ "unread_count" => 7 }
- }
- }
+ "notifications" => %{
+ "last_read_id" => "69420",
+ "updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
+ "version" => 0,
+ "pleroma" => %{"unread_count" => 7}
+ }
+ }
end
test "gets markers with missed scopes", %{conn: conn} do
@@ -72,7 +72,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"last_read_id" => "69420",
"updated_at" => _,
"version" => 0,
- "pleroma" => %{ "unread_count" => 0 }
+ "pleroma" => %{"unread_count" => 0}
}
} = response
end
@@ -102,7 +102,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"last_read_id" => "69888",
"updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
"version" => 0,
- "pleroma" => %{ "unread_count" => 0 }
+ "pleroma" => %{"unread_count" => 0}
}
}
end
--
cgit v1.2.3
From 3d1b445cbf001f76af614441c241dcc299e76af7 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 Nov 2019 15:02:09 +0100
Subject: Object Validators: Extract common validations.
---
test/web/activity_pub/side_effects_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index b34e45a7f..ef91954ae 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -19,7 +19,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
{:ok, post} = CommonAPI.post(user, %{"status" => "hey"})
{:ok, like_data, _meta} = Builder.like(user, post.object)
- {:ok, like, _meta} = ActivityPub.persist(like_data, [local: true])
+ {:ok, like, _meta} = ActivityPub.persist(like_data, local: true)
%{like: like, user: user}
end
--
cgit v1.2.3
From faced6236b9e2ce9675cf743068f16098b744562 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 Nov 2019 15:02:31 +0100
Subject: NoteValidator: Add very basic validator for Note objects.
---
.../object_validators/note_validator_test.exs | 35 ++++++++++++++++++++++
1 file changed, 35 insertions(+)
create mode 100644 test/web/activity_pub/object_validators/note_validator_test.exs
(limited to 'test')
diff --git a/test/web/activity_pub/object_validators/note_validator_test.exs b/test/web/activity_pub/object_validators/note_validator_test.exs
new file mode 100644
index 000000000..2bcd75e25
--- /dev/null
+++ b/test/web/activity_pub/object_validators/note_validator_test.exs
@@ -0,0 +1,35 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.ObjectValidators.NoteValidatorTest do
+ use Pleroma.DataCase
+
+ alias Pleroma.Web.ActivityPub.ObjectValidators.NoteValidator
+ alias Pleroma.Web.ActivityPub.Utils
+
+ import Pleroma.Factory
+
+ describe "Notes" do
+ setup do
+ user = insert(:user)
+
+ note = %{
+ "id" => Utils.generate_activity_id(),
+ "type" => "Note",
+ "actor" => user.ap_id,
+ "to" => [user.follower_address],
+ "cc" => [],
+ "content" => "Hellow this is content.",
+ "context" => "xxx",
+ "summary" => "a post"
+ }
+
+ %{user: user, note: note}
+ end
+
+ test "a basic note validates", %{note: note} do
+ %{valid?: true} = NoteValidator.cast_and_validate(note)
+ end
+ end
+end
--
cgit v1.2.3
From b9041c209787dc279d4dc5194d65dff73684cdb9 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Fri, 15 Nov 2019 22:10:41 +0300
Subject: added recount unread notifications to markers
---
test/marker_test.exs | 14 ++++++++++++++
.../mastodon_api/controllers/marker_controller_test.exs | 3 ++-
2 files changed, 16 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/marker_test.exs b/test/marker_test.exs
index 5d03db48e..7b1d2218a 100644
--- a/test/marker_test.exs
+++ b/test/marker_test.exs
@@ -36,6 +36,20 @@ defmodule Pleroma.MarkerTest do
insert(:marker, timeline: "home", user: user)
assert Marker.get_markers(user, ["notifications"]) == [refresh_record(marker)]
end
+
+ test "returns user markers with recount unread notifications" do
+ user = insert(:user)
+ marker = insert(:marker, user: user)
+ insert(:notification, user: user)
+ insert(:notification, user: user)
+ insert(:marker, timeline: "home", user: user)
+
+ assert Marker.get_markers(
+ user,
+ ["notifications"],
+ %{recount_unread: true}
+ ) == [%Marker{refresh_record(marker) | unread_count: 2}]
+ end
end
describe "upsert/2" do
diff --git a/test/web/mastodon_api/controllers/marker_controller_test.exs b/test/web/mastodon_api/controllers/marker_controller_test.exs
index 8bcfcb7e1..64bf79bb1 100644
--- a/test/web/mastodon_api/controllers/marker_controller_test.exs
+++ b/test/web/mastodon_api/controllers/marker_controller_test.exs
@@ -11,11 +11,12 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
test "gets markers with correct scopes", %{conn: conn} do
user = insert(:user)
token = insert(:oauth_token, user: user, scopes: ["read:statuses"])
+ insert_list(7, :notification, user: user)
{:ok, %{"notifications" => marker}} =
Pleroma.Marker.upsert(
user,
- %{"notifications" => %{"last_read_id" => "69420", "unread_count" => 7}}
+ %{"notifications" => %{"last_read_id" => "69420"}}
)
response =
--
cgit v1.2.3
From 1993d7096d673d8a8151fedd7bcac909d584d13d Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 5 Dec 2019 12:33:06 +0100
Subject: Validators: Add a type for the datetime used in AP.
---
.../object_validators/types/date_time_test.exs | 32 ++++++++++++++++++++++
1 file changed, 32 insertions(+)
create mode 100644 test/web/activity_pub/object_validators/types/date_time_test.exs
(limited to 'test')
diff --git a/test/web/activity_pub/object_validators/types/date_time_test.exs b/test/web/activity_pub/object_validators/types/date_time_test.exs
new file mode 100644
index 000000000..3e17a9497
--- /dev/null
+++ b/test/web/activity_pub/object_validators/types/date_time_test.exs
@@ -0,0 +1,32 @@
+defmodule Pleroma.Web.ActivityPub.ObjectValidators.Types.DateTimeTest do
+ alias Pleroma.Web.ActivityPub.ObjectValidators.Types.DateTime
+ use Pleroma.DataCase
+
+ test "it validates an xsd:Datetime" do
+ valid_strings = [
+ "2004-04-12T13:20:00",
+ "2004-04-12T13:20:15.5",
+ "2004-04-12T13:20:00-05:00",
+ "2004-04-12T13:20:00Z"
+ ]
+
+ invalid_strings = [
+ "2004-04-12T13:00",
+ "2004-04-1213:20:00",
+ "99-04-12T13:00",
+ "2004-04-12"
+ ]
+
+ assert {:ok, "2004-04-01T12:00:00Z"} == DateTime.cast("2004-04-01T12:00:00Z")
+
+ Enum.each(valid_strings, fn date_time ->
+ result = DateTime.cast(date_time)
+ assert {:ok, _} = result
+ end)
+
+ Enum.each(invalid_strings, fn date_time ->
+ result = DateTime.cast(date_time)
+ assert :error == result
+ end)
+ end
+end
--
cgit v1.2.3
From cd040691bd28fea1437b8f1c39bb914465e1ff46 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Mon, 10 Feb 2020 09:01:45 +0300
Subject: maked `unread_count` as virtual field
---
test/marker_test.exs | 14 +++-----------
test/notification_test.exs | 5 ++++-
2 files changed, 7 insertions(+), 12 deletions(-)
(limited to 'test')
diff --git a/test/marker_test.exs b/test/marker_test.exs
index 7b1d2218a..54c710691 100644
--- a/test/marker_test.exs
+++ b/test/marker_test.exs
@@ -15,7 +15,7 @@ defmodule Pleroma.MarkerTest do
assert %Ecto.Multi{
operations: [marker: {:run, _}, counters: {:run, _}]
} =
- Marker.multi_set_unread_count(
+ Marker.multi_set_last_read_id(
Ecto.Multi.new(),
user,
"notifications"
@@ -25,19 +25,12 @@ defmodule Pleroma.MarkerTest do
test "return empty multi" do
user = insert(:user)
multi = Ecto.Multi.new()
- assert Marker.multi_set_unread_count(multi, user, "home") == multi
+ assert Marker.multi_set_last_read_id(multi, user, "home") == multi
end
end
describe "get_markers/2" do
test "returns user markers" do
- user = insert(:user)
- marker = insert(:marker, user: user)
- insert(:marker, timeline: "home", user: user)
- assert Marker.get_markers(user, ["notifications"]) == [refresh_record(marker)]
- end
-
- test "returns user markers with recount unread notifications" do
user = insert(:user)
marker = insert(:marker, user: user)
insert(:notification, user: user)
@@ -46,8 +39,7 @@ defmodule Pleroma.MarkerTest do
assert Marker.get_markers(
user,
- ["notifications"],
- %{recount_unread: true}
+ ["notifications"]
) == [%Marker{refresh_record(marker) | unread_count: 2}]
end
end
diff --git a/test/notification_test.exs b/test/notification_test.exs
index c9b352097..49a79b2d3 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -338,12 +338,15 @@ defmodule Pleroma.NotificationTest do
assert n2.seen == true
assert n3.seen == false
- assert %Pleroma.Marker{unread_count: 1} =
+ assert %Pleroma.Marker{} =
+ m =
Pleroma.Repo.get_by(
Pleroma.Marker,
user_id: other_user.id,
timeline: "notifications"
)
+
+ assert m.last_read_id == to_string(n2.id)
end
end
--
cgit v1.2.3
From 514c899275a32e6ef63305f9424c50344d41b12e Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 11 Feb 2020 10:12:57 +0300
Subject: adding gun adapter
---
test/activity/ir/topics_test.exs | 2 +-
test/config/config_db_test.exs | 8 -
test/fixtures/warnings/otp_version/21.1 | 1 +
test/fixtures/warnings/otp_version/22.1 | 1 +
test/fixtures/warnings/otp_version/22.4 | 1 +
test/fixtures/warnings/otp_version/23.0 | 1 +
test/fixtures/warnings/otp_version/error | 1 +
test/fixtures/warnings/otp_version/undefined | 1 +
test/gun/gun_test.exs | 33 +
test/http/adapter/gun_test.exs | 266 +++++++
test/http/adapter/hackney_test.exs | 54 ++
test/http/adapter_test.exs | 65 ++
test/http/connection_test.exs | 142 ++++
test/http/request_builder_test.exs | 30 +-
test/http_test.exs | 35 +-
test/notification_test.exs | 7 +
test/otp_version_test.exs | 58 ++
test/pool/connections_test.exs | 959 +++++++++++++++++++++++
test/reverse_proxy/client/tesla_test.exs | 93 +++
test/reverse_proxy/reverse_proxy_test.exs | 385 +++++++++
test/reverse_proxy_test.exs | 344 --------
test/support/http_request_mock.ex | 94 ++-
test/user_invite_token_test.exs | 4 -
test/web/admin_api/admin_api_controller_test.exs | 9 +-
test/web/common_api/common_api_utils_test.exs | 7 +
test/web/push/impl_test.exs | 2 +-
26 files changed, 2180 insertions(+), 423 deletions(-)
create mode 100644 test/fixtures/warnings/otp_version/21.1
create mode 100644 test/fixtures/warnings/otp_version/22.1
create mode 100644 test/fixtures/warnings/otp_version/22.4
create mode 100644 test/fixtures/warnings/otp_version/23.0
create mode 100644 test/fixtures/warnings/otp_version/error
create mode 100644 test/fixtures/warnings/otp_version/undefined
create mode 100644 test/gun/gun_test.exs
create mode 100644 test/http/adapter/gun_test.exs
create mode 100644 test/http/adapter/hackney_test.exs
create mode 100644 test/http/adapter_test.exs
create mode 100644 test/http/connection_test.exs
create mode 100644 test/otp_version_test.exs
create mode 100644 test/pool/connections_test.exs
create mode 100644 test/reverse_proxy/client/tesla_test.exs
create mode 100644 test/reverse_proxy/reverse_proxy_test.exs
delete mode 100644 test/reverse_proxy_test.exs
(limited to 'test')
diff --git a/test/activity/ir/topics_test.exs b/test/activity/ir/topics_test.exs
index e75f83586..8729e5746 100644
--- a/test/activity/ir/topics_test.exs
+++ b/test/activity/ir/topics_test.exs
@@ -83,7 +83,7 @@ defmodule Pleroma.Activity.Ir.TopicsTest do
assert Enum.member?(topics, "hashtag:bar")
end
- test "only converts strinngs to hash tags", %{
+ test "only converts strings to hash tags", %{
activity: %{object: %{data: data} = object} = activity
} do
tagged_data = Map.put(data, "tag", [2])
diff --git a/test/config/config_db_test.exs b/test/config/config_db_test.exs
index 812709fd8..394040a59 100644
--- a/test/config/config_db_test.exs
+++ b/test/config/config_db_test.exs
@@ -478,14 +478,6 @@ defmodule Pleroma.ConfigDBTest do
assert ConfigDB.from_binary(binary) == [key: "value"]
end
- test "keyword with partial_chain key" do
- binary =
- ConfigDB.transform([%{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]}])
-
- assert binary == :erlang.term_to_binary(partial_chain: &:hackney_connect.partial_chain/1)
- assert ConfigDB.from_binary(binary) == [partial_chain: &:hackney_connect.partial_chain/1]
- end
-
test "keyword" do
binary =
ConfigDB.transform([
diff --git a/test/fixtures/warnings/otp_version/21.1 b/test/fixtures/warnings/otp_version/21.1
new file mode 100644
index 000000000..90cd64c4f
--- /dev/null
+++ b/test/fixtures/warnings/otp_version/21.1
@@ -0,0 +1 @@
+21.1
\ No newline at end of file
diff --git a/test/fixtures/warnings/otp_version/22.1 b/test/fixtures/warnings/otp_version/22.1
new file mode 100644
index 000000000..d9b314368
--- /dev/null
+++ b/test/fixtures/warnings/otp_version/22.1
@@ -0,0 +1 @@
+22.1
\ No newline at end of file
diff --git a/test/fixtures/warnings/otp_version/22.4 b/test/fixtures/warnings/otp_version/22.4
new file mode 100644
index 000000000..1da8ccd28
--- /dev/null
+++ b/test/fixtures/warnings/otp_version/22.4
@@ -0,0 +1 @@
+22.4
\ No newline at end of file
diff --git a/test/fixtures/warnings/otp_version/23.0 b/test/fixtures/warnings/otp_version/23.0
new file mode 100644
index 000000000..4266d8634
--- /dev/null
+++ b/test/fixtures/warnings/otp_version/23.0
@@ -0,0 +1 @@
+23.0
\ No newline at end of file
diff --git a/test/fixtures/warnings/otp_version/error b/test/fixtures/warnings/otp_version/error
new file mode 100644
index 000000000..8fdd954df
--- /dev/null
+++ b/test/fixtures/warnings/otp_version/error
@@ -0,0 +1 @@
+22
\ No newline at end of file
diff --git a/test/fixtures/warnings/otp_version/undefined b/test/fixtures/warnings/otp_version/undefined
new file mode 100644
index 000000000..66dc9051d
--- /dev/null
+++ b/test/fixtures/warnings/otp_version/undefined
@@ -0,0 +1 @@
+undefined
\ No newline at end of file
diff --git a/test/gun/gun_test.exs b/test/gun/gun_test.exs
new file mode 100644
index 000000000..7f185617c
--- /dev/null
+++ b/test/gun/gun_test.exs
@@ -0,0 +1,33 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.GunTest do
+ use ExUnit.Case
+ alias Pleroma.Gun
+
+ @moduletag :integration
+
+ test "opens connection and receive response" do
+ {:ok, conn} = Gun.open('httpbin.org', 443)
+ assert is_pid(conn)
+ {:ok, _protocol} = Gun.await_up(conn)
+ ref = :gun.get(conn, '/get?a=b&c=d')
+ assert is_reference(ref)
+
+ assert {:response, :nofin, 200, _} = Gun.await(conn, ref)
+ assert json = receive_response(conn, ref)
+
+ assert %{"args" => %{"a" => "b", "c" => "d"}} = Jason.decode!(json)
+ end
+
+ defp receive_response(conn, ref, acc \\ "") do
+ case Gun.await(conn, ref) do
+ {:data, :nofin, body} ->
+ receive_response(conn, ref, acc <> body)
+
+ {:data, :fin, body} ->
+ acc <> body
+ end
+ end
+end
diff --git a/test/http/adapter/gun_test.exs b/test/http/adapter/gun_test.exs
new file mode 100644
index 000000000..37489e1a4
--- /dev/null
+++ b/test/http/adapter/gun_test.exs
@@ -0,0 +1,266 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.HTTP.Adapter.GunTest do
+ use ExUnit.Case, async: true
+ use Pleroma.Tests.Helpers
+ import ExUnit.CaptureLog
+ alias Pleroma.Config
+ alias Pleroma.HTTP.Adapter.Gun
+ alias Pleroma.Pool.Connections
+
+ setup_all do
+ {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.Gun.API.Mock)
+ :ok
+ end
+
+ describe "options/1" do
+ clear_config([:http, :adapter]) do
+ Config.put([:http, :adapter], a: 1, b: 2)
+ end
+
+ test "https url with default port" do
+ uri = URI.parse("https://example.com")
+
+ opts = Gun.options(uri)
+ assert opts[:certificates_verification]
+ tls_opts = opts[:tls_opts]
+ assert tls_opts[:verify] == :verify_peer
+ assert tls_opts[:depth] == 20
+ assert tls_opts[:reuse_sessions] == false
+
+ assert tls_opts[:verify_fun] ==
+ {&:ssl_verify_hostname.verify_fun/3, [check_hostname: 'example.com']}
+
+ assert File.exists?(tls_opts[:cacertfile])
+
+ assert opts[:original] == "example.com:443"
+ end
+
+ test "https ipv4 with default port" do
+ uri = URI.parse("https://127.0.0.1")
+
+ opts = Gun.options(uri)
+
+ assert opts[:tls_opts][:verify_fun] ==
+ {&:ssl_verify_hostname.verify_fun/3, [check_hostname: '127.0.0.1']}
+
+ assert opts[:original] == "127.0.0.1:443"
+ end
+
+ test "https ipv6 with default port" do
+ uri = URI.parse("https://[2a03:2880:f10c:83:face:b00c:0:25de]")
+
+ opts = Gun.options(uri)
+
+ assert opts[:tls_opts][:verify_fun] ==
+ {&:ssl_verify_hostname.verify_fun/3,
+ [check_hostname: '2a03:2880:f10c:83:face:b00c:0:25de']}
+
+ assert opts[:original] == "2a03:2880:f10c:83:face:b00c:0:25de:443"
+ end
+
+ test "https url with non standart port" do
+ uri = URI.parse("https://example.com:115")
+
+ opts = Gun.options(uri)
+
+ assert opts[:certificates_verification]
+ assert opts[:transport] == :tls
+ end
+
+ test "receive conn by default" do
+ uri = URI.parse("http://another-domain.com")
+ :ok = Connections.open_conn(uri, :gun_connections)
+
+ received_opts = Gun.options(uri)
+ assert received_opts[:close_conn] == false
+ assert is_pid(received_opts[:conn])
+ end
+
+ test "don't receive conn if receive_conn is false" do
+ uri = URI.parse("http://another-domain2.com")
+ :ok = Connections.open_conn(uri, :gun_connections)
+
+ opts = [receive_conn: false]
+ received_opts = Gun.options(opts, uri)
+ assert received_opts[:close_conn] == nil
+ assert received_opts[:conn] == nil
+ end
+
+ test "get conn on next request" do
+ level = Application.get_env(:logger, :level)
+ Logger.configure(level: :info)
+ on_exit(fn -> Logger.configure(level: level) end)
+ uri = URI.parse("http://some-domain2.com")
+
+ assert capture_log(fn ->
+ opts = Gun.options(uri)
+
+ assert opts[:conn] == nil
+ assert opts[:close_conn] == nil
+ end) =~
+ "Gun connections pool checkin was not succesfull. Trying to open conn for next request."
+
+ opts = Gun.options(uri)
+
+ assert is_pid(opts[:conn])
+ assert opts[:close_conn] == false
+ end
+
+ test "merges with defaul http adapter config" do
+ defaults = Gun.options(URI.parse("https://example.com"))
+ assert Keyword.has_key?(defaults, :a)
+ assert Keyword.has_key?(defaults, :b)
+ end
+
+ test "default ssl adapter opts with connection" do
+ uri = URI.parse("https://some-domain.com")
+
+ :ok = Connections.open_conn(uri, :gun_connections)
+
+ opts = Gun.options(uri)
+
+ assert opts[:certificates_verification]
+ tls_opts = opts[:tls_opts]
+ assert tls_opts[:verify] == :verify_peer
+ assert tls_opts[:depth] == 20
+ assert tls_opts[:reuse_sessions] == false
+
+ assert opts[:original] == "some-domain.com:443"
+ assert opts[:close_conn] == false
+ assert is_pid(opts[:conn])
+ end
+
+ test "parses string proxy host & port" do
+ proxy = Config.get([:http, :proxy_url])
+ Config.put([:http, :proxy_url], "localhost:8123")
+ on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
+
+ uri = URI.parse("https://some-domain.com")
+ opts = Gun.options([receive_conn: false], uri)
+ assert opts[:proxy] == {'localhost', 8123}
+ end
+
+ test "parses tuple proxy scheme host and port" do
+ proxy = Config.get([:http, :proxy_url])
+ Config.put([:http, :proxy_url], {:socks, 'localhost', 1234})
+ on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
+
+ uri = URI.parse("https://some-domain.com")
+ opts = Gun.options([receive_conn: false], uri)
+ assert opts[:proxy] == {:socks, 'localhost', 1234}
+ end
+
+ test "passed opts have more weight than defaults" do
+ proxy = Config.get([:http, :proxy_url])
+ Config.put([:http, :proxy_url], {:socks5, 'localhost', 1234})
+ on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
+ uri = URI.parse("https://some-domain.com")
+ opts = Gun.options([receive_conn: false, proxy: {'example.com', 4321}], uri)
+
+ assert opts[:proxy] == {'example.com', 4321}
+ end
+ end
+
+ describe "after_request/1" do
+ test "body_as not chunks" do
+ uri = URI.parse("http://some-domain.com")
+ :ok = Connections.open_conn(uri, :gun_connections)
+ opts = Gun.options(uri)
+ :ok = Gun.after_request(opts)
+ conn = opts[:conn]
+
+ assert %Connections{
+ conns: %{
+ "http:some-domain.com:80" => %Pleroma.Gun.Conn{
+ conn: ^conn,
+ conn_state: :idle,
+ used_by: []
+ }
+ }
+ } = Connections.get_state(:gun_connections)
+ end
+
+ test "body_as chunks" do
+ uri = URI.parse("http://some-domain.com")
+ :ok = Connections.open_conn(uri, :gun_connections)
+ opts = Gun.options([body_as: :chunks], uri)
+ :ok = Gun.after_request(opts)
+ conn = opts[:conn]
+ self = self()
+
+ assert %Connections{
+ conns: %{
+ "http:some-domain.com:80" => %Pleroma.Gun.Conn{
+ conn: ^conn,
+ conn_state: :active,
+ used_by: [{^self, _}]
+ }
+ }
+ } = Connections.get_state(:gun_connections)
+ end
+
+ test "with no connection" do
+ uri = URI.parse("http://uniq-domain.com")
+
+ :ok = Connections.open_conn(uri, :gun_connections)
+
+ opts = Gun.options([body_as: :chunks], uri)
+ conn = opts[:conn]
+ opts = Keyword.delete(opts, :conn)
+ self = self()
+
+ :ok = Gun.after_request(opts)
+
+ assert %Connections{
+ conns: %{
+ "http:uniq-domain.com:80" => %Pleroma.Gun.Conn{
+ conn: ^conn,
+ conn_state: :active,
+ used_by: [{^self, _}]
+ }
+ }
+ } = Connections.get_state(:gun_connections)
+ end
+
+ test "with ipv4" do
+ uri = URI.parse("http://127.0.0.1")
+ :ok = Connections.open_conn(uri, :gun_connections)
+ opts = Gun.options(uri)
+ send(:gun_connections, {:gun_up, opts[:conn], :http})
+ :ok = Gun.after_request(opts)
+ conn = opts[:conn]
+
+ assert %Connections{
+ conns: %{
+ "http:127.0.0.1:80" => %Pleroma.Gun.Conn{
+ conn: ^conn,
+ conn_state: :idle,
+ used_by: []
+ }
+ }
+ } = Connections.get_state(:gun_connections)
+ end
+
+ test "with ipv6" do
+ uri = URI.parse("http://[2a03:2880:f10c:83:face:b00c:0:25de]")
+ :ok = Connections.open_conn(uri, :gun_connections)
+ opts = Gun.options(uri)
+ send(:gun_connections, {:gun_up, opts[:conn], :http})
+ :ok = Gun.after_request(opts)
+ conn = opts[:conn]
+
+ assert %Connections{
+ conns: %{
+ "http:2a03:2880:f10c:83:face:b00c:0:25de:80" => %Pleroma.Gun.Conn{
+ conn: ^conn,
+ conn_state: :idle,
+ used_by: []
+ }
+ }
+ } = Connections.get_state(:gun_connections)
+ end
+ end
+end
diff --git a/test/http/adapter/hackney_test.exs b/test/http/adapter/hackney_test.exs
new file mode 100644
index 000000000..35cb58125
--- /dev/null
+++ b/test/http/adapter/hackney_test.exs
@@ -0,0 +1,54 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.HTTP.Adapter.HackneyTest do
+ use ExUnit.Case
+ use Pleroma.Tests.Helpers
+
+ alias Pleroma.Config
+ alias Pleroma.HTTP.Adapter.Hackney
+
+ setup_all do
+ uri = URI.parse("http://domain.com")
+ {:ok, uri: uri}
+ end
+
+ describe "options/2" do
+ clear_config([:http, :adapter]) do
+ Config.put([:http, :adapter], a: 1, b: 2)
+ end
+
+ test "add proxy and opts from config", %{uri: uri} do
+ proxy = Config.get([:http, :proxy_url])
+ Config.put([:http, :proxy_url], "localhost:8123")
+ on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
+
+ opts = Hackney.options(uri)
+
+ assert opts[:a] == 1
+ assert opts[:b] == 2
+ assert opts[:proxy] == "localhost:8123"
+ end
+
+ test "respect connection opts and no proxy", %{uri: uri} do
+ opts = Hackney.options([a: 2, b: 1], uri)
+
+ assert opts[:a] == 2
+ assert opts[:b] == 1
+ refute Keyword.has_key?(opts, :proxy)
+ end
+
+ test "add opts for https" do
+ uri = URI.parse("https://domain.com")
+
+ opts = Hackney.options(uri)
+
+ assert opts[:ssl_options] == [
+ partial_chain: &:hackney_connect.partial_chain/1,
+ versions: [:tlsv1, :"tlsv1.1", :"tlsv1.2"],
+ server_name_indication: 'domain.com'
+ ]
+ end
+ end
+end
diff --git a/test/http/adapter_test.exs b/test/http/adapter_test.exs
new file mode 100644
index 000000000..37e47dabe
--- /dev/null
+++ b/test/http/adapter_test.exs
@@ -0,0 +1,65 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.HTTP.AdapterTest do
+ use ExUnit.Case, async: true
+
+ alias Pleroma.HTTP.Adapter
+
+ describe "domain_or_ip/1" do
+ test "with domain" do
+ assert Adapter.domain_or_ip("example.com") == {:domain, 'example.com'}
+ end
+
+ test "with idna domain" do
+ assert Adapter.domain_or_ip("ですexample.com") == {:domain, 'xn--example-183fne.com'}
+ end
+
+ test "with ipv4" do
+ assert Adapter.domain_or_ip("127.0.0.1") == {:ip, {127, 0, 0, 1}}
+ end
+
+ test "with ipv6" do
+ assert Adapter.domain_or_ip("2a03:2880:f10c:83:face:b00c:0:25de") ==
+ {:ip, {10_755, 10_368, 61_708, 131, 64_206, 45_068, 0, 9_694}}
+ end
+ end
+
+ describe "domain_or_fallback/1" do
+ test "with domain" do
+ assert Adapter.domain_or_fallback("example.com") == 'example.com'
+ end
+
+ test "with idna domain" do
+ assert Adapter.domain_or_fallback("ですexample.com") == 'xn--example-183fne.com'
+ end
+
+ test "with ipv4" do
+ assert Adapter.domain_or_fallback("127.0.0.1") == '127.0.0.1'
+ end
+
+ test "with ipv6" do
+ assert Adapter.domain_or_fallback("2a03:2880:f10c:83:face:b00c:0:25de") ==
+ '2a03:2880:f10c:83:face:b00c:0:25de'
+ end
+ end
+
+ describe "format_proxy/1" do
+ test "with nil" do
+ assert Adapter.format_proxy(nil) == nil
+ end
+
+ test "with string" do
+ assert Adapter.format_proxy("127.0.0.1:8123") == {{127, 0, 0, 1}, 8123}
+ end
+
+ test "localhost with port" do
+ assert Adapter.format_proxy("localhost:8123") == {'localhost', 8123}
+ end
+
+ test "tuple" do
+ assert Adapter.format_proxy({:socks4, :localhost, 9050}) == {:socks4, 'localhost', 9050}
+ end
+ end
+end
diff --git a/test/http/connection_test.exs b/test/http/connection_test.exs
new file mode 100644
index 000000000..c1ff0cc21
--- /dev/null
+++ b/test/http/connection_test.exs
@@ -0,0 +1,142 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.HTTP.ConnectionTest do
+ use ExUnit.Case
+ use Pleroma.Tests.Helpers
+ import ExUnit.CaptureLog
+ alias Pleroma.Config
+ alias Pleroma.HTTP.Connection
+
+ setup_all do
+ {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.Gun.API.Mock)
+ :ok
+ end
+
+ describe "parse_host/1" do
+ test "as atom to charlist" do
+ assert Connection.parse_host(:localhost) == 'localhost'
+ end
+
+ test "as string to charlist" do
+ assert Connection.parse_host("localhost.com") == 'localhost.com'
+ end
+
+ test "as string ip to tuple" do
+ assert Connection.parse_host("127.0.0.1") == {127, 0, 0, 1}
+ end
+ end
+
+ describe "parse_proxy/1" do
+ test "ip with port" do
+ assert Connection.parse_proxy("127.0.0.1:8123") == {:ok, {127, 0, 0, 1}, 8123}
+ end
+
+ test "host with port" do
+ assert Connection.parse_proxy("localhost:8123") == {:ok, 'localhost', 8123}
+ end
+
+ test "as tuple" do
+ assert Connection.parse_proxy({:socks4, :localhost, 9050}) ==
+ {:ok, :socks4, 'localhost', 9050}
+ end
+
+ test "as tuple with string host" do
+ assert Connection.parse_proxy({:socks5, "localhost", 9050}) ==
+ {:ok, :socks5, 'localhost', 9050}
+ end
+ end
+
+ describe "parse_proxy/1 errors" do
+ test "ip without port" do
+ capture_log(fn ->
+ assert Connection.parse_proxy("127.0.0.1") == {:error, :error_parsing_proxy}
+ end) =~ "parsing proxy fail \"127.0.0.1\""
+ end
+
+ test "host without port" do
+ capture_log(fn ->
+ assert Connection.parse_proxy("localhost") == {:error, :error_parsing_proxy}
+ end) =~ "parsing proxy fail \"localhost\""
+ end
+
+ test "host with bad port" do
+ capture_log(fn ->
+ assert Connection.parse_proxy("localhost:port") == {:error, :error_parsing_port_in_proxy}
+ end) =~ "parsing port in proxy fail \"localhost:port\""
+ end
+
+ test "ip with bad port" do
+ capture_log(fn ->
+ assert Connection.parse_proxy("127.0.0.1:15.9") == {:error, :error_parsing_port_in_proxy}
+ end) =~ "parsing port in proxy fail \"127.0.0.1:15.9\""
+ end
+
+ test "as tuple without port" do
+ capture_log(fn ->
+ assert Connection.parse_proxy({:socks5, :localhost}) == {:error, :error_parsing_proxy}
+ end) =~ "parsing proxy fail {:socks5, :localhost}"
+ end
+
+ test "with nil" do
+ assert Connection.parse_proxy(nil) == nil
+ end
+ end
+
+ describe "options/3" do
+ clear_config([:http, :proxy_url])
+
+ test "without proxy_url in config" do
+ Config.delete([:http, :proxy_url])
+
+ opts = Connection.options(%URI{})
+ refute Keyword.has_key?(opts, :proxy)
+ end
+
+ test "parses string proxy host & port" do
+ Config.put([:http, :proxy_url], "localhost:8123")
+
+ opts = Connection.options(%URI{})
+ assert opts[:proxy] == {'localhost', 8123}
+ end
+
+ test "parses tuple proxy scheme host and port" do
+ Config.put([:http, :proxy_url], {:socks, 'localhost', 1234})
+
+ opts = Connection.options(%URI{})
+ assert opts[:proxy] == {:socks, 'localhost', 1234}
+ end
+
+ test "passed opts have more weight than defaults" do
+ Config.put([:http, :proxy_url], {:socks5, 'localhost', 1234})
+
+ opts = Connection.options(%URI{}, proxy: {'example.com', 4321})
+
+ assert opts[:proxy] == {'example.com', 4321}
+ end
+
+ test "default ssl adapter opts with connection" do
+ adapter = Application.get_env(:tesla, :adapter)
+ Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
+ on_exit(fn -> Application.put_env(:tesla, :adapter, adapter) end)
+
+ uri = URI.parse("https://some-domain.com")
+
+ pid = Process.whereis(:federation)
+ :ok = Pleroma.Pool.Connections.open_conn(uri, :gun_connections, genserver_pid: pid)
+
+ opts = Connection.options(uri)
+
+ assert opts[:certificates_verification]
+ tls_opts = opts[:tls_opts]
+ assert tls_opts[:verify] == :verify_peer
+ assert tls_opts[:depth] == 20
+ assert tls_opts[:reuse_sessions] == false
+
+ assert opts[:original] == "some-domain.com:443"
+ assert opts[:close_conn] == false
+ assert is_pid(opts[:conn])
+ end
+ end
+end
diff --git a/test/http/request_builder_test.exs b/test/http/request_builder_test.exs
index 80ef25d7b..27ca651be 100644
--- a/test/http/request_builder_test.exs
+++ b/test/http/request_builder_test.exs
@@ -5,30 +5,32 @@
defmodule Pleroma.HTTP.RequestBuilderTest do
use ExUnit.Case, async: true
use Pleroma.Tests.Helpers
+ alias Pleroma.Config
+ alias Pleroma.HTTP.Request
alias Pleroma.HTTP.RequestBuilder
describe "headers/2" do
clear_config([:http, :send_user_agent])
test "don't send pleroma user agent" do
- assert RequestBuilder.headers(%{}, []) == %{headers: []}
+ assert RequestBuilder.headers(%Request{}, []) == %Request{headers: []}
end
test "send pleroma user agent" do
- Pleroma.Config.put([:http, :send_user_agent], true)
- Pleroma.Config.put([:http, :user_agent], :default)
+ Config.put([:http, :send_user_agent], true)
+ Config.put([:http, :user_agent], :default)
- assert RequestBuilder.headers(%{}, []) == %{
- headers: [{"User-Agent", Pleroma.Application.user_agent()}]
+ assert RequestBuilder.headers(%Request{}, []) == %Request{
+ headers: [{"user-agent", Pleroma.Application.user_agent()}]
}
end
test "send custom user agent" do
- Pleroma.Config.put([:http, :send_user_agent], true)
- Pleroma.Config.put([:http, :user_agent], "totally-not-pleroma")
+ Config.put([:http, :send_user_agent], true)
+ Config.put([:http, :user_agent], "totally-not-pleroma")
- assert RequestBuilder.headers(%{}, []) == %{
- headers: [{"User-Agent", "totally-not-pleroma"}]
+ assert RequestBuilder.headers(%Request{}, []) == %Request{
+ headers: [{"user-agent", "totally-not-pleroma"}]
}
end
end
@@ -40,19 +42,19 @@ defmodule Pleroma.HTTP.RequestBuilderTest do
test "add query parameter" do
assert RequestBuilder.add_optional_params(
- %{},
+ %Request{},
%{query: :query, body: :body, another: :val},
[
{:query, "param1=val1¶m2=val2"},
{:body, "some body"}
]
- ) == %{query: "param1=val1¶m2=val2", body: "some body"}
+ ) == %Request{query: "param1=val1¶m2=val2", body: "some body"}
end
end
describe "add_param/4" do
test "add file parameter" do
- %{
+ %Request{
body: %Tesla.Multipart{
boundary: _,
content_type_params: [],
@@ -69,7 +71,7 @@ defmodule Pleroma.HTTP.RequestBuilderTest do
}
]
}
- } = RequestBuilder.add_param(%{}, :file, "filename.png", "some-path/filename.png")
+ } = RequestBuilder.add_param(%Request{}, :file, "filename.png", "some-path/filename.png")
end
test "add key to body" do
@@ -81,7 +83,7 @@ defmodule Pleroma.HTTP.RequestBuilderTest do
%Tesla.Multipart.Part{
body: "\"someval\"",
dispositions: [name: "somekey"],
- headers: ["Content-Type": "application/json"]
+ headers: [{"content-type", "application/json"}]
}
]
}
diff --git a/test/http_test.exs b/test/http_test.exs
index 5f9522cf0..d80b96496 100644
--- a/test/http_test.exs
+++ b/test/http_test.exs
@@ -3,8 +3,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTPTest do
- use Pleroma.DataCase
+ use ExUnit.Case
+ use Pleroma.Tests.Helpers
import Tesla.Mock
+ alias Pleroma.HTTP
setup do
mock(fn
@@ -27,7 +29,7 @@ defmodule Pleroma.HTTPTest do
describe "get/1" do
test "returns successfully result" do
- assert Pleroma.HTTP.get("http://example.com/hello") == {
+ assert HTTP.get("http://example.com/hello") == {
:ok,
%Tesla.Env{status: 200, body: "hello"}
}
@@ -36,7 +38,7 @@ defmodule Pleroma.HTTPTest do
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"}]) ==
+ assert HTTP.get("http://example.com/hello", [{"content-type", "application/json"}]) ==
{
:ok,
%Tesla.Env{
@@ -50,10 +52,35 @@ defmodule Pleroma.HTTPTest do
describe "post/2" do
test "returns successfully result" do
- assert Pleroma.HTTP.post("http://example.com/world", "") == {
+ assert HTTP.post("http://example.com/world", "") == {
:ok,
%Tesla.Env{status: 200, body: "world"}
}
end
end
+
+ describe "connection pools" do
+ @describetag :integration
+ clear_config([Pleroma.Gun.API]) do
+ Pleroma.Config.put([Pleroma.Gun.API], Pleroma.Gun)
+ end
+
+ test "gun" do
+ adapter = Application.get_env(:tesla, :adapter)
+ Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
+
+ on_exit(fn ->
+ Application.put_env(:tesla, :adapter, adapter)
+ end)
+
+ options = [adapter: [pool: :federation]]
+
+ assert {:ok, resp} = HTTP.get("https://httpbin.org/user-agent", [], options)
+
+ assert resp.status == 200
+
+ state = Pleroma.Pool.Connections.get_state(:gun_connections)
+ assert state.conns["https:httpbin.org:443"]
+ end
+ end
end
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 04bf5b41a..1de3c6e3b 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -649,6 +649,13 @@ defmodule Pleroma.NotificationTest do
"object" => remote_user.ap_id
}
+ remote_user_url = remote_user.ap_id
+
+ Tesla.Mock.mock(fn
+ %{method: :get, url: ^remote_user_url} ->
+ %Tesla.Env{status: 404, body: ""}
+ end)
+
{:ok, _delete_activity} = Transmogrifier.handle_incoming(delete_user_message)
ObanHelpers.perform_all()
diff --git a/test/otp_version_test.exs b/test/otp_version_test.exs
new file mode 100644
index 000000000..f26b90f61
--- /dev/null
+++ b/test/otp_version_test.exs
@@ -0,0 +1,58 @@
+defmodule Pleroma.OTPVersionTest do
+ use ExUnit.Case, async: true
+
+ alias Pleroma.OTPVersion
+
+ describe "get_and_check_version/2" do
+ test "22.4" do
+ assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
+ "test/fixtures/warnings/otp_version/22.4"
+ ]) == :ok
+ end
+
+ test "22.1" do
+ assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
+ "test/fixtures/warnings/otp_version/22.1"
+ ]) == {:error, "22.1"}
+ end
+
+ test "21.1" do
+ assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
+ "test/fixtures/warnings/otp_version/21.1"
+ ]) == {:error, "21.1"}
+ end
+
+ test "23.0" do
+ assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
+ "test/fixtures/warnings/otp_version/23.0"
+ ]) == :ok
+ end
+
+ test "undefined" do
+ assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
+ "test/fixtures/warnings/otp_version/undefined"
+ ]) == :undefined
+ end
+
+ test "not parsable" do
+ assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
+ "test/fixtures/warnings/otp_version/error"
+ ]) == :undefined
+ end
+
+ test "with non existance file" do
+ assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
+ "test/fixtures/warnings/otp_version/non-exising",
+ "test/fixtures/warnings/otp_version/22.4"
+ ]) == :ok
+ end
+
+ test "empty paths" do
+ assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, []) == :undefined
+ end
+
+ test "another adapter" do
+ assert OTPVersion.get_and_check_version(Tesla.Adapter.Hackney, []) == :ok
+ end
+ end
+end
diff --git a/test/pool/connections_test.exs b/test/pool/connections_test.exs
new file mode 100644
index 000000000..6f0e041ae
--- /dev/null
+++ b/test/pool/connections_test.exs
@@ -0,0 +1,959 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Pool.ConnectionsTest do
+ use ExUnit.Case
+ use Pleroma.Tests.Helpers
+ import ExUnit.CaptureLog
+ alias Pleroma.Gun.API
+ alias Pleroma.Gun.Conn
+ alias Pleroma.Pool.Connections
+
+ setup_all do
+ {:ok, _} = Registry.start_link(keys: :unique, name: API.Mock)
+ :ok
+ end
+
+ setup do
+ name = :test_connections
+ adapter = Application.get_env(:tesla, :adapter)
+ Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
+ on_exit(fn -> Application.put_env(:tesla, :adapter, adapter) end)
+
+ {:ok, _pid} =
+ Connections.start_link({name, [max_connections: 2, receive_connection_timeout: 1_500]})
+
+ {:ok, name: name}
+ end
+
+ describe "alive?/2" do
+ test "is alive", %{name: name} do
+ assert Connections.alive?(name)
+ end
+
+ test "returns false if not started" do
+ refute Connections.alive?(:some_random_name)
+ end
+ end
+
+ test "opens connection and reuse it on next request", %{name: name} do
+ url = "http://some-domain.com"
+ key = "http:some-domain.com:80"
+ refute Connections.checkin(url, name)
+ :ok = Connections.open_conn(url, name)
+
+ conn = Connections.checkin(url, name)
+ assert is_pid(conn)
+ assert Process.alive?(conn)
+
+ self = self()
+
+ %Connections{
+ conns: %{
+ ^key => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ used_by: [{^self, _}],
+ conn_state: :active
+ }
+ }
+ } = Connections.get_state(name)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert conn == reused_conn
+
+ %Connections{
+ conns: %{
+ ^key => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ used_by: [{^self, _}, {^self, _}],
+ conn_state: :active
+ }
+ }
+ } = Connections.get_state(name)
+
+ :ok = Connections.checkout(conn, self, name)
+
+ %Connections{
+ conns: %{
+ ^key => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ used_by: [{^self, _}],
+ conn_state: :active
+ }
+ }
+ } = Connections.get_state(name)
+
+ :ok = Connections.checkout(conn, self, name)
+
+ %Connections{
+ conns: %{
+ ^key => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ used_by: [],
+ conn_state: :idle
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ test "reuse connection for idna domains", %{name: name} do
+ url = "http://ですsome-domain.com"
+ refute Connections.checkin(url, name)
+
+ :ok = Connections.open_conn(url, name)
+
+ conn = Connections.checkin(url, name)
+ assert is_pid(conn)
+ assert Process.alive?(conn)
+
+ self = self()
+
+ %Connections{
+ conns: %{
+ "http:ですsome-domain.com:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ used_by: [{^self, _}],
+ conn_state: :active
+ }
+ }
+ } = Connections.get_state(name)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert conn == reused_conn
+ end
+
+ test "reuse for ipv4", %{name: name} do
+ url = "http://127.0.0.1"
+
+ refute Connections.checkin(url, name)
+
+ :ok = Connections.open_conn(url, name)
+
+ conn = Connections.checkin(url, name)
+ assert is_pid(conn)
+ assert Process.alive?(conn)
+
+ self = self()
+
+ %Connections{
+ conns: %{
+ "http:127.0.0.1:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ used_by: [{^self, _}],
+ conn_state: :active
+ }
+ }
+ } = Connections.get_state(name)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert conn == reused_conn
+
+ :ok = Connections.checkout(conn, self, name)
+ :ok = Connections.checkout(reused_conn, self, name)
+
+ %Connections{
+ conns: %{
+ "http:127.0.0.1:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ used_by: [],
+ conn_state: :idle
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ test "reuse for ipv6", %{name: name} do
+ url = "http://[2a03:2880:f10c:83:face:b00c:0:25de]"
+
+ refute Connections.checkin(url, name)
+
+ :ok = Connections.open_conn(url, name)
+
+ conn = Connections.checkin(url, name)
+ assert is_pid(conn)
+ assert Process.alive?(conn)
+
+ self = self()
+
+ %Connections{
+ conns: %{
+ "http:2a03:2880:f10c:83:face:b00c:0:25de:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ used_by: [{^self, _}],
+ conn_state: :active
+ }
+ }
+ } = Connections.get_state(name)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert conn == reused_conn
+ end
+
+ test "up and down ipv4", %{name: name} do
+ self = self()
+ url = "http://127.0.0.1"
+ :ok = Connections.open_conn(url, name)
+ conn = Connections.checkin(url, name)
+ send(name, {:gun_down, conn, nil, nil, nil})
+ send(name, {:gun_up, conn, nil})
+
+ %Connections{
+ conns: %{
+ "http:127.0.0.1:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ used_by: [{^self, _}],
+ conn_state: :active
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ test "up and down ipv6", %{name: name} do
+ self = self()
+ url = "http://[2a03:2880:f10c:83:face:b00c:0:25de]"
+ :ok = Connections.open_conn(url, name)
+ conn = Connections.checkin(url, name)
+ send(name, {:gun_down, conn, nil, nil, nil})
+ send(name, {:gun_up, conn, nil})
+
+ %Connections{
+ conns: %{
+ "http:2a03:2880:f10c:83:face:b00c:0:25de:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ used_by: [{^self, _}],
+ conn_state: :active
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ test "reuses connection based on protocol", %{name: name} do
+ http_url = "http://some-domain.com"
+ http_key = "http:some-domain.com:80"
+ https_url = "https://some-domain.com"
+ https_key = "https:some-domain.com:443"
+
+ refute Connections.checkin(http_url, name)
+ :ok = Connections.open_conn(http_url, name)
+ conn = Connections.checkin(http_url, name)
+ assert is_pid(conn)
+ assert Process.alive?(conn)
+
+ refute Connections.checkin(https_url, name)
+ :ok = Connections.open_conn(https_url, name)
+ https_conn = Connections.checkin(https_url, name)
+
+ refute conn == https_conn
+
+ reused_https = Connections.checkin(https_url, name)
+
+ refute conn == reused_https
+
+ assert reused_https == https_conn
+
+ %Connections{
+ conns: %{
+ ^http_key => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ },
+ ^https_key => %Conn{
+ conn: ^https_conn,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ test "connection can't get up", %{name: name} do
+ url = "http://gun-not-up.com"
+
+ assert capture_log(fn ->
+ :ok = Connections.open_conn(url, name)
+ refute Connections.checkin(url, name)
+ end) =~
+ "Received error on opening connection http://gun-not-up.com: {:error, :timeout}"
+ end
+
+ test "process gun_down message and then gun_up", %{name: name} do
+ self = self()
+ url = "http://gun-down-and-up.com"
+ key = "http:gun-down-and-up.com:80"
+ :ok = Connections.open_conn(url, name)
+ conn = Connections.checkin(url, name)
+
+ assert is_pid(conn)
+ assert Process.alive?(conn)
+
+ %Connections{
+ conns: %{
+ ^key => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ used_by: [{^self, _}]
+ }
+ }
+ } = Connections.get_state(name)
+
+ send(name, {:gun_down, conn, :http, nil, nil})
+
+ %Connections{
+ conns: %{
+ ^key => %Conn{
+ conn: ^conn,
+ gun_state: :down,
+ used_by: [{^self, _}]
+ }
+ }
+ } = Connections.get_state(name)
+
+ send(name, {:gun_up, conn, :http})
+
+ conn2 = Connections.checkin(url, name)
+ assert conn == conn2
+
+ assert is_pid(conn2)
+ assert Process.alive?(conn2)
+
+ %Connections{
+ conns: %{
+ ^key => %Conn{
+ conn: _,
+ gun_state: :up,
+ used_by: [{^self, _}, {^self, _}]
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ test "async processes get same conn for same domain", %{name: name} do
+ url = "http://some-domain.com"
+ :ok = Connections.open_conn(url, name)
+
+ tasks =
+ for _ <- 1..5 do
+ Task.async(fn ->
+ Connections.checkin(url, name)
+ end)
+ end
+
+ tasks_with_results = Task.yield_many(tasks)
+
+ results =
+ Enum.map(tasks_with_results, fn {task, res} ->
+ res || Task.shutdown(task, :brutal_kill)
+ end)
+
+ conns = for {:ok, value} <- results, do: value
+
+ %Connections{
+ conns: %{
+ "http:some-domain.com:80" => %Conn{
+ conn: conn,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+
+ assert Enum.all?(conns, fn res -> res == conn end)
+ end
+
+ test "remove frequently used and idle", %{name: name} do
+ self = self()
+ http_url = "http://some-domain.com"
+ https_url = "https://some-domain.com"
+ :ok = Connections.open_conn(https_url, name)
+ :ok = Connections.open_conn(http_url, name)
+
+ conn1 = Connections.checkin(https_url, name)
+
+ [conn2 | _conns] =
+ for _ <- 1..4 do
+ Connections.checkin(http_url, name)
+ end
+
+ http_key = "http:some-domain.com:80"
+
+ %Connections{
+ conns: %{
+ ^http_key => %Conn{
+ conn: ^conn2,
+ gun_state: :up,
+ conn_state: :active,
+ used_by: [{^self, _}, {^self, _}, {^self, _}, {^self, _}]
+ },
+ "https:some-domain.com:443" => %Conn{
+ conn: ^conn1,
+ gun_state: :up,
+ conn_state: :active,
+ used_by: [{^self, _}]
+ }
+ }
+ } = Connections.get_state(name)
+
+ :ok = Connections.checkout(conn1, self, name)
+
+ another_url = "http://another-domain.com"
+ :ok = Connections.open_conn(another_url, name)
+ conn = Connections.checkin(another_url, name)
+
+ %Connections{
+ conns: %{
+ "http:another-domain.com:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ },
+ ^http_key => %Conn{
+ conn: _,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ describe "integration test" do
+ @describetag :integration
+
+ clear_config([API]) do
+ Pleroma.Config.put([API], Pleroma.Gun)
+ end
+
+ test "opens connection and reuse it on next request", %{name: name} do
+ url = "http://httpbin.org"
+ :ok = Connections.open_conn(url, name)
+ Process.sleep(250)
+ conn = Connections.checkin(url, name)
+
+ assert is_pid(conn)
+ assert Process.alive?(conn)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert conn == reused_conn
+
+ %Connections{
+ conns: %{
+ "http:httpbin.org:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ test "opens ssl connection and reuse it on next request", %{name: name} do
+ url = "https://httpbin.org"
+ :ok = Connections.open_conn(url, name)
+ Process.sleep(1_000)
+ conn = Connections.checkin(url, name)
+
+ assert is_pid(conn)
+ assert Process.alive?(conn)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert conn == reused_conn
+
+ %Connections{
+ conns: %{
+ "https:httpbin.org:443" => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ test "remove frequently used and idle", %{name: name} do
+ self = self()
+ https1 = "https://www.google.com"
+ https2 = "https://httpbin.org"
+
+ :ok = Connections.open_conn(https1, name)
+ :ok = Connections.open_conn(https2, name)
+ Process.sleep(1_500)
+ conn = Connections.checkin(https1, name)
+
+ for _ <- 1..4 do
+ Connections.checkin(https2, name)
+ end
+
+ %Connections{
+ conns: %{
+ "https:httpbin.org:443" => %Conn{
+ conn: _,
+ gun_state: :up
+ },
+ "https:www.google.com:443" => %Conn{
+ conn: _,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+
+ :ok = Connections.checkout(conn, self, name)
+ http = "http://httpbin.org"
+ Process.sleep(1_000)
+ :ok = Connections.open_conn(http, name)
+ conn = Connections.checkin(http, name)
+
+ %Connections{
+ conns: %{
+ "http:httpbin.org:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ },
+ "https:httpbin.org:443" => %Conn{
+ conn: _,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ test "remove earlier used and idle", %{name: name} do
+ self = self()
+
+ https1 = "https://www.google.com"
+ https2 = "https://httpbin.org"
+ :ok = Connections.open_conn(https1, name)
+ :ok = Connections.open_conn(https2, name)
+ Process.sleep(1_500)
+
+ Connections.checkin(https1, name)
+ conn = Connections.checkin(https1, name)
+
+ Process.sleep(1_000)
+ Connections.checkin(https2, name)
+ Connections.checkin(https2, name)
+
+ %Connections{
+ conns: %{
+ "https:httpbin.org:443" => %Conn{
+ conn: _,
+ gun_state: :up
+ },
+ "https:www.google.com:443" => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+
+ :ok = Connections.checkout(conn, self, name)
+ :ok = Connections.checkout(conn, self, name)
+
+ http = "http://httpbin.org"
+ :ok = Connections.open_conn(http, name)
+ Process.sleep(1_000)
+
+ conn = Connections.checkin(http, name)
+
+ %Connections{
+ conns: %{
+ "http:httpbin.org:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ },
+ "https:httpbin.org:443" => %Conn{
+ conn: _,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ test "doesn't open new conn on pool overflow", %{name: name} do
+ self = self()
+
+ https1 = "https://www.google.com"
+ https2 = "https://httpbin.org"
+ :ok = Connections.open_conn(https1, name)
+ :ok = Connections.open_conn(https2, name)
+ Process.sleep(1_000)
+ Connections.checkin(https1, name)
+ conn1 = Connections.checkin(https1, name)
+ conn2 = Connections.checkin(https2, name)
+
+ %Connections{
+ conns: %{
+ "https:httpbin.org:443" => %Conn{
+ conn: ^conn2,
+ gun_state: :up,
+ conn_state: :active,
+ used_by: [{^self, _}]
+ },
+ "https:www.google.com:443" => %Conn{
+ conn: ^conn1,
+ gun_state: :up,
+ conn_state: :active,
+ used_by: [{^self, _}, {^self, _}]
+ }
+ }
+ } = Connections.get_state(name)
+
+ refute Connections.checkin("http://httpbin.org", name)
+
+ %Connections{
+ conns: %{
+ "https:httpbin.org:443" => %Conn{
+ conn: ^conn2,
+ gun_state: :up,
+ conn_state: :active,
+ used_by: [{^self, _}]
+ },
+ "https:www.google.com:443" => %Conn{
+ conn: ^conn1,
+ gun_state: :up,
+ conn_state: :active,
+ used_by: [{^self, _}, {^self, _}]
+ }
+ }
+ } = Connections.get_state(name)
+ end
+
+ test "get idle connection with the smallest crf", %{
+ name: name
+ } do
+ self = self()
+
+ https1 = "https://www.google.com"
+ https2 = "https://httpbin.org"
+
+ :ok = Connections.open_conn(https1, name)
+ :ok = Connections.open_conn(https2, name)
+ Process.sleep(1_500)
+ Connections.checkin(https1, name)
+ Connections.checkin(https2, name)
+ Connections.checkin(https1, name)
+ conn1 = Connections.checkin(https1, name)
+ conn2 = Connections.checkin(https2, name)
+
+ %Connections{
+ conns: %{
+ "https:httpbin.org:443" => %Conn{
+ conn: ^conn2,
+ gun_state: :up,
+ conn_state: :active,
+ used_by: [{^self, _}, {^self, _}],
+ crf: crf2
+ },
+ "https:www.google.com:443" => %Conn{
+ conn: ^conn1,
+ gun_state: :up,
+ conn_state: :active,
+ used_by: [{^self, _}, {^self, _}, {^self, _}],
+ crf: crf1
+ }
+ }
+ } = Connections.get_state(name)
+
+ assert crf1 > crf2
+
+ :ok = Connections.checkout(conn1, self, name)
+ :ok = Connections.checkout(conn1, self, name)
+ :ok = Connections.checkout(conn1, self, name)
+
+ :ok = Connections.checkout(conn2, self, name)
+ :ok = Connections.checkout(conn2, self, name)
+
+ %Connections{
+ conns: %{
+ "https:httpbin.org:443" => %Conn{
+ conn: ^conn2,
+ gun_state: :up,
+ conn_state: :idle,
+ used_by: []
+ },
+ "https:www.google.com:443" => %Conn{
+ conn: ^conn1,
+ gun_state: :up,
+ conn_state: :idle,
+ used_by: []
+ }
+ }
+ } = Connections.get_state(name)
+
+ http = "http://httpbin.org"
+ :ok = Connections.open_conn(http, name)
+ Process.sleep(1_000)
+ conn = Connections.checkin(http, name)
+
+ %Connections{
+ conns: %{
+ "https:www.google.com:443" => %Conn{
+ conn: ^conn1,
+ gun_state: :up,
+ conn_state: :idle,
+ used_by: [],
+ crf: crf1
+ },
+ "http:httpbin.org:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up,
+ conn_state: :active,
+ used_by: [{^self, _}],
+ crf: crf
+ }
+ }
+ } = Connections.get_state(name)
+
+ assert crf1 > crf
+ end
+ end
+
+ describe "with proxy" do
+ test "as ip", %{name: name} do
+ url = "http://proxy-string.com"
+ key = "http:proxy-string.com:80"
+ :ok = Connections.open_conn(url, name, proxy: {{127, 0, 0, 1}, 8123})
+
+ conn = Connections.checkin(url, name)
+
+ %Connections{
+ conns: %{
+ ^key => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert reused_conn == conn
+ end
+
+ test "as host", %{name: name} do
+ url = "http://proxy-tuple-atom.com"
+ :ok = Connections.open_conn(url, name, proxy: {'localhost', 9050})
+ conn = Connections.checkin(url, name)
+
+ %Connections{
+ conns: %{
+ "http:proxy-tuple-atom.com:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert reused_conn == conn
+ end
+
+ test "as ip and ssl", %{name: name} do
+ url = "https://proxy-string.com"
+
+ :ok = Connections.open_conn(url, name, proxy: {{127, 0, 0, 1}, 8123})
+ conn = Connections.checkin(url, name)
+
+ %Connections{
+ conns: %{
+ "https:proxy-string.com:443" => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert reused_conn == conn
+ end
+
+ test "as host and ssl", %{name: name} do
+ url = "https://proxy-tuple-atom.com"
+ :ok = Connections.open_conn(url, name, proxy: {'localhost', 9050})
+ conn = Connections.checkin(url, name)
+
+ %Connections{
+ conns: %{
+ "https:proxy-tuple-atom.com:443" => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert reused_conn == conn
+ end
+
+ test "with socks type", %{name: name} do
+ url = "http://proxy-socks.com"
+
+ :ok = Connections.open_conn(url, name, proxy: {:socks5, 'localhost', 1234})
+
+ conn = Connections.checkin(url, name)
+
+ %Connections{
+ conns: %{
+ "http:proxy-socks.com:80" => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert reused_conn == conn
+ end
+
+ test "with socks4 type and ssl", %{name: name} do
+ url = "https://proxy-socks.com"
+
+ :ok = Connections.open_conn(url, name, proxy: {:socks4, 'localhost', 1234})
+
+ conn = Connections.checkin(url, name)
+
+ %Connections{
+ conns: %{
+ "https:proxy-socks.com:443" => %Conn{
+ conn: ^conn,
+ gun_state: :up
+ }
+ }
+ } = Connections.get_state(name)
+
+ reused_conn = Connections.checkin(url, name)
+
+ assert reused_conn == conn
+ end
+ end
+
+ describe "crf/3" do
+ setup do
+ crf = Connections.crf(1, 10, 1)
+ {:ok, crf: crf}
+ end
+
+ test "more used will have crf higher", %{crf: crf} do
+ # used 3 times
+ crf1 = Connections.crf(1, 10, crf)
+ crf1 = Connections.crf(1, 10, crf1)
+
+ # used 2 times
+ crf2 = Connections.crf(1, 10, crf)
+
+ assert crf1 > crf2
+ end
+
+ test "recently used will have crf higher on equal references", %{crf: crf} do
+ # used 3 sec ago
+ crf1 = Connections.crf(3, 10, crf)
+
+ # used 4 sec ago
+ crf2 = Connections.crf(4, 10, crf)
+
+ assert crf1 > crf2
+ end
+
+ test "equal crf on equal reference and time", %{crf: crf} do
+ # used 2 times
+ crf1 = Connections.crf(1, 10, crf)
+
+ # used 2 times
+ crf2 = Connections.crf(1, 10, crf)
+
+ assert crf1 == crf2
+ end
+
+ test "recently used will have higher crf", %{crf: crf} do
+ crf1 = Connections.crf(2, 10, crf)
+ crf1 = Connections.crf(1, 10, crf1)
+
+ crf2 = Connections.crf(3, 10, crf)
+ crf2 = Connections.crf(4, 10, crf2)
+ assert crf1 > crf2
+ end
+ end
+
+ describe "get_unused_conns/1" do
+ test "crf is equalent, sorting by reference" do
+ conns = %{
+ "1" => %Conn{
+ conn_state: :idle,
+ last_reference: now() - 1
+ },
+ "2" => %Conn{
+ conn_state: :idle,
+ last_reference: now()
+ }
+ }
+
+ assert [{"1", _unused_conn} | _others] = Connections.get_unused_conns(conns)
+ end
+
+ test "reference is equalent, sorting by crf" do
+ conns = %{
+ "1" => %Conn{
+ conn_state: :idle,
+ crf: 1.999
+ },
+ "2" => %Conn{
+ conn_state: :idle,
+ crf: 2
+ }
+ }
+
+ assert [{"1", _unused_conn} | _others] = Connections.get_unused_conns(conns)
+ end
+
+ test "higher crf and lower reference" do
+ conns = %{
+ "1" => %Conn{
+ conn_state: :idle,
+ crf: 3,
+ last_reference: now() - 1
+ },
+ "2" => %Conn{
+ conn_state: :idle,
+ crf: 2,
+ last_reference: now()
+ }
+ }
+
+ assert [{"2", _unused_conn} | _others] = Connections.get_unused_conns(conns)
+ end
+
+ test "lower crf and lower reference" do
+ conns = %{
+ "1" => %Conn{
+ conn_state: :idle,
+ crf: 1.99,
+ last_reference: now() - 1
+ },
+ "2" => %Conn{
+ conn_state: :idle,
+ crf: 2,
+ last_reference: now()
+ }
+ }
+
+ assert [{"1", _unused_conn} | _others] = Connections.get_unused_conns(conns)
+ end
+ end
+
+ defp now do
+ :os.system_time(:second)
+ end
+end
diff --git a/test/reverse_proxy/client/tesla_test.exs b/test/reverse_proxy/client/tesla_test.exs
new file mode 100644
index 000000000..75a70988c
--- /dev/null
+++ b/test/reverse_proxy/client/tesla_test.exs
@@ -0,0 +1,93 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.ReverseProxy.Client.TeslaTest do
+ use ExUnit.Case
+ use Pleroma.Tests.Helpers
+ alias Pleroma.ReverseProxy.Client
+ @moduletag :integration
+
+ clear_config_all([Pleroma.Gun.API]) do
+ Pleroma.Config.put([Pleroma.Gun.API], Pleroma.Gun)
+ end
+
+ setup do
+ Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
+
+ on_exit(fn ->
+ Application.put_env(:tesla, :adapter, Tesla.Mock)
+ end)
+ end
+
+ test "get response body stream" do
+ {:ok, status, headers, ref} =
+ Client.Tesla.request(
+ :get,
+ "http://httpbin.org/stream-bytes/10",
+ [{"accept", "application/octet-stream"}],
+ "",
+ []
+ )
+
+ assert status == 200
+ assert headers != []
+
+ {:ok, response, ref} = Client.Tesla.stream_body(ref)
+ check_ref(ref)
+ assert is_binary(response)
+ assert byte_size(response) == 10
+
+ assert :done == Client.Tesla.stream_body(ref)
+ assert :ok = Client.Tesla.close(ref)
+ end
+
+ test "head response" do
+ {:ok, status, headers} = Client.Tesla.request(:head, "https://httpbin.org/get", [], "")
+
+ assert status == 200
+ assert headers != []
+ end
+
+ test "get error response" do
+ {:ok, status, headers, _body} =
+ Client.Tesla.request(
+ :get,
+ "https://httpbin.org/status/500",
+ [],
+ ""
+ )
+
+ assert status == 500
+ assert headers != []
+ end
+
+ describe "client error" do
+ setup do
+ adapter = Application.get_env(:tesla, :adapter)
+ Application.put_env(:tesla, :adapter, Tesla.Adapter.Hackney)
+
+ on_exit(fn -> Application.put_env(:tesla, :adapter, adapter) end)
+ :ok
+ end
+
+ test "adapter doesn't support reading body in chunks" do
+ assert_raise RuntimeError,
+ "Elixir.Tesla.Adapter.Hackney doesn't support reading body in chunks",
+ fn ->
+ Client.Tesla.request(
+ :get,
+ "http://httpbin.org/stream-bytes/10",
+ [{"accept", "application/octet-stream"}],
+ ""
+ )
+ end
+ end
+ end
+
+ defp check_ref(%{pid: pid, stream: stream} = ref) do
+ assert is_pid(pid)
+ assert is_reference(stream)
+ assert ref[:fin]
+ end
+end
diff --git a/test/reverse_proxy/reverse_proxy_test.exs b/test/reverse_proxy/reverse_proxy_test.exs
new file mode 100644
index 000000000..1ab3cc4bb
--- /dev/null
+++ b/test/reverse_proxy/reverse_proxy_test.exs
@@ -0,0 +1,385 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.ReverseProxyTest do
+ use Pleroma.Web.ConnCase
+ import ExUnit.CaptureLog
+ import Mox
+ alias Pleroma.ReverseProxy
+ alias Pleroma.ReverseProxy.ClientMock
+
+ setup_all do
+ {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.ReverseProxy.ClientMock)
+ :ok
+ end
+
+ setup :verify_on_exit!
+
+ defp user_agent_mock(user_agent, invokes) do
+ json = Jason.encode!(%{"user-agent": user_agent})
+
+ ClientMock
+ |> expect(:request, fn :get, url, _, _, _ ->
+ Registry.register(Pleroma.ReverseProxy.ClientMock, url, 0)
+
+ {:ok, 200,
+ [
+ {"content-type", "application/json"},
+ {"content-length", byte_size(json) |> to_string()}
+ ], %{url: url}}
+ end)
+ |> expect(:stream_body, invokes, fn %{url: url} = client ->
+ case Registry.lookup(Pleroma.ReverseProxy.ClientMock, url) do
+ [{_, 0}] ->
+ Registry.update_value(Pleroma.ReverseProxy.ClientMock, url, &(&1 + 1))
+ {:ok, json, client}
+
+ [{_, 1}] ->
+ Registry.unregister(Pleroma.ReverseProxy.ClientMock, url)
+ :done
+ end
+ end)
+ end
+
+ describe "reverse proxy" do
+ test "do not track successful request", %{conn: conn} do
+ user_agent_mock("hackney/1.15.1", 2)
+ url = "/success"
+
+ conn = ReverseProxy.call(conn, url)
+
+ assert conn.status == 200
+ assert Cachex.get(:failed_proxy_url_cache, url) == {:ok, nil}
+ end
+ end
+
+ describe "user-agent" do
+ test "don't keep", %{conn: conn} do
+ user_agent_mock("hackney/1.15.1", 2)
+ conn = ReverseProxy.call(conn, "/user-agent")
+ assert json_response(conn, 200) == %{"user-agent" => "hackney/1.15.1"}
+ end
+
+ test "keep", %{conn: conn} do
+ user_agent_mock(Pleroma.Application.user_agent(), 2)
+ conn = ReverseProxy.call(conn, "/user-agent-keep", keep_user_agent: true)
+ assert json_response(conn, 200) == %{"user-agent" => Pleroma.Application.user_agent()}
+ end
+ end
+
+ test "closed connection", %{conn: conn} do
+ ClientMock
+ |> expect(:request, fn :get, "/closed", _, _, _ -> {:ok, 200, [], %{}} end)
+ |> expect(:stream_body, fn _ -> {:error, :closed} end)
+ |> expect(:close, fn _ -> :ok end)
+
+ conn = ReverseProxy.call(conn, "/closed")
+ assert conn.halted
+ end
+
+ defp stream_mock(invokes, with_close? \\ false) do
+ ClientMock
+ |> expect(:request, fn :get, "/stream-bytes/" <> length, _, _, _ ->
+ Registry.register(Pleroma.ReverseProxy.ClientMock, "/stream-bytes/" <> length, 0)
+
+ {:ok, 200, [{"content-type", "application/octet-stream"}],
+ %{url: "/stream-bytes/" <> length}}
+ end)
+ |> expect(:stream_body, invokes, fn %{url: "/stream-bytes/" <> length} = client ->
+ max = String.to_integer(length)
+
+ case Registry.lookup(Pleroma.ReverseProxy.ClientMock, "/stream-bytes/" <> length) do
+ [{_, current}] when current < max ->
+ Registry.update_value(
+ Pleroma.ReverseProxy.ClientMock,
+ "/stream-bytes/" <> length,
+ &(&1 + 10)
+ )
+
+ {:ok, "0123456789", client}
+
+ [{_, ^max}] ->
+ Registry.unregister(Pleroma.ReverseProxy.ClientMock, "/stream-bytes/" <> length)
+ :done
+ end
+ end)
+
+ if with_close? do
+ expect(ClientMock, :close, fn _ -> :ok end)
+ end
+ end
+
+ describe "max_body" do
+ test "length returns error if content-length more than option", %{conn: conn} do
+ user_agent_mock("hackney/1.15.1", 0)
+
+ assert capture_log(fn ->
+ ReverseProxy.call(conn, "/huge-file", max_body_length: 4)
+ end) =~
+ "[error] Elixir.Pleroma.ReverseProxy: request to \"/huge-file\" failed: :body_too_large"
+
+ assert {:ok, true} == Cachex.get(:failed_proxy_url_cache, "/huge-file")
+
+ assert capture_log(fn ->
+ ReverseProxy.call(conn, "/huge-file", max_body_length: 4)
+ end) == ""
+ end
+
+ test "max_body_length returns error if streaming body more than that option", %{conn: conn} do
+ stream_mock(3, true)
+
+ assert capture_log(fn ->
+ ReverseProxy.call(conn, "/stream-bytes/50", max_body_length: 30)
+ end) =~
+ "[warn] Elixir.Pleroma.ReverseProxy request to /stream-bytes/50 failed while reading/chunking: :body_too_large"
+ end
+ end
+
+ describe "HEAD requests" do
+ test "common", %{conn: conn} do
+ ClientMock
+ |> expect(:request, fn :head, "/head", _, _, _ ->
+ {:ok, 200, [{"content-type", "text/html; charset=utf-8"}]}
+ end)
+
+ conn = ReverseProxy.call(Map.put(conn, :method, "HEAD"), "/head")
+ assert html_response(conn, 200) == ""
+ end
+ end
+
+ defp error_mock(status) when is_integer(status) do
+ ClientMock
+ |> expect(:request, fn :get, "/status/" <> _, _, _, _ ->
+ {:error, status}
+ end)
+ end
+
+ describe "returns error on" do
+ test "500", %{conn: conn} do
+ error_mock(500)
+ url = "/status/500"
+
+ capture_log(fn -> ReverseProxy.call(conn, url) end) =~
+ "[error] Elixir.Pleroma.ReverseProxy: request to /status/500 failed with HTTP status 500"
+
+ assert Cachex.get(:failed_proxy_url_cache, url) == {:ok, true}
+
+ {:ok, ttl} = Cachex.ttl(:failed_proxy_url_cache, url)
+ assert ttl <= 60_000
+ end
+
+ test "400", %{conn: conn} do
+ error_mock(400)
+ url = "/status/400"
+
+ capture_log(fn -> ReverseProxy.call(conn, url) end) =~
+ "[error] Elixir.Pleroma.ReverseProxy: request to /status/400 failed with HTTP status 400"
+
+ assert Cachex.get(:failed_proxy_url_cache, url) == {:ok, true}
+ assert Cachex.ttl(:failed_proxy_url_cache, url) == {:ok, nil}
+ end
+
+ test "403", %{conn: conn} do
+ error_mock(403)
+ url = "/status/403"
+
+ capture_log(fn ->
+ ReverseProxy.call(conn, url, failed_request_ttl: :timer.seconds(120))
+ end) =~
+ "[error] Elixir.Pleroma.ReverseProxy: request to /status/403 failed with HTTP status 403"
+
+ {:ok, ttl} = Cachex.ttl(:failed_proxy_url_cache, url)
+ assert ttl > 100_000
+ end
+
+ test "204", %{conn: conn} do
+ url = "/status/204"
+ expect(ClientMock, :request, fn :get, _url, _, _, _ -> {:ok, 204, [], %{}} end)
+
+ capture_log(fn ->
+ conn = ReverseProxy.call(conn, url)
+ assert conn.resp_body == "Request failed: No Content"
+ assert conn.halted
+ end) =~
+ "[error] Elixir.Pleroma.ReverseProxy: request to \"/status/204\" failed with HTTP status 204"
+
+ assert Cachex.get(:failed_proxy_url_cache, url) == {:ok, true}
+ assert Cachex.ttl(:failed_proxy_url_cache, url) == {:ok, nil}
+ end
+ end
+
+ test "streaming", %{conn: conn} do
+ stream_mock(21)
+ conn = ReverseProxy.call(conn, "/stream-bytes/200")
+ assert conn.state == :chunked
+ assert byte_size(conn.resp_body) == 200
+ assert Plug.Conn.get_resp_header(conn, "content-type") == ["application/octet-stream"]
+ end
+
+ defp headers_mock(_) do
+ ClientMock
+ |> expect(:request, fn :get, "/headers", headers, _, _ ->
+ Registry.register(Pleroma.ReverseProxy.ClientMock, "/headers", 0)
+ {:ok, 200, [{"content-type", "application/json"}], %{url: "/headers", headers: headers}}
+ end)
+ |> expect(:stream_body, 2, fn %{url: url, headers: headers} = client ->
+ case Registry.lookup(Pleroma.ReverseProxy.ClientMock, url) do
+ [{_, 0}] ->
+ Registry.update_value(Pleroma.ReverseProxy.ClientMock, url, &(&1 + 1))
+ headers = for {k, v} <- headers, into: %{}, do: {String.capitalize(k), v}
+ {:ok, Jason.encode!(%{headers: headers}), client}
+
+ [{_, 1}] ->
+ Registry.unregister(Pleroma.ReverseProxy.ClientMock, url)
+ :done
+ end
+ end)
+
+ :ok
+ end
+
+ describe "keep request headers" do
+ setup [:headers_mock]
+
+ test "header passes", %{conn: conn} do
+ conn =
+ Plug.Conn.put_req_header(
+ conn,
+ "accept",
+ "text/html"
+ )
+ |> ReverseProxy.call("/headers")
+
+ %{"headers" => headers} = json_response(conn, 200)
+ assert headers["Accept"] == "text/html"
+ end
+
+ test "header is filtered", %{conn: conn} do
+ conn =
+ Plug.Conn.put_req_header(
+ conn,
+ "accept-language",
+ "en-US"
+ )
+ |> ReverseProxy.call("/headers")
+
+ %{"headers" => headers} = json_response(conn, 200)
+ refute headers["Accept-Language"]
+ end
+ end
+
+ test "returns 400 on non GET, HEAD requests", %{conn: conn} do
+ conn = ReverseProxy.call(Map.put(conn, :method, "POST"), "/ip")
+ assert conn.status == 400
+ end
+
+ describe "cache resp headers" do
+ test "returns headers", %{conn: conn} do
+ ClientMock
+ |> expect(:request, fn :get, "/cache/" <> ttl, _, _, _ ->
+ {:ok, 200, [{"cache-control", "public, max-age=" <> ttl}], %{}}
+ end)
+ |> expect(:stream_body, fn _ -> :done end)
+
+ conn = ReverseProxy.call(conn, "/cache/10")
+ assert {"cache-control", "public, max-age=10"} in conn.resp_headers
+ end
+
+ test "add cache-control", %{conn: conn} do
+ ClientMock
+ |> expect(:request, fn :get, "/cache", _, _, _ ->
+ {:ok, 200, [{"ETag", "some ETag"}], %{}}
+ end)
+ |> expect(:stream_body, fn _ -> :done end)
+
+ conn = ReverseProxy.call(conn, "/cache")
+ assert {"cache-control", "public"} in conn.resp_headers
+ end
+ end
+
+ defp disposition_headers_mock(headers) do
+ ClientMock
+ |> expect(:request, fn :get, "/disposition", _, _, _ ->
+ Registry.register(Pleroma.ReverseProxy.ClientMock, "/disposition", 0)
+
+ {:ok, 200, headers, %{url: "/disposition"}}
+ end)
+ |> expect(:stream_body, 2, fn %{url: "/disposition"} = client ->
+ case Registry.lookup(Pleroma.ReverseProxy.ClientMock, "/disposition") do
+ [{_, 0}] ->
+ Registry.update_value(Pleroma.ReverseProxy.ClientMock, "/disposition", &(&1 + 1))
+ {:ok, "", client}
+
+ [{_, 1}] ->
+ Registry.unregister(Pleroma.ReverseProxy.ClientMock, "/disposition")
+ :done
+ end
+ end)
+ end
+
+ describe "response content disposition header" do
+ test "not atachment", %{conn: conn} do
+ disposition_headers_mock([
+ {"content-type", "image/gif"},
+ {"content-length", 0}
+ ])
+
+ conn = ReverseProxy.call(conn, "/disposition")
+
+ assert {"content-type", "image/gif"} in conn.resp_headers
+ end
+
+ test "with content-disposition header", %{conn: conn} do
+ disposition_headers_mock([
+ {"content-disposition", "attachment; filename=\"filename.jpg\""},
+ {"content-length", 0}
+ ])
+
+ conn = ReverseProxy.call(conn, "/disposition")
+
+ assert {"content-disposition", "attachment; filename=\"filename.jpg\""} in conn.resp_headers
+ end
+ end
+
+ describe "tesla client using gun integration" do
+ @describetag :integration
+
+ clear_config([Pleroma.ReverseProxy.Client]) do
+ Pleroma.Config.put([Pleroma.ReverseProxy.Client], Pleroma.ReverseProxy.Client.Tesla)
+ end
+
+ clear_config([Pleroma.Gun.API]) do
+ Pleroma.Config.put([Pleroma.Gun.API], Pleroma.Gun)
+ end
+
+ setup do
+ adapter = Application.get_env(:tesla, :adapter)
+ Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
+
+ on_exit(fn ->
+ Application.put_env(:tesla, :adapter, adapter)
+ end)
+ end
+
+ test "common", %{conn: conn} do
+ conn = ReverseProxy.call(conn, "http://httpbin.org/stream-bytes/10")
+ assert byte_size(conn.resp_body) == 10
+ assert conn.state == :chunked
+ assert conn.status == 200
+ end
+
+ test "ssl", %{conn: conn} do
+ conn = ReverseProxy.call(conn, "https://httpbin.org/stream-bytes/10")
+ assert byte_size(conn.resp_body) == 10
+ assert conn.state == :chunked
+ assert conn.status == 200
+ end
+
+ test "follow redirects", %{conn: conn} do
+ conn = ReverseProxy.call(conn, "https://httpbin.org/redirect/5")
+ assert conn.state == :chunked
+ assert conn.status == 200
+ end
+ end
+end
diff --git a/test/reverse_proxy_test.exs b/test/reverse_proxy_test.exs
deleted file mode 100644
index 0672f57db..000000000
--- a/test/reverse_proxy_test.exs
+++ /dev/null
@@ -1,344 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.ReverseProxyTest do
- use Pleroma.Web.ConnCase, async: true
- import ExUnit.CaptureLog
- import Mox
- alias Pleroma.ReverseProxy
- alias Pleroma.ReverseProxy.ClientMock
-
- setup_all do
- {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.ReverseProxy.ClientMock)
- :ok
- end
-
- setup :verify_on_exit!
-
- defp user_agent_mock(user_agent, invokes) do
- json = Jason.encode!(%{"user-agent": user_agent})
-
- ClientMock
- |> expect(:request, fn :get, url, _, _, _ ->
- Registry.register(Pleroma.ReverseProxy.ClientMock, url, 0)
-
- {:ok, 200,
- [
- {"content-type", "application/json"},
- {"content-length", byte_size(json) |> to_string()}
- ], %{url: url}}
- end)
- |> expect(:stream_body, invokes, fn %{url: url} ->
- case Registry.lookup(Pleroma.ReverseProxy.ClientMock, url) do
- [{_, 0}] ->
- Registry.update_value(Pleroma.ReverseProxy.ClientMock, url, &(&1 + 1))
- {:ok, json}
-
- [{_, 1}] ->
- Registry.unregister(Pleroma.ReverseProxy.ClientMock, url)
- :done
- end
- end)
- end
-
- describe "reverse proxy" do
- test "do not track successful request", %{conn: conn} do
- user_agent_mock("hackney/1.15.1", 2)
- url = "/success"
-
- conn = ReverseProxy.call(conn, url)
-
- assert conn.status == 200
- assert Cachex.get(:failed_proxy_url_cache, url) == {:ok, nil}
- end
- end
-
- describe "user-agent" do
- test "don't keep", %{conn: conn} do
- user_agent_mock("hackney/1.15.1", 2)
- conn = ReverseProxy.call(conn, "/user-agent")
- assert json_response(conn, 200) == %{"user-agent" => "hackney/1.15.1"}
- end
-
- test "keep", %{conn: conn} do
- user_agent_mock(Pleroma.Application.user_agent(), 2)
- conn = ReverseProxy.call(conn, "/user-agent-keep", keep_user_agent: true)
- assert json_response(conn, 200) == %{"user-agent" => Pleroma.Application.user_agent()}
- end
- end
-
- test "closed connection", %{conn: conn} do
- ClientMock
- |> expect(:request, fn :get, "/closed", _, _, _ -> {:ok, 200, [], %{}} end)
- |> expect(:stream_body, fn _ -> {:error, :closed} end)
- |> expect(:close, fn _ -> :ok end)
-
- conn = ReverseProxy.call(conn, "/closed")
- assert conn.halted
- end
-
- describe "max_body " do
- test "length returns error if content-length more than option", %{conn: conn} do
- user_agent_mock("hackney/1.15.1", 0)
-
- assert capture_log(fn ->
- ReverseProxy.call(conn, "/huge-file", max_body_length: 4)
- end) =~
- "[error] Elixir.Pleroma.ReverseProxy: request to \"/huge-file\" failed: :body_too_large"
-
- assert {:ok, true} == Cachex.get(:failed_proxy_url_cache, "/huge-file")
-
- assert capture_log(fn ->
- ReverseProxy.call(conn, "/huge-file", max_body_length: 4)
- end) == ""
- end
-
- defp stream_mock(invokes, with_close? \\ false) do
- ClientMock
- |> expect(:request, fn :get, "/stream-bytes/" <> length, _, _, _ ->
- Registry.register(Pleroma.ReverseProxy.ClientMock, "/stream-bytes/" <> length, 0)
-
- {:ok, 200, [{"content-type", "application/octet-stream"}],
- %{url: "/stream-bytes/" <> length}}
- end)
- |> expect(:stream_body, invokes, fn %{url: "/stream-bytes/" <> length} ->
- max = String.to_integer(length)
-
- case Registry.lookup(Pleroma.ReverseProxy.ClientMock, "/stream-bytes/" <> length) do
- [{_, current}] when current < max ->
- Registry.update_value(
- Pleroma.ReverseProxy.ClientMock,
- "/stream-bytes/" <> length,
- &(&1 + 10)
- )
-
- {:ok, "0123456789"}
-
- [{_, ^max}] ->
- Registry.unregister(Pleroma.ReverseProxy.ClientMock, "/stream-bytes/" <> length)
- :done
- end
- end)
-
- if with_close? do
- expect(ClientMock, :close, fn _ -> :ok end)
- end
- end
-
- test "max_body_length returns error if streaming body more than that option", %{conn: conn} do
- stream_mock(3, true)
-
- assert capture_log(fn ->
- ReverseProxy.call(conn, "/stream-bytes/50", max_body_length: 30)
- end) =~
- "[warn] Elixir.Pleroma.ReverseProxy request to /stream-bytes/50 failed while reading/chunking: :body_too_large"
- end
- end
-
- describe "HEAD requests" do
- test "common", %{conn: conn} do
- ClientMock
- |> expect(:request, fn :head, "/head", _, _, _ ->
- {:ok, 200, [{"content-type", "text/html; charset=utf-8"}]}
- end)
-
- conn = ReverseProxy.call(Map.put(conn, :method, "HEAD"), "/head")
- assert html_response(conn, 200) == ""
- end
- end
-
- defp error_mock(status) when is_integer(status) do
- ClientMock
- |> expect(:request, fn :get, "/status/" <> _, _, _, _ ->
- {:error, status}
- end)
- end
-
- describe "returns error on" do
- test "500", %{conn: conn} do
- error_mock(500)
- url = "/status/500"
-
- capture_log(fn -> ReverseProxy.call(conn, url) end) =~
- "[error] Elixir.Pleroma.ReverseProxy: request to /status/500 failed with HTTP status 500"
-
- assert Cachex.get(:failed_proxy_url_cache, url) == {:ok, true}
-
- {:ok, ttl} = Cachex.ttl(:failed_proxy_url_cache, url)
- assert ttl <= 60_000
- end
-
- test "400", %{conn: conn} do
- error_mock(400)
- url = "/status/400"
-
- capture_log(fn -> ReverseProxy.call(conn, url) end) =~
- "[error] Elixir.Pleroma.ReverseProxy: request to /status/400 failed with HTTP status 400"
-
- assert Cachex.get(:failed_proxy_url_cache, url) == {:ok, true}
- assert Cachex.ttl(:failed_proxy_url_cache, url) == {:ok, nil}
- end
-
- test "403", %{conn: conn} do
- error_mock(403)
- url = "/status/403"
-
- capture_log(fn ->
- ReverseProxy.call(conn, url, failed_request_ttl: :timer.seconds(120))
- end) =~
- "[error] Elixir.Pleroma.ReverseProxy: request to /status/403 failed with HTTP status 403"
-
- {:ok, ttl} = Cachex.ttl(:failed_proxy_url_cache, url)
- assert ttl > 100_000
- end
-
- test "204", %{conn: conn} do
- url = "/status/204"
- expect(ClientMock, :request, fn :get, _url, _, _, _ -> {:ok, 204, [], %{}} end)
-
- capture_log(fn ->
- conn = ReverseProxy.call(conn, url)
- assert conn.resp_body == "Request failed: No Content"
- assert conn.halted
- end) =~
- "[error] Elixir.Pleroma.ReverseProxy: request to \"/status/204\" failed with HTTP status 204"
-
- assert Cachex.get(:failed_proxy_url_cache, url) == {:ok, true}
- assert Cachex.ttl(:failed_proxy_url_cache, url) == {:ok, nil}
- end
- end
-
- test "streaming", %{conn: conn} do
- stream_mock(21)
- conn = ReverseProxy.call(conn, "/stream-bytes/200")
- assert conn.state == :chunked
- assert byte_size(conn.resp_body) == 200
- assert Plug.Conn.get_resp_header(conn, "content-type") == ["application/octet-stream"]
- end
-
- defp headers_mock(_) do
- ClientMock
- |> expect(:request, fn :get, "/headers", headers, _, _ ->
- Registry.register(Pleroma.ReverseProxy.ClientMock, "/headers", 0)
- {:ok, 200, [{"content-type", "application/json"}], %{url: "/headers", headers: headers}}
- end)
- |> expect(:stream_body, 2, fn %{url: url, headers: headers} ->
- case Registry.lookup(Pleroma.ReverseProxy.ClientMock, url) do
- [{_, 0}] ->
- Registry.update_value(Pleroma.ReverseProxy.ClientMock, url, &(&1 + 1))
- headers = for {k, v} <- headers, into: %{}, do: {String.capitalize(k), v}
- {:ok, Jason.encode!(%{headers: headers})}
-
- [{_, 1}] ->
- Registry.unregister(Pleroma.ReverseProxy.ClientMock, url)
- :done
- end
- end)
-
- :ok
- end
-
- describe "keep request headers" do
- setup [:headers_mock]
-
- test "header passes", %{conn: conn} do
- conn =
- Plug.Conn.put_req_header(
- conn,
- "accept",
- "text/html"
- )
- |> ReverseProxy.call("/headers")
-
- %{"headers" => headers} = json_response(conn, 200)
- assert headers["Accept"] == "text/html"
- end
-
- test "header is filtered", %{conn: conn} do
- conn =
- Plug.Conn.put_req_header(
- conn,
- "accept-language",
- "en-US"
- )
- |> ReverseProxy.call("/headers")
-
- %{"headers" => headers} = json_response(conn, 200)
- refute headers["Accept-Language"]
- end
- end
-
- test "returns 400 on non GET, HEAD requests", %{conn: conn} do
- conn = ReverseProxy.call(Map.put(conn, :method, "POST"), "/ip")
- assert conn.status == 400
- end
-
- describe "cache resp headers" do
- test "returns headers", %{conn: conn} do
- ClientMock
- |> expect(:request, fn :get, "/cache/" <> ttl, _, _, _ ->
- {:ok, 200, [{"cache-control", "public, max-age=" <> ttl}], %{}}
- end)
- |> expect(:stream_body, fn _ -> :done end)
-
- conn = ReverseProxy.call(conn, "/cache/10")
- assert {"cache-control", "public, max-age=10"} in conn.resp_headers
- end
-
- test "add cache-control", %{conn: conn} do
- ClientMock
- |> expect(:request, fn :get, "/cache", _, _, _ ->
- {:ok, 200, [{"ETag", "some ETag"}], %{}}
- end)
- |> expect(:stream_body, fn _ -> :done end)
-
- conn = ReverseProxy.call(conn, "/cache")
- assert {"cache-control", "public"} in conn.resp_headers
- end
- end
-
- defp disposition_headers_mock(headers) do
- ClientMock
- |> expect(:request, fn :get, "/disposition", _, _, _ ->
- Registry.register(Pleroma.ReverseProxy.ClientMock, "/disposition", 0)
-
- {:ok, 200, headers, %{url: "/disposition"}}
- end)
- |> expect(:stream_body, 2, fn %{url: "/disposition"} ->
- case Registry.lookup(Pleroma.ReverseProxy.ClientMock, "/disposition") do
- [{_, 0}] ->
- Registry.update_value(Pleroma.ReverseProxy.ClientMock, "/disposition", &(&1 + 1))
- {:ok, ""}
-
- [{_, 1}] ->
- Registry.unregister(Pleroma.ReverseProxy.ClientMock, "/disposition")
- :done
- end
- end)
- end
-
- describe "response content disposition header" do
- test "not atachment", %{conn: conn} do
- disposition_headers_mock([
- {"content-type", "image/gif"},
- {"content-length", 0}
- ])
-
- conn = ReverseProxy.call(conn, "/disposition")
-
- assert {"content-type", "image/gif"} in conn.resp_headers
- end
-
- test "with content-disposition header", %{conn: conn} do
- disposition_headers_mock([
- {"content-disposition", "attachment; filename=\"filename.jpg\""},
- {"content-length", 0}
- ])
-
- conn = ReverseProxy.call(conn, "/disposition")
-
- assert {"content-disposition", "attachment; filename=\"filename.jpg\""} in conn.resp_headers
- end
- end
-end
diff --git a/test/support/http_request_mock.ex b/test/support/http_request_mock.ex
index ba3341327..5727871ea 100644
--- a/test/support/http_request_mock.ex
+++ b/test/support/http_request_mock.ex
@@ -107,7 +107,7 @@ defmodule HttpRequestMock do
"https://osada.macgirvin.com/.well-known/webfinger?resource=acct:mike@osada.macgirvin.com",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -120,7 +120,7 @@ defmodule HttpRequestMock do
"https://social.heldscal.la/.well-known/webfinger?resource=https://social.heldscal.la/user/29191",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -141,7 +141,7 @@ defmodule HttpRequestMock do
"https://pawoo.net/.well-known/webfinger?resource=acct:https://pawoo.net/users/pekorino",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -167,7 +167,7 @@ defmodule HttpRequestMock do
"https://social.stopwatchingus-heidelberg.de/.well-known/webfinger?resource=acct:https://social.stopwatchingus-heidelberg.de/user/18330",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -188,7 +188,7 @@ defmodule HttpRequestMock do
"https://mamot.fr/.well-known/webfinger?resource=acct:https://mamot.fr/users/Skruyb",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -201,7 +201,7 @@ defmodule HttpRequestMock do
"https://social.heldscal.la/.well-known/webfinger?resource=nonexistant@social.heldscal.la",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -214,7 +214,7 @@ defmodule HttpRequestMock do
"https://squeet.me/xrd/?uri=lain@squeet.me",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -227,7 +227,7 @@ defmodule HttpRequestMock do
"https://mst3k.interlinked.me/users/luciferMysticus",
_,
_,
- Accept: "application/activity+json"
+ [{"accept", "application/activity+json"}]
) do
{:ok,
%Tesla.Env{
@@ -248,7 +248,7 @@ defmodule HttpRequestMock do
"https://hubzilla.example.org/channel/kaniini",
_,
_,
- Accept: "application/activity+json"
+ [{"accept", "application/activity+json"}]
) do
{:ok,
%Tesla.Env{
@@ -257,7 +257,7 @@ defmodule HttpRequestMock do
}}
end
- def get("https://niu.moe/users/rye", _, _, Accept: "application/activity+json") do
+ def get("https://niu.moe/users/rye", _, _, [{"accept", "application/activity+json"}]) do
{:ok,
%Tesla.Env{
status: 200,
@@ -265,7 +265,7 @@ defmodule HttpRequestMock do
}}
end
- def get("https://n1u.moe/users/rye", _, _, Accept: "application/activity+json") do
+ def get("https://n1u.moe/users/rye", _, _, [{"accept", "application/activity+json"}]) do
{:ok,
%Tesla.Env{
status: 200,
@@ -284,7 +284,7 @@ defmodule HttpRequestMock do
}}
end
- def get("https://puckipedia.com/", _, _, Accept: "application/activity+json") do
+ def get("https://puckipedia.com/", _, _, [{"accept", "application/activity+json"}]) do
{:ok,
%Tesla.Env{
status: 200,
@@ -308,9 +308,9 @@ defmodule HttpRequestMock do
}}
end
- def get("https://mobilizon.org/events/252d5816-00a3-4a89-a66f-15bf65c33e39", _, _,
- Accept: "application/activity+json"
- ) do
+ def get("https://mobilizon.org/events/252d5816-00a3-4a89-a66f-15bf65c33e39", _, _, [
+ {"accept", "application/activity+json"}
+ ]) do
{:ok,
%Tesla.Env{
status: 200,
@@ -318,7 +318,7 @@ defmodule HttpRequestMock do
}}
end
- def get("https://mobilizon.org/@tcit", _, _, Accept: "application/activity+json") do
+ def get("https://mobilizon.org/@tcit", _, _, [{"accept", "application/activity+json"}]) do
{:ok,
%Tesla.Env{
status: 200,
@@ -358,7 +358,7 @@ defmodule HttpRequestMock do
}}
end
- def get("http://mastodon.example.org/users/admin", _, _, Accept: "application/activity+json") do
+ def get("http://mastodon.example.org/users/admin", _, _, _) do
{:ok,
%Tesla.Env{
status: 200,
@@ -366,7 +366,9 @@ defmodule HttpRequestMock do
}}
end
- def get("http://mastodon.example.org/users/relay", _, _, Accept: "application/activity+json") do
+ def get("http://mastodon.example.org/users/relay", _, _, [
+ {"accept", "application/activity+json"}
+ ]) do
{:ok,
%Tesla.Env{
status: 200,
@@ -374,7 +376,9 @@ defmodule HttpRequestMock do
}}
end
- def get("http://mastodon.example.org/users/gargron", _, _, Accept: "application/activity+json") do
+ def get("http://mastodon.example.org/users/gargron", _, _, [
+ {"accept", "application/activity+json"}
+ ]) do
{:error, :nxdomain}
end
@@ -557,7 +561,7 @@ defmodule HttpRequestMock do
"http://mastodon.example.org/@admin/99541947525187367",
_,
_,
- Accept: "application/activity+json"
+ _
) do
{:ok,
%Tesla.Env{
@@ -582,7 +586,7 @@ defmodule HttpRequestMock do
}}
end
- def get("https://mstdn.io/users/mayuutann", _, _, Accept: "application/activity+json") do
+ def get("https://mstdn.io/users/mayuutann", _, _, [{"accept", "application/activity+json"}]) do
{:ok,
%Tesla.Env{
status: 200,
@@ -594,7 +598,7 @@ defmodule HttpRequestMock do
"https://mstdn.io/users/mayuutann/statuses/99568293732299394",
_,
_,
- Accept: "application/activity+json"
+ [{"accept", "application/activity+json"}]
) do
{:ok,
%Tesla.Env{
@@ -614,7 +618,7 @@ defmodule HttpRequestMock do
}}
end
- def get(url, _, _, Accept: "application/xrd+xml,application/jrd+json")
+ 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"
@@ -641,7 +645,7 @@ defmodule HttpRequestMock do
"https://shitposter.club/.well-known/webfinger?resource=https://shitposter.club/user/1",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -685,7 +689,7 @@ defmodule HttpRequestMock do
"https://shitposter.club/.well-known/webfinger?resource=https://shitposter.club/user/5381",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -738,7 +742,7 @@ defmodule HttpRequestMock do
"https://social.sakamoto.gq/.well-known/webfinger?resource=https://social.sakamoto.gq/users/eal",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -751,7 +755,7 @@ defmodule HttpRequestMock do
"https://social.sakamoto.gq/objects/0ccc1a2c-66b0-4305-b23a-7f7f2b040056",
_,
_,
- Accept: "application/atom+xml"
+ [{"accept", "application/atom+xml"}]
) do
{:ok, %Tesla.Env{status: 200, body: File.read!("test/fixtures/tesla_mock/sakamoto.atom")}}
end
@@ -768,7 +772,7 @@ defmodule HttpRequestMock do
"https://mastodon.social/.well-known/webfinger?resource=https://mastodon.social/users/lambadalambda",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -790,7 +794,7 @@ defmodule HttpRequestMock do
"http://gs.example.org/.well-known/webfinger?resource=http://gs.example.org:4040/index.php/user/1",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -804,7 +808,7 @@ defmodule HttpRequestMock do
"http://gs.example.org:4040/index.php/user/1",
_,
_,
- Accept: "application/activity+json"
+ [{"accept", "application/activity+json"}]
) do
{:ok, %Tesla.Env{status: 406, body: ""}}
end
@@ -840,7 +844,7 @@ defmodule HttpRequestMock do
"https://squeet.me/xrd?uri=lain@squeet.me",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -853,7 +857,7 @@ defmodule HttpRequestMock do
"https://social.heldscal.la/.well-known/webfinger?resource=shp@social.heldscal.la",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -866,7 +870,7 @@ defmodule HttpRequestMock do
"https://social.heldscal.la/.well-known/webfinger?resource=invalid_content@social.heldscal.la",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok, %Tesla.Env{status: 200, body: ""}}
end
@@ -883,7 +887,7 @@ defmodule HttpRequestMock do
"http://framatube.org/main/xrd?uri=framasoft@framatube.org",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -905,7 +909,7 @@ defmodule HttpRequestMock do
"http://gnusocial.de/main/xrd?uri=winterdienst@gnusocial.de",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -942,7 +946,7 @@ defmodule HttpRequestMock do
"https://gerzilla.de/xrd/?uri=kaniini@gerzilla.de",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -1005,7 +1009,7 @@ defmodule HttpRequestMock do
%Tesla.Env{status: 200, body: File.read!("test/fixtures/tesla_mock/osada-user-indio.json")}}
end
- def get("https://social.heldscal.la/user/23211", _, _, Accept: "application/activity+json") do
+ 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
@@ -1138,7 +1142,7 @@ defmodule HttpRequestMock do
"https://zetsubou.xn--q9jyb4c/.well-known/webfinger?resource=lain@zetsubou.xn--q9jyb4c",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -1151,7 +1155,7 @@ defmodule HttpRequestMock do
"https://zetsubou.xn--q9jyb4c/.well-known/webfinger?resource=https://zetsubou.xn--q9jyb4c/users/lain",
_,
_,
- Accept: "application/xrd+xml,application/jrd+json"
+ [{"accept", "application/xrd+xml,application/jrd+json"}]
) do
{:ok,
%Tesla.Env{
@@ -1173,7 +1177,9 @@ defmodule HttpRequestMock do
}}
end
- def get("https://info.pleroma.site/activity.json", _, _, Accept: "application/activity+json") do
+ def get("https://info.pleroma.site/activity.json", _, _, [
+ {"accept", "application/activity+json"}
+ ]) do
{:ok,
%Tesla.Env{
status: 200,
@@ -1185,7 +1191,9 @@ defmodule HttpRequestMock do
{:ok, %Tesla.Env{status: 404, body: ""}}
end
- def get("https://info.pleroma.site/activity2.json", _, _, Accept: "application/activity+json") do
+ def get("https://info.pleroma.site/activity2.json", _, _, [
+ {"accept", "application/activity+json"}
+ ]) do
{:ok,
%Tesla.Env{
status: 200,
@@ -1197,7 +1205,9 @@ defmodule HttpRequestMock do
{:ok, %Tesla.Env{status: 404, body: ""}}
end
- def get("https://info.pleroma.site/activity3.json", _, _, Accept: "application/activity+json") do
+ def get("https://info.pleroma.site/activity3.json", _, _, [
+ {"accept", "application/activity+json"}
+ ]) do
{:ok,
%Tesla.Env{
status: 200,
diff --git a/test/user_invite_token_test.exs b/test/user_invite_token_test.exs
index 111e40361..671560e41 100644
--- a/test/user_invite_token_test.exs
+++ b/test/user_invite_token_test.exs
@@ -4,7 +4,6 @@
defmodule Pleroma.UserInviteTokenTest do
use ExUnit.Case, async: true
- use Pleroma.DataCase
alias Pleroma.UserInviteToken
describe "valid_invite?/1 one time invites" do
@@ -64,7 +63,6 @@ defmodule Pleroma.UserInviteTokenTest do
test "expires yesterday returns false", %{invite: invite} do
invite = %{invite | expires_at: Date.add(Date.utc_today(), -1)}
- invite = Repo.insert!(invite)
refute UserInviteToken.valid_invite?(invite)
end
end
@@ -82,7 +80,6 @@ defmodule Pleroma.UserInviteTokenTest do
test "overdue date and less uses returns false", %{invite: invite} do
invite = %{invite | expires_at: Date.add(Date.utc_today(), -1)}
- invite = Repo.insert!(invite)
refute UserInviteToken.valid_invite?(invite)
end
@@ -93,7 +90,6 @@ defmodule Pleroma.UserInviteTokenTest do
test "overdue date with more uses returns false", %{invite: invite} do
invite = %{invite | expires_at: Date.add(Date.utc_today(), -1), uses: 5}
- invite = Repo.insert!(invite)
refute UserInviteToken.valid_invite?(invite)
end
end
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 5fbdf96f6..02ffbfa0b 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -2439,7 +2439,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
"value" => "Tesla.Adapter.Httpc",
"db" => [":adapter"]
}
- ]
+ ],
+ "need_reboot" => true
}
end
@@ -2526,7 +2527,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
%{"tuple" => [":seconds_valid", 60]},
%{"tuple" => [":path", ""]},
%{"tuple" => [":key1", nil]},
- %{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]},
%{"tuple" => [":regex1", "~r/https:\/\/example.com/"]},
%{"tuple" => [":regex2", "~r/https:\/\/example.com/u"]},
%{"tuple" => [":regex3", "~r/https:\/\/example.com/i"]},
@@ -2556,7 +2556,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
%{"tuple" => [":seconds_valid", 60]},
%{"tuple" => [":path", ""]},
%{"tuple" => [":key1", nil]},
- %{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]},
%{"tuple" => [":regex1", "~r/https:\\/\\/example.com/"]},
%{"tuple" => [":regex2", "~r/https:\\/\\/example.com/u"]},
%{"tuple" => [":regex3", "~r/https:\\/\\/example.com/i"]},
@@ -2569,7 +2568,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
":seconds_valid",
":path",
":key1",
- ":partial_chain",
":regex1",
":regex2",
":regex3",
@@ -2583,7 +2581,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
"value" => "Tesla.Adapter.Httpc",
"db" => [":adapter"]
}
- ]
+ ],
+ "need_reboot" => true
}
end
diff --git a/test/web/common_api/common_api_utils_test.exs b/test/web/common_api/common_api_utils_test.exs
index 848300ef3..759501a67 100644
--- a/test/web/common_api/common_api_utils_test.exs
+++ b/test/web/common_api/common_api_utils_test.exs
@@ -474,6 +474,13 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
activity = insert(:note_activity, user: user, note: object)
Pleroma.Repo.delete(object)
+ obj_url = activity.data["object"]
+
+ Tesla.Mock.mock(fn
+ %{method: :get, url: ^obj_url} ->
+ %Tesla.Env{status: 404, body: ""}
+ end)
+
assert Utils.maybe_notify_mentioned_recipients(["test-test"], activity) == [
"test-test"
]
diff --git a/test/web/push/impl_test.exs b/test/web/push/impl_test.exs
index acae7a734..737976f1f 100644
--- a/test/web/push/impl_test.exs
+++ b/test/web/push/impl_test.exs
@@ -126,7 +126,7 @@ defmodule Pleroma.Web.Push.ImplTest do
user = insert(:user, nickname: "Bob")
other_user = insert(:user)
{:ok, _, _, activity} = CommonAPI.follow(user, other_user)
- object = Object.normalize(activity)
+ object = Object.normalize(activity, false)
assert Impl.format_body(%{activity: activity}, user, object) == "@Bob has followed you"
--
cgit v1.2.3
From 138a3c1fe48bbace79c0121d4571db3c2a827860 Mon Sep 17 00:00:00 2001
From: Mark Felder
Date: Tue, 18 Feb 2020 09:30:18 -0600
Subject: Spelling was wrong in test as well
---
test/http/adapter/gun_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/http/adapter/gun_test.exs b/test/http/adapter/gun_test.exs
index 37489e1a4..1d7977c83 100644
--- a/test/http/adapter/gun_test.exs
+++ b/test/http/adapter/gun_test.exs
@@ -101,7 +101,7 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
assert opts[:conn] == nil
assert opts[:close_conn] == nil
end) =~
- "Gun connections pool checkin was not succesfull. Trying to open conn for next request."
+ "Gun connections pool checkin was not successful. Trying to open conn for next request."
opts = Gun.options(uri)
--
cgit v1.2.3
From c9db0507f8d49aee9988b0b63477672f5df9c0b2 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 19 Feb 2020 12:19:03 +0300
Subject: removing retry option and changing some logger messages levels
---
test/http/adapter/gun_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/http/adapter/gun_test.exs b/test/http/adapter/gun_test.exs
index 1d7977c83..ef1b4a882 100644
--- a/test/http/adapter/gun_test.exs
+++ b/test/http/adapter/gun_test.exs
@@ -91,7 +91,7 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
test "get conn on next request" do
level = Application.get_env(:logger, :level)
- Logger.configure(level: :info)
+ Logger.configure(level: :debug)
on_exit(fn -> Logger.configure(level: level) end)
uri = URI.parse("http://some-domain2.com")
--
cgit v1.2.3
From ad8f26c0a4a0a579e93547e78313d3e4ecef6ed5 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Fri, 21 Feb 2020 12:53:40 +0300
Subject: more info in Connections.checkin timout errors
---
test/http_test.exs | 4 ++--
test/pool/connections_test.exs | 8 ++++++--
test/reverse_proxy/client/tesla_test.exs | 4 ++--
test/reverse_proxy/reverse_proxy_test.exs | 8 ++++----
4 files changed, 14 insertions(+), 10 deletions(-)
(limited to 'test')
diff --git a/test/http_test.exs b/test/http_test.exs
index d80b96496..83c27f6e1 100644
--- a/test/http_test.exs
+++ b/test/http_test.exs
@@ -61,8 +61,8 @@ defmodule Pleroma.HTTPTest do
describe "connection pools" do
@describetag :integration
- clear_config([Pleroma.Gun.API]) do
- Pleroma.Config.put([Pleroma.Gun.API], Pleroma.Gun)
+ clear_config(Pleroma.Gun.API) do
+ Pleroma.Config.put(Pleroma.Gun.API, Pleroma.Gun)
end
test "gun" do
diff --git a/test/pool/connections_test.exs b/test/pool/connections_test.exs
index 6f0e041ae..d0d711c55 100644
--- a/test/pool/connections_test.exs
+++ b/test/pool/connections_test.exs
@@ -15,6 +15,10 @@ defmodule Pleroma.Pool.ConnectionsTest do
:ok
end
+ clear_config([:connections_pool, :retry]) do
+ Pleroma.Config.put([:connections_pool, :retry], 5)
+ end
+
setup do
name = :test_connections
adapter = Application.get_env(:tesla, :adapter)
@@ -429,8 +433,8 @@ defmodule Pleroma.Pool.ConnectionsTest do
describe "integration test" do
@describetag :integration
- clear_config([API]) do
- Pleroma.Config.put([API], Pleroma.Gun)
+ clear_config(API) do
+ Pleroma.Config.put(API, Pleroma.Gun)
end
test "opens connection and reuse it on next request", %{name: name} do
diff --git a/test/reverse_proxy/client/tesla_test.exs b/test/reverse_proxy/client/tesla_test.exs
index 75a70988c..231271b0d 100644
--- a/test/reverse_proxy/client/tesla_test.exs
+++ b/test/reverse_proxy/client/tesla_test.exs
@@ -8,8 +8,8 @@ defmodule Pleroma.ReverseProxy.Client.TeslaTest do
alias Pleroma.ReverseProxy.Client
@moduletag :integration
- clear_config_all([Pleroma.Gun.API]) do
- Pleroma.Config.put([Pleroma.Gun.API], Pleroma.Gun)
+ clear_config_all(Pleroma.Gun.API) do
+ Pleroma.Config.put(Pleroma.Gun.API, Pleroma.Gun)
end
setup do
diff --git a/test/reverse_proxy/reverse_proxy_test.exs b/test/reverse_proxy/reverse_proxy_test.exs
index 1ab3cc4bb..f61fc02c5 100644
--- a/test/reverse_proxy/reverse_proxy_test.exs
+++ b/test/reverse_proxy/reverse_proxy_test.exs
@@ -345,12 +345,12 @@ defmodule Pleroma.ReverseProxyTest do
describe "tesla client using gun integration" do
@describetag :integration
- clear_config([Pleroma.ReverseProxy.Client]) do
- Pleroma.Config.put([Pleroma.ReverseProxy.Client], Pleroma.ReverseProxy.Client.Tesla)
+ clear_config(Pleroma.ReverseProxy.Client) do
+ Pleroma.Config.put(Pleroma.ReverseProxy.Client, Pleroma.ReverseProxy.Client.Tesla)
end
- clear_config([Pleroma.Gun.API]) do
- Pleroma.Config.put([Pleroma.Gun.API], Pleroma.Gun)
+ clear_config(Pleroma.Gun.API) do
+ Pleroma.Config.put(Pleroma.Gun.API, Pleroma.Gun)
end
setup do
--
cgit v1.2.3
From 8efae966b1e87fe448a13d04eae0898c4a102c29 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Mon, 24 Feb 2020 19:56:27 +0300
Subject: open conn in separate task
---
test/gun/gun_test.exs | 6 ++
test/http/adapter/gun_test.exs | 17 ++--
test/http/connection_test.exs | 2 +-
test/pool/connections_test.exs | 188 ++++++++++++++++++++++-------------------
4 files changed, 117 insertions(+), 96 deletions(-)
(limited to 'test')
diff --git a/test/gun/gun_test.exs b/test/gun/gun_test.exs
index 7f185617c..9f3e0f938 100644
--- a/test/gun/gun_test.exs
+++ b/test/gun/gun_test.exs
@@ -19,6 +19,12 @@ defmodule Pleroma.GunTest do
assert json = receive_response(conn, ref)
assert %{"args" => %{"a" => "b", "c" => "d"}} = Jason.decode!(json)
+
+ {:ok, pid} = Task.start(fn -> Process.sleep(50) end)
+
+ :ok = :gun.set_owner(conn, pid)
+
+ assert :gun.info(conn).owner == pid
end
defp receive_response(conn, ref, acc \\ "") do
diff --git a/test/http/adapter/gun_test.exs b/test/http/adapter/gun_test.exs
index ef1b4a882..a8dcbae04 100644
--- a/test/http/adapter/gun_test.exs
+++ b/test/http/adapter/gun_test.exs
@@ -7,6 +7,7 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
use Pleroma.Tests.Helpers
import ExUnit.CaptureLog
alias Pleroma.Config
+ alias Pleroma.Gun.Conn
alias Pleroma.HTTP.Adapter.Gun
alias Pleroma.Pool.Connections
@@ -72,7 +73,7 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
test "receive conn by default" do
uri = URI.parse("http://another-domain.com")
- :ok = Connections.open_conn(uri, :gun_connections)
+ :ok = Conn.open(uri, :gun_connections)
received_opts = Gun.options(uri)
assert received_opts[:close_conn] == false
@@ -81,7 +82,7 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
test "don't receive conn if receive_conn is false" do
uri = URI.parse("http://another-domain2.com")
- :ok = Connections.open_conn(uri, :gun_connections)
+ :ok = Conn.open(uri, :gun_connections)
opts = [receive_conn: false]
received_opts = Gun.options(opts, uri)
@@ -118,7 +119,7 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
test "default ssl adapter opts with connection" do
uri = URI.parse("https://some-domain.com")
- :ok = Connections.open_conn(uri, :gun_connections)
+ :ok = Conn.open(uri, :gun_connections)
opts = Gun.options(uri)
@@ -167,7 +168,7 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
describe "after_request/1" do
test "body_as not chunks" do
uri = URI.parse("http://some-domain.com")
- :ok = Connections.open_conn(uri, :gun_connections)
+ :ok = Conn.open(uri, :gun_connections)
opts = Gun.options(uri)
:ok = Gun.after_request(opts)
conn = opts[:conn]
@@ -185,7 +186,7 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
test "body_as chunks" do
uri = URI.parse("http://some-domain.com")
- :ok = Connections.open_conn(uri, :gun_connections)
+ :ok = Conn.open(uri, :gun_connections)
opts = Gun.options([body_as: :chunks], uri)
:ok = Gun.after_request(opts)
conn = opts[:conn]
@@ -205,7 +206,7 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
test "with no connection" do
uri = URI.parse("http://uniq-domain.com")
- :ok = Connections.open_conn(uri, :gun_connections)
+ :ok = Conn.open(uri, :gun_connections)
opts = Gun.options([body_as: :chunks], uri)
conn = opts[:conn]
@@ -227,7 +228,7 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
test "with ipv4" do
uri = URI.parse("http://127.0.0.1")
- :ok = Connections.open_conn(uri, :gun_connections)
+ :ok = Conn.open(uri, :gun_connections)
opts = Gun.options(uri)
send(:gun_connections, {:gun_up, opts[:conn], :http})
:ok = Gun.after_request(opts)
@@ -246,7 +247,7 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
test "with ipv6" do
uri = URI.parse("http://[2a03:2880:f10c:83:face:b00c:0:25de]")
- :ok = Connections.open_conn(uri, :gun_connections)
+ :ok = Conn.open(uri, :gun_connections)
opts = Gun.options(uri)
send(:gun_connections, {:gun_up, opts[:conn], :http})
:ok = Gun.after_request(opts)
diff --git a/test/http/connection_test.exs b/test/http/connection_test.exs
index c1ff0cc21..53ccbc9cd 100644
--- a/test/http/connection_test.exs
+++ b/test/http/connection_test.exs
@@ -124,7 +124,7 @@ defmodule Pleroma.HTTP.ConnectionTest do
uri = URI.parse("https://some-domain.com")
pid = Process.whereis(:federation)
- :ok = Pleroma.Pool.Connections.open_conn(uri, :gun_connections, genserver_pid: pid)
+ :ok = Pleroma.Gun.Conn.open(uri, :gun_connections, genserver_pid: pid)
opts = Connection.options(uri)
diff --git a/test/pool/connections_test.exs b/test/pool/connections_test.exs
index d0d711c55..f766e3b5f 100644
--- a/test/pool/connections_test.exs
+++ b/test/pool/connections_test.exs
@@ -45,7 +45,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
url = "http://some-domain.com"
key = "http:some-domain.com:80"
refute Connections.checkin(url, name)
- :ok = Connections.open_conn(url, name)
+ :ok = Conn.open(url, name)
conn = Connections.checkin(url, name)
assert is_pid(conn)
@@ -110,7 +110,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
url = "http://ですsome-domain.com"
refute Connections.checkin(url, name)
- :ok = Connections.open_conn(url, name)
+ :ok = Conn.open(url, name)
conn = Connections.checkin(url, name)
assert is_pid(conn)
@@ -139,7 +139,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
refute Connections.checkin(url, name)
- :ok = Connections.open_conn(url, name)
+ :ok = Conn.open(url, name)
conn = Connections.checkin(url, name)
assert is_pid(conn)
@@ -182,7 +182,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
refute Connections.checkin(url, name)
- :ok = Connections.open_conn(url, name)
+ :ok = Conn.open(url, name)
conn = Connections.checkin(url, name)
assert is_pid(conn)
@@ -209,7 +209,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "up and down ipv4", %{name: name} do
self = self()
url = "http://127.0.0.1"
- :ok = Connections.open_conn(url, name)
+ :ok = Conn.open(url, name)
conn = Connections.checkin(url, name)
send(name, {:gun_down, conn, nil, nil, nil})
send(name, {:gun_up, conn, nil})
@@ -229,7 +229,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "up and down ipv6", %{name: name} do
self = self()
url = "http://[2a03:2880:f10c:83:face:b00c:0:25de]"
- :ok = Connections.open_conn(url, name)
+ :ok = Conn.open(url, name)
conn = Connections.checkin(url, name)
send(name, {:gun_down, conn, nil, nil, nil})
send(name, {:gun_up, conn, nil})
@@ -253,13 +253,13 @@ defmodule Pleroma.Pool.ConnectionsTest do
https_key = "https:some-domain.com:443"
refute Connections.checkin(http_url, name)
- :ok = Connections.open_conn(http_url, name)
+ :ok = Conn.open(http_url, name)
conn = Connections.checkin(http_url, name)
assert is_pid(conn)
assert Process.alive?(conn)
refute Connections.checkin(https_url, name)
- :ok = Connections.open_conn(https_url, name)
+ :ok = Conn.open(https_url, name)
https_conn = Connections.checkin(https_url, name)
refute conn == https_conn
@@ -288,17 +288,17 @@ defmodule Pleroma.Pool.ConnectionsTest do
url = "http://gun-not-up.com"
assert capture_log(fn ->
- :ok = Connections.open_conn(url, name)
+ refute Conn.open(url, name)
refute Connections.checkin(url, name)
end) =~
- "Received error on opening connection http://gun-not-up.com: {:error, :timeout}"
+ "Received error on opening connection http://gun-not-up.com {:error, :timeout}"
end
test "process gun_down message and then gun_up", %{name: name} do
self = self()
url = "http://gun-down-and-up.com"
key = "http:gun-down-and-up.com:80"
- :ok = Connections.open_conn(url, name)
+ :ok = Conn.open(url, name)
conn = Connections.checkin(url, name)
assert is_pid(conn)
@@ -347,7 +347,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "async processes get same conn for same domain", %{name: name} do
url = "http://some-domain.com"
- :ok = Connections.open_conn(url, name)
+ :ok = Conn.open(url, name)
tasks =
for _ <- 1..5 do
@@ -381,8 +381,8 @@ defmodule Pleroma.Pool.ConnectionsTest do
self = self()
http_url = "http://some-domain.com"
https_url = "https://some-domain.com"
- :ok = Connections.open_conn(https_url, name)
- :ok = Connections.open_conn(http_url, name)
+ :ok = Conn.open(https_url, name)
+ :ok = Conn.open(http_url, name)
conn1 = Connections.checkin(https_url, name)
@@ -413,7 +413,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
:ok = Connections.checkout(conn1, self, name)
another_url = "http://another-domain.com"
- :ok = Connections.open_conn(another_url, name)
+ :ok = Conn.open(another_url, name)
conn = Connections.checkin(another_url, name)
%Connections{
@@ -437,9 +437,19 @@ defmodule Pleroma.Pool.ConnectionsTest do
Pleroma.Config.put(API, Pleroma.Gun)
end
+ test "opens connection and change owner", %{name: name} do
+ url = "https://httpbin.org"
+ :ok = Conn.open(url, name)
+ conn = Connections.checkin(url, name)
+
+ pid = Process.whereis(name)
+
+ assert :gun.info(conn).owner == pid
+ end
+
test "opens connection and reuse it on next request", %{name: name} do
url = "http://httpbin.org"
- :ok = Connections.open_conn(url, name)
+ :ok = Conn.open(url, name)
Process.sleep(250)
conn = Connections.checkin(url, name)
@@ -462,7 +472,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "opens ssl connection and reuse it on next request", %{name: name} do
url = "https://httpbin.org"
- :ok = Connections.open_conn(url, name)
+ :ok = Conn.open(url, name)
Process.sleep(1_000)
conn = Connections.checkin(url, name)
@@ -488,8 +498,8 @@ defmodule Pleroma.Pool.ConnectionsTest do
https1 = "https://www.google.com"
https2 = "https://httpbin.org"
- :ok = Connections.open_conn(https1, name)
- :ok = Connections.open_conn(https2, name)
+ :ok = Conn.open(https1, name)
+ :ok = Conn.open(https2, name)
Process.sleep(1_500)
conn = Connections.checkin(https1, name)
@@ -513,7 +523,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
:ok = Connections.checkout(conn, self, name)
http = "http://httpbin.org"
Process.sleep(1_000)
- :ok = Connections.open_conn(http, name)
+ :ok = Conn.open(http, name)
conn = Connections.checkin(http, name)
%Connections{
@@ -535,8 +545,8 @@ defmodule Pleroma.Pool.ConnectionsTest do
https1 = "https://www.google.com"
https2 = "https://httpbin.org"
- :ok = Connections.open_conn(https1, name)
- :ok = Connections.open_conn(https2, name)
+ :ok = Conn.open(https1, name)
+ :ok = Conn.open(https2, name)
Process.sleep(1_500)
Connections.checkin(https1, name)
@@ -563,7 +573,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
:ok = Connections.checkout(conn, self, name)
http = "http://httpbin.org"
- :ok = Connections.open_conn(http, name)
+ :ok = Conn.open(http, name)
Process.sleep(1_000)
conn = Connections.checkin(http, name)
@@ -587,8 +597,8 @@ defmodule Pleroma.Pool.ConnectionsTest do
https1 = "https://www.google.com"
https2 = "https://httpbin.org"
- :ok = Connections.open_conn(https1, name)
- :ok = Connections.open_conn(https2, name)
+ :ok = Conn.open(https1, name)
+ :ok = Conn.open(https2, name)
Process.sleep(1_000)
Connections.checkin(https1, name)
conn1 = Connections.checkin(https1, name)
@@ -639,8 +649,8 @@ defmodule Pleroma.Pool.ConnectionsTest do
https1 = "https://www.google.com"
https2 = "https://httpbin.org"
- :ok = Connections.open_conn(https1, name)
- :ok = Connections.open_conn(https2, name)
+ :ok = Conn.open(https1, name)
+ :ok = Conn.open(https2, name)
Process.sleep(1_500)
Connections.checkin(https1, name)
Connections.checkin(https2, name)
@@ -694,7 +704,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
} = Connections.get_state(name)
http = "http://httpbin.org"
- :ok = Connections.open_conn(http, name)
+ :ok = Conn.open(http, name)
Process.sleep(1_000)
conn = Connections.checkin(http, name)
@@ -725,7 +735,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "as ip", %{name: name} do
url = "http://proxy-string.com"
key = "http:proxy-string.com:80"
- :ok = Connections.open_conn(url, name, proxy: {{127, 0, 0, 1}, 8123})
+ :ok = Conn.open(url, name, proxy: {{127, 0, 0, 1}, 8123})
conn = Connections.checkin(url, name)
@@ -745,7 +755,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "as host", %{name: name} do
url = "http://proxy-tuple-atom.com"
- :ok = Connections.open_conn(url, name, proxy: {'localhost', 9050})
+ :ok = Conn.open(url, name, proxy: {'localhost', 9050})
conn = Connections.checkin(url, name)
%Connections{
@@ -765,7 +775,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "as ip and ssl", %{name: name} do
url = "https://proxy-string.com"
- :ok = Connections.open_conn(url, name, proxy: {{127, 0, 0, 1}, 8123})
+ :ok = Conn.open(url, name, proxy: {{127, 0, 0, 1}, 8123})
conn = Connections.checkin(url, name)
%Connections{
@@ -784,7 +794,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "as host and ssl", %{name: name} do
url = "https://proxy-tuple-atom.com"
- :ok = Connections.open_conn(url, name, proxy: {'localhost', 9050})
+ :ok = Conn.open(url, name, proxy: {'localhost', 9050})
conn = Connections.checkin(url, name)
%Connections{
@@ -804,7 +814,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "with socks type", %{name: name} do
url = "http://proxy-socks.com"
- :ok = Connections.open_conn(url, name, proxy: {:socks5, 'localhost', 1234})
+ :ok = Conn.open(url, name, proxy: {:socks5, 'localhost', 1234})
conn = Connections.checkin(url, name)
@@ -825,7 +835,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "with socks4 type and ssl", %{name: name} do
url = "https://proxy-socks.com"
- :ok = Connections.open_conn(url, name, proxy: {:socks4, 'localhost', 1234})
+ :ok = Conn.open(url, name, proxy: {:socks4, 'localhost', 1234})
conn = Connections.checkin(url, name)
@@ -892,71 +902,75 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
describe "get_unused_conns/1" do
- test "crf is equalent, sorting by reference" do
- conns = %{
- "1" => %Conn{
- conn_state: :idle,
- last_reference: now() - 1
- },
- "2" => %Conn{
- conn_state: :idle,
- last_reference: now()
- }
- }
-
- assert [{"1", _unused_conn} | _others] = Connections.get_unused_conns(conns)
+ test "crf is equalent, sorting by reference", %{name: name} do
+ Connections.add_conn(name, "1", %Conn{
+ conn_state: :idle,
+ last_reference: now() - 1
+ })
+
+ Connections.add_conn(name, "2", %Conn{
+ conn_state: :idle,
+ last_reference: now()
+ })
+
+ assert [{"1", _unused_conn} | _others] = Connections.get_unused_conns(name)
end
- test "reference is equalent, sorting by crf" do
- conns = %{
- "1" => %Conn{
- conn_state: :idle,
- crf: 1.999
- },
- "2" => %Conn{
- conn_state: :idle,
- crf: 2
- }
- }
+ test "reference is equalent, sorting by crf", %{name: name} do
+ Connections.add_conn(name, "1", %Conn{
+ conn_state: :idle,
+ crf: 1.999
+ })
+
+ Connections.add_conn(name, "2", %Conn{
+ conn_state: :idle,
+ crf: 2
+ })
- assert [{"1", _unused_conn} | _others] = Connections.get_unused_conns(conns)
+ assert [{"1", _unused_conn} | _others] = Connections.get_unused_conns(name)
end
- test "higher crf and lower reference" do
- conns = %{
- "1" => %Conn{
- conn_state: :idle,
- crf: 3,
- last_reference: now() - 1
- },
- "2" => %Conn{
- conn_state: :idle,
- crf: 2,
- last_reference: now()
- }
- }
+ test "higher crf and lower reference", %{name: name} do
+ Connections.add_conn(name, "1", %Conn{
+ conn_state: :idle,
+ crf: 3,
+ last_reference: now() - 1
+ })
+
+ Connections.add_conn(name, "2", %Conn{
+ conn_state: :idle,
+ crf: 2,
+ last_reference: now()
+ })
- assert [{"2", _unused_conn} | _others] = Connections.get_unused_conns(conns)
+ assert [{"2", _unused_conn} | _others] = Connections.get_unused_conns(name)
end
- test "lower crf and lower reference" do
- conns = %{
- "1" => %Conn{
- conn_state: :idle,
- crf: 1.99,
- last_reference: now() - 1
- },
- "2" => %Conn{
- conn_state: :idle,
- crf: 2,
- last_reference: now()
- }
- }
+ test "lower crf and lower reference", %{name: name} do
+ Connections.add_conn(name, "1", %Conn{
+ conn_state: :idle,
+ crf: 1.99,
+ last_reference: now() - 1
+ })
- assert [{"1", _unused_conn} | _others] = Connections.get_unused_conns(conns)
+ Connections.add_conn(name, "2", %Conn{
+ conn_state: :idle,
+ crf: 2,
+ last_reference: now()
+ })
+
+ assert [{"1", _unused_conn} | _others] = Connections.get_unused_conns(name)
end
end
+ test "count/1", %{name: name} do
+ assert Connections.count(name) == 0
+ Connections.add_conn(name, "1", %Conn{conn: self()})
+ assert Connections.count(name) == 1
+ Connections.remove_conn(name, "1")
+ assert Connections.count(name) == 0
+ end
+
defp now do
:os.system_time(:second)
end
--
cgit v1.2.3
From 137c600cae9869e706d10b06dea04c9249e043da Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Mon, 2 Mar 2020 10:01:07 +0300
Subject: stop connections manually
---
test/pool/connections_test.exs | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/pool/connections_test.exs b/test/pool/connections_test.exs
index f766e3b5f..0e7a118ab 100644
--- a/test/pool/connections_test.exs
+++ b/test/pool/connections_test.exs
@@ -23,11 +23,18 @@ defmodule Pleroma.Pool.ConnectionsTest do
name = :test_connections
adapter = Application.get_env(:tesla, :adapter)
Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
- on_exit(fn -> Application.put_env(:tesla, :adapter, adapter) end)
- {:ok, _pid} =
+ {:ok, pid} =
Connections.start_link({name, [max_connections: 2, receive_connection_timeout: 1_500]})
+ on_exit(fn ->
+ Application.put_env(:tesla, :adapter, adapter)
+
+ if Process.alive?(pid) do
+ GenServer.stop(name)
+ end
+ end)
+
{:ok, name: name}
end
--
cgit v1.2.3
From 4c8569d403f47957f7a5d698c595959007c8a95a Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 3 Mar 2020 12:19:29 +0300
Subject: otp_version refactor
---
test/fixtures/warnings/otp_version/error | 1 -
test/fixtures/warnings/otp_version/undefined | 1 -
test/otp_version_test.exs | 42 ++++++++--------------------
3 files changed, 11 insertions(+), 33 deletions(-)
delete mode 100644 test/fixtures/warnings/otp_version/error
delete mode 100644 test/fixtures/warnings/otp_version/undefined
(limited to 'test')
diff --git a/test/fixtures/warnings/otp_version/error b/test/fixtures/warnings/otp_version/error
deleted file mode 100644
index 8fdd954df..000000000
--- a/test/fixtures/warnings/otp_version/error
+++ /dev/null
@@ -1 +0,0 @@
-22
\ No newline at end of file
diff --git a/test/fixtures/warnings/otp_version/undefined b/test/fixtures/warnings/otp_version/undefined
deleted file mode 100644
index 66dc9051d..000000000
--- a/test/fixtures/warnings/otp_version/undefined
+++ /dev/null
@@ -1 +0,0 @@
-undefined
\ No newline at end of file
diff --git a/test/otp_version_test.exs b/test/otp_version_test.exs
index f26b90f61..af278cc72 100644
--- a/test/otp_version_test.exs
+++ b/test/otp_version_test.exs
@@ -1,58 +1,38 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
defmodule Pleroma.OTPVersionTest do
use ExUnit.Case, async: true
alias Pleroma.OTPVersion
- describe "get_and_check_version/2" do
+ describe "check/1" do
test "22.4" do
- assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
- "test/fixtures/warnings/otp_version/22.4"
- ]) == :ok
+ assert OTPVersion.check(["test/fixtures/warnings/otp_version/22.4"]) == :ok
end
test "22.1" do
- assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
- "test/fixtures/warnings/otp_version/22.1"
- ]) == {:error, "22.1"}
+ assert OTPVersion.check(["test/fixtures/warnings/otp_version/22.1"]) == {:error, "22.1"}
end
test "21.1" do
- assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
- "test/fixtures/warnings/otp_version/21.1"
- ]) == {:error, "21.1"}
+ assert OTPVersion.check(["test/fixtures/warnings/otp_version/21.1"]) == {:error, "21.1"}
end
test "23.0" do
- assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
- "test/fixtures/warnings/otp_version/23.0"
- ]) == :ok
- end
-
- test "undefined" do
- assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
- "test/fixtures/warnings/otp_version/undefined"
- ]) == :undefined
- end
-
- test "not parsable" do
- assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
- "test/fixtures/warnings/otp_version/error"
- ]) == :undefined
+ assert OTPVersion.check(["test/fixtures/warnings/otp_version/23.0"]) == :ok
end
test "with non existance file" do
- assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, [
+ assert OTPVersion.check([
"test/fixtures/warnings/otp_version/non-exising",
"test/fixtures/warnings/otp_version/22.4"
]) == :ok
end
test "empty paths" do
- assert OTPVersion.get_and_check_version(Tesla.Adapter.Gun, []) == :undefined
- end
-
- test "another adapter" do
- assert OTPVersion.get_and_check_version(Tesla.Adapter.Hackney, []) == :ok
+ assert OTPVersion.check([]) == :undefined
end
end
end
--
cgit v1.2.3
From 28ed4b41d03c6a137d198b8c67fb081c7ebfbbc6 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 3 Mar 2020 13:05:28 +0300
Subject: naming for checkin from pool timeout
---
test/pool/connections_test.exs | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/pool/connections_test.exs b/test/pool/connections_test.exs
index 0e7a118ab..a084f31b9 100644
--- a/test/pool/connections_test.exs
+++ b/test/pool/connections_test.exs
@@ -24,8 +24,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
adapter = Application.get_env(:tesla, :adapter)
Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
- {:ok, pid} =
- Connections.start_link({name, [max_connections: 2, receive_connection_timeout: 1_500]})
+ {:ok, pid} = Connections.start_link({name, [max_connections: 2, checkin_timeout: 1_500]})
on_exit(fn ->
Application.put_env(:tesla, :adapter, adapter)
--
cgit v1.2.3
From ee8071f0d5a8a53f6a9ae635d6ea57ce8576e21b Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 3 Mar 2020 15:12:09 +0300
Subject: removing unused method
---
test/http/request_builder_test.exs | 17 -----------------
1 file changed, 17 deletions(-)
(limited to 'test')
diff --git a/test/http/request_builder_test.exs b/test/http/request_builder_test.exs
index f87ca11d3..f6eeac6c0 100644
--- a/test/http/request_builder_test.exs
+++ b/test/http/request_builder_test.exs
@@ -36,23 +36,6 @@ defmodule Pleroma.HTTP.RequestBuilderTest do
end
end
- describe "add_optional_params/3" do
- test "don't add if keyword is empty" do
- assert RequestBuilder.add_optional_params(%{}, %{}, []) == %{}
- end
-
- test "add query parameter" do
- assert RequestBuilder.add_optional_params(
- %Request{},
- %{query: :query, body: :body, another: :val},
- [
- {:query, "param1=val1¶m2=val2"},
- {:body, "some body"}
- ]
- ) == %Request{query: "param1=val1¶m2=val2", body: "some body"}
- end
- end
-
describe "add_param/4" do
test "add file parameter" do
%Request{
--
cgit v1.2.3
From e605e79df9761cef3d9f93c489dd4618c6b70eda Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 3 Mar 2020 15:44:13 +0300
Subject: simplification of formatting host method
case for format_proxy method
---
test/http/adapter/gun_test.exs | 21 ++++++++++++++++++++-
test/http/adapter_test.exs | 40 +---------------------------------------
2 files changed, 21 insertions(+), 40 deletions(-)
(limited to 'test')
diff --git a/test/http/adapter/gun_test.exs b/test/http/adapter/gun_test.exs
index a8dcbae04..a05471ac6 100644
--- a/test/http/adapter/gun_test.exs
+++ b/test/http/adapter/gun_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTP.Adapter.GunTest do
@@ -264,4 +264,23 @@ defmodule Pleroma.HTTP.Adapter.GunTest do
} = Connections.get_state(:gun_connections)
end
end
+
+ describe "format_host/1" do
+ test "with domain" do
+ assert Gun.format_host("example.com") == 'example.com'
+ end
+
+ test "with idna domain" do
+ assert Gun.format_host("ですexample.com") == 'xn--example-183fne.com'
+ end
+
+ test "with ipv4" do
+ assert Gun.format_host("127.0.0.1") == '127.0.0.1'
+ end
+
+ test "with ipv6" do
+ assert Gun.format_host("2a03:2880:f10c:83:face:b00c:0:25de") ==
+ '2a03:2880:f10c:83:face:b00c:0:25de'
+ end
+ end
end
diff --git a/test/http/adapter_test.exs b/test/http/adapter_test.exs
index 37e47dabe..4c805837c 100644
--- a/test/http/adapter_test.exs
+++ b/test/http/adapter_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTP.AdapterTest do
@@ -7,44 +7,6 @@ defmodule Pleroma.HTTP.AdapterTest do
alias Pleroma.HTTP.Adapter
- describe "domain_or_ip/1" do
- test "with domain" do
- assert Adapter.domain_or_ip("example.com") == {:domain, 'example.com'}
- end
-
- test "with idna domain" do
- assert Adapter.domain_or_ip("ですexample.com") == {:domain, 'xn--example-183fne.com'}
- end
-
- test "with ipv4" do
- assert Adapter.domain_or_ip("127.0.0.1") == {:ip, {127, 0, 0, 1}}
- end
-
- test "with ipv6" do
- assert Adapter.domain_or_ip("2a03:2880:f10c:83:face:b00c:0:25de") ==
- {:ip, {10_755, 10_368, 61_708, 131, 64_206, 45_068, 0, 9_694}}
- end
- end
-
- describe "domain_or_fallback/1" do
- test "with domain" do
- assert Adapter.domain_or_fallback("example.com") == 'example.com'
- end
-
- test "with idna domain" do
- assert Adapter.domain_or_fallback("ですexample.com") == 'xn--example-183fne.com'
- end
-
- test "with ipv4" do
- assert Adapter.domain_or_fallback("127.0.0.1") == '127.0.0.1'
- end
-
- test "with ipv6" do
- assert Adapter.domain_or_fallback("2a03:2880:f10c:83:face:b00c:0:25de") ==
- '2a03:2880:f10c:83:face:b00c:0:25de'
- end
- end
-
describe "format_proxy/1" do
test "with nil" do
assert Adapter.format_proxy(nil) == nil
--
cgit v1.2.3
From 7c0ed9302cb13ab44c1bf18017538315dcd0ce2e Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 3 Mar 2020 16:46:20 +0300
Subject: unnecessary mock
---
test/notification_test.exs | 7 -------
1 file changed, 7 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 1c60f6866..56a581810 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -649,13 +649,6 @@ defmodule Pleroma.NotificationTest do
"object" => remote_user.ap_id
}
- remote_user_url = remote_user.ap_id
-
- Tesla.Mock.mock(fn
- %{method: :get, url: ^remote_user_url} ->
- %Tesla.Env{status: 404, body: ""}
- end)
-
{:ok, _delete_activity} = Transmogrifier.handle_incoming(delete_user_message)
ObanHelpers.perform_all()
--
cgit v1.2.3
From 3723d723652b747b00fc26054101c15e39a5af18 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 3 Mar 2020 17:32:59 +0300
Subject: proxy parse tests fix
---
test/http/connection_test.exs | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/http/connection_test.exs b/test/http/connection_test.exs
index 53ccbc9cd..37de11e7a 100644
--- a/test/http/connection_test.exs
+++ b/test/http/connection_test.exs
@@ -51,31 +51,31 @@ defmodule Pleroma.HTTP.ConnectionTest do
describe "parse_proxy/1 errors" do
test "ip without port" do
capture_log(fn ->
- assert Connection.parse_proxy("127.0.0.1") == {:error, :error_parsing_proxy}
+ assert Connection.parse_proxy("127.0.0.1") == {:error, :invalid_proxy}
end) =~ "parsing proxy fail \"127.0.0.1\""
end
test "host without port" do
capture_log(fn ->
- assert Connection.parse_proxy("localhost") == {:error, :error_parsing_proxy}
+ assert Connection.parse_proxy("localhost") == {:error, :invalid_proxy}
end) =~ "parsing proxy fail \"localhost\""
end
test "host with bad port" do
capture_log(fn ->
- assert Connection.parse_proxy("localhost:port") == {:error, :error_parsing_port_in_proxy}
+ assert Connection.parse_proxy("localhost:port") == {:error, :invalid_proxy_port}
end) =~ "parsing port in proxy fail \"localhost:port\""
end
test "ip with bad port" do
capture_log(fn ->
- assert Connection.parse_proxy("127.0.0.1:15.9") == {:error, :error_parsing_port_in_proxy}
+ assert Connection.parse_proxy("127.0.0.1:15.9") == {:error, :invalid_proxy_port}
end) =~ "parsing port in proxy fail \"127.0.0.1:15.9\""
end
test "as tuple without port" do
capture_log(fn ->
- assert Connection.parse_proxy({:socks5, :localhost}) == {:error, :error_parsing_proxy}
+ assert Connection.parse_proxy({:socks5, :localhost}) == {:error, :invalid_proxy}
end) =~ "parsing proxy fail {:socks5, :localhost}"
end
--
cgit v1.2.3
From f98ee730f01de528797e38f27964b69a465662c4 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 3 Mar 2020 18:53:44 +0300
Subject: adapter renaming to adapter_helper
---
test/http/adapter/gun_test.exs | 286 ------------------------------
test/http/adapter/hackney_test.exs | 54 ------
test/http/adapter_helper/gun_test.exs | 286 ++++++++++++++++++++++++++++++
test/http/adapter_helper/hackney_test.exs | 54 ++++++
test/http/adapter_helper_test.exs | 28 +++
test/http/adapter_test.exs | 27 ---
6 files changed, 368 insertions(+), 367 deletions(-)
delete mode 100644 test/http/adapter/gun_test.exs
delete mode 100644 test/http/adapter/hackney_test.exs
create mode 100644 test/http/adapter_helper/gun_test.exs
create mode 100644 test/http/adapter_helper/hackney_test.exs
create mode 100644 test/http/adapter_helper_test.exs
delete mode 100644 test/http/adapter_test.exs
(limited to 'test')
diff --git a/test/http/adapter/gun_test.exs b/test/http/adapter/gun_test.exs
deleted file mode 100644
index a05471ac6..000000000
--- a/test/http/adapter/gun_test.exs
+++ /dev/null
@@ -1,286 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.HTTP.Adapter.GunTest do
- use ExUnit.Case, async: true
- use Pleroma.Tests.Helpers
- import ExUnit.CaptureLog
- alias Pleroma.Config
- alias Pleroma.Gun.Conn
- alias Pleroma.HTTP.Adapter.Gun
- alias Pleroma.Pool.Connections
-
- setup_all do
- {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.Gun.API.Mock)
- :ok
- end
-
- describe "options/1" do
- clear_config([:http, :adapter]) do
- Config.put([:http, :adapter], a: 1, b: 2)
- end
-
- test "https url with default port" do
- uri = URI.parse("https://example.com")
-
- opts = Gun.options(uri)
- assert opts[:certificates_verification]
- tls_opts = opts[:tls_opts]
- assert tls_opts[:verify] == :verify_peer
- assert tls_opts[:depth] == 20
- assert tls_opts[:reuse_sessions] == false
-
- assert tls_opts[:verify_fun] ==
- {&:ssl_verify_hostname.verify_fun/3, [check_hostname: 'example.com']}
-
- assert File.exists?(tls_opts[:cacertfile])
-
- assert opts[:original] == "example.com:443"
- end
-
- test "https ipv4 with default port" do
- uri = URI.parse("https://127.0.0.1")
-
- opts = Gun.options(uri)
-
- assert opts[:tls_opts][:verify_fun] ==
- {&:ssl_verify_hostname.verify_fun/3, [check_hostname: '127.0.0.1']}
-
- assert opts[:original] == "127.0.0.1:443"
- end
-
- test "https ipv6 with default port" do
- uri = URI.parse("https://[2a03:2880:f10c:83:face:b00c:0:25de]")
-
- opts = Gun.options(uri)
-
- assert opts[:tls_opts][:verify_fun] ==
- {&:ssl_verify_hostname.verify_fun/3,
- [check_hostname: '2a03:2880:f10c:83:face:b00c:0:25de']}
-
- assert opts[:original] == "2a03:2880:f10c:83:face:b00c:0:25de:443"
- end
-
- test "https url with non standart port" do
- uri = URI.parse("https://example.com:115")
-
- opts = Gun.options(uri)
-
- assert opts[:certificates_verification]
- assert opts[:transport] == :tls
- end
-
- test "receive conn by default" do
- uri = URI.parse("http://another-domain.com")
- :ok = Conn.open(uri, :gun_connections)
-
- received_opts = Gun.options(uri)
- assert received_opts[:close_conn] == false
- assert is_pid(received_opts[:conn])
- end
-
- test "don't receive conn if receive_conn is false" do
- uri = URI.parse("http://another-domain2.com")
- :ok = Conn.open(uri, :gun_connections)
-
- opts = [receive_conn: false]
- received_opts = Gun.options(opts, uri)
- assert received_opts[:close_conn] == nil
- assert received_opts[:conn] == nil
- end
-
- test "get conn on next request" do
- level = Application.get_env(:logger, :level)
- Logger.configure(level: :debug)
- on_exit(fn -> Logger.configure(level: level) end)
- uri = URI.parse("http://some-domain2.com")
-
- assert capture_log(fn ->
- opts = Gun.options(uri)
-
- assert opts[:conn] == nil
- assert opts[:close_conn] == nil
- end) =~
- "Gun connections pool checkin was not successful. Trying to open conn for next request."
-
- opts = Gun.options(uri)
-
- assert is_pid(opts[:conn])
- assert opts[:close_conn] == false
- end
-
- test "merges with defaul http adapter config" do
- defaults = Gun.options(URI.parse("https://example.com"))
- assert Keyword.has_key?(defaults, :a)
- assert Keyword.has_key?(defaults, :b)
- end
-
- test "default ssl adapter opts with connection" do
- uri = URI.parse("https://some-domain.com")
-
- :ok = Conn.open(uri, :gun_connections)
-
- opts = Gun.options(uri)
-
- assert opts[:certificates_verification]
- tls_opts = opts[:tls_opts]
- assert tls_opts[:verify] == :verify_peer
- assert tls_opts[:depth] == 20
- assert tls_opts[:reuse_sessions] == false
-
- assert opts[:original] == "some-domain.com:443"
- assert opts[:close_conn] == false
- assert is_pid(opts[:conn])
- end
-
- test "parses string proxy host & port" do
- proxy = Config.get([:http, :proxy_url])
- Config.put([:http, :proxy_url], "localhost:8123")
- on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
-
- uri = URI.parse("https://some-domain.com")
- opts = Gun.options([receive_conn: false], uri)
- assert opts[:proxy] == {'localhost', 8123}
- end
-
- test "parses tuple proxy scheme host and port" do
- proxy = Config.get([:http, :proxy_url])
- Config.put([:http, :proxy_url], {:socks, 'localhost', 1234})
- on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
-
- uri = URI.parse("https://some-domain.com")
- opts = Gun.options([receive_conn: false], uri)
- assert opts[:proxy] == {:socks, 'localhost', 1234}
- end
-
- test "passed opts have more weight than defaults" do
- proxy = Config.get([:http, :proxy_url])
- Config.put([:http, :proxy_url], {:socks5, 'localhost', 1234})
- on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
- uri = URI.parse("https://some-domain.com")
- opts = Gun.options([receive_conn: false, proxy: {'example.com', 4321}], uri)
-
- assert opts[:proxy] == {'example.com', 4321}
- end
- end
-
- describe "after_request/1" do
- test "body_as not chunks" do
- uri = URI.parse("http://some-domain.com")
- :ok = Conn.open(uri, :gun_connections)
- opts = Gun.options(uri)
- :ok = Gun.after_request(opts)
- conn = opts[:conn]
-
- assert %Connections{
- conns: %{
- "http:some-domain.com:80" => %Pleroma.Gun.Conn{
- conn: ^conn,
- conn_state: :idle,
- used_by: []
- }
- }
- } = Connections.get_state(:gun_connections)
- end
-
- test "body_as chunks" do
- uri = URI.parse("http://some-domain.com")
- :ok = Conn.open(uri, :gun_connections)
- opts = Gun.options([body_as: :chunks], uri)
- :ok = Gun.after_request(opts)
- conn = opts[:conn]
- self = self()
-
- assert %Connections{
- conns: %{
- "http:some-domain.com:80" => %Pleroma.Gun.Conn{
- conn: ^conn,
- conn_state: :active,
- used_by: [{^self, _}]
- }
- }
- } = Connections.get_state(:gun_connections)
- end
-
- test "with no connection" do
- uri = URI.parse("http://uniq-domain.com")
-
- :ok = Conn.open(uri, :gun_connections)
-
- opts = Gun.options([body_as: :chunks], uri)
- conn = opts[:conn]
- opts = Keyword.delete(opts, :conn)
- self = self()
-
- :ok = Gun.after_request(opts)
-
- assert %Connections{
- conns: %{
- "http:uniq-domain.com:80" => %Pleroma.Gun.Conn{
- conn: ^conn,
- conn_state: :active,
- used_by: [{^self, _}]
- }
- }
- } = Connections.get_state(:gun_connections)
- end
-
- test "with ipv4" do
- uri = URI.parse("http://127.0.0.1")
- :ok = Conn.open(uri, :gun_connections)
- opts = Gun.options(uri)
- send(:gun_connections, {:gun_up, opts[:conn], :http})
- :ok = Gun.after_request(opts)
- conn = opts[:conn]
-
- assert %Connections{
- conns: %{
- "http:127.0.0.1:80" => %Pleroma.Gun.Conn{
- conn: ^conn,
- conn_state: :idle,
- used_by: []
- }
- }
- } = Connections.get_state(:gun_connections)
- end
-
- test "with ipv6" do
- uri = URI.parse("http://[2a03:2880:f10c:83:face:b00c:0:25de]")
- :ok = Conn.open(uri, :gun_connections)
- opts = Gun.options(uri)
- send(:gun_connections, {:gun_up, opts[:conn], :http})
- :ok = Gun.after_request(opts)
- conn = opts[:conn]
-
- assert %Connections{
- conns: %{
- "http:2a03:2880:f10c:83:face:b00c:0:25de:80" => %Pleroma.Gun.Conn{
- conn: ^conn,
- conn_state: :idle,
- used_by: []
- }
- }
- } = Connections.get_state(:gun_connections)
- end
- end
-
- describe "format_host/1" do
- test "with domain" do
- assert Gun.format_host("example.com") == 'example.com'
- end
-
- test "with idna domain" do
- assert Gun.format_host("ですexample.com") == 'xn--example-183fne.com'
- end
-
- test "with ipv4" do
- assert Gun.format_host("127.0.0.1") == '127.0.0.1'
- end
-
- test "with ipv6" do
- assert Gun.format_host("2a03:2880:f10c:83:face:b00c:0:25de") ==
- '2a03:2880:f10c:83:face:b00c:0:25de'
- end
- end
-end
diff --git a/test/http/adapter/hackney_test.exs b/test/http/adapter/hackney_test.exs
deleted file mode 100644
index 35cb58125..000000000
--- a/test/http/adapter/hackney_test.exs
+++ /dev/null
@@ -1,54 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.HTTP.Adapter.HackneyTest do
- use ExUnit.Case
- use Pleroma.Tests.Helpers
-
- alias Pleroma.Config
- alias Pleroma.HTTP.Adapter.Hackney
-
- setup_all do
- uri = URI.parse("http://domain.com")
- {:ok, uri: uri}
- end
-
- describe "options/2" do
- clear_config([:http, :adapter]) do
- Config.put([:http, :adapter], a: 1, b: 2)
- end
-
- test "add proxy and opts from config", %{uri: uri} do
- proxy = Config.get([:http, :proxy_url])
- Config.put([:http, :proxy_url], "localhost:8123")
- on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
-
- opts = Hackney.options(uri)
-
- assert opts[:a] == 1
- assert opts[:b] == 2
- assert opts[:proxy] == "localhost:8123"
- end
-
- test "respect connection opts and no proxy", %{uri: uri} do
- opts = Hackney.options([a: 2, b: 1], uri)
-
- assert opts[:a] == 2
- assert opts[:b] == 1
- refute Keyword.has_key?(opts, :proxy)
- end
-
- test "add opts for https" do
- uri = URI.parse("https://domain.com")
-
- opts = Hackney.options(uri)
-
- assert opts[:ssl_options] == [
- partial_chain: &:hackney_connect.partial_chain/1,
- versions: [:tlsv1, :"tlsv1.1", :"tlsv1.2"],
- server_name_indication: 'domain.com'
- ]
- end
- end
-end
diff --git a/test/http/adapter_helper/gun_test.exs b/test/http/adapter_helper/gun_test.exs
new file mode 100644
index 000000000..bc7e3f0e0
--- /dev/null
+++ b/test/http/adapter_helper/gun_test.exs
@@ -0,0 +1,286 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.HTTP.AdapterHelper.GunTest do
+ use ExUnit.Case, async: true
+ use Pleroma.Tests.Helpers
+ import ExUnit.CaptureLog
+ alias Pleroma.Config
+ alias Pleroma.Gun.Conn
+ alias Pleroma.HTTP.AdapterHelper.Gun
+ alias Pleroma.Pool.Connections
+
+ setup_all do
+ {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.Gun.API.Mock)
+ :ok
+ end
+
+ describe "options/1" do
+ clear_config([:http, :adapter]) do
+ Config.put([:http, :adapter], a: 1, b: 2)
+ end
+
+ test "https url with default port" do
+ uri = URI.parse("https://example.com")
+
+ opts = Gun.options(uri)
+ assert opts[:certificates_verification]
+ tls_opts = opts[:tls_opts]
+ assert tls_opts[:verify] == :verify_peer
+ assert tls_opts[:depth] == 20
+ assert tls_opts[:reuse_sessions] == false
+
+ assert tls_opts[:verify_fun] ==
+ {&:ssl_verify_hostname.verify_fun/3, [check_hostname: 'example.com']}
+
+ assert File.exists?(tls_opts[:cacertfile])
+
+ assert opts[:original] == "example.com:443"
+ end
+
+ test "https ipv4 with default port" do
+ uri = URI.parse("https://127.0.0.1")
+
+ opts = Gun.options(uri)
+
+ assert opts[:tls_opts][:verify_fun] ==
+ {&:ssl_verify_hostname.verify_fun/3, [check_hostname: '127.0.0.1']}
+
+ assert opts[:original] == "127.0.0.1:443"
+ end
+
+ test "https ipv6 with default port" do
+ uri = URI.parse("https://[2a03:2880:f10c:83:face:b00c:0:25de]")
+
+ opts = Gun.options(uri)
+
+ assert opts[:tls_opts][:verify_fun] ==
+ {&:ssl_verify_hostname.verify_fun/3,
+ [check_hostname: '2a03:2880:f10c:83:face:b00c:0:25de']}
+
+ assert opts[:original] == "2a03:2880:f10c:83:face:b00c:0:25de:443"
+ end
+
+ test "https url with non standart port" do
+ uri = URI.parse("https://example.com:115")
+
+ opts = Gun.options(uri)
+
+ assert opts[:certificates_verification]
+ assert opts[:transport] == :tls
+ end
+
+ test "receive conn by default" do
+ uri = URI.parse("http://another-domain.com")
+ :ok = Conn.open(uri, :gun_connections)
+
+ received_opts = Gun.options(uri)
+ assert received_opts[:close_conn] == false
+ assert is_pid(received_opts[:conn])
+ end
+
+ test "don't receive conn if receive_conn is false" do
+ uri = URI.parse("http://another-domain2.com")
+ :ok = Conn.open(uri, :gun_connections)
+
+ opts = [receive_conn: false]
+ received_opts = Gun.options(opts, uri)
+ assert received_opts[:close_conn] == nil
+ assert received_opts[:conn] == nil
+ end
+
+ test "get conn on next request" do
+ level = Application.get_env(:logger, :level)
+ Logger.configure(level: :debug)
+ on_exit(fn -> Logger.configure(level: level) end)
+ uri = URI.parse("http://some-domain2.com")
+
+ assert capture_log(fn ->
+ opts = Gun.options(uri)
+
+ assert opts[:conn] == nil
+ assert opts[:close_conn] == nil
+ end) =~
+ "Gun connections pool checkin was not successful. Trying to open conn for next request."
+
+ opts = Gun.options(uri)
+
+ assert is_pid(opts[:conn])
+ assert opts[:close_conn] == false
+ end
+
+ test "merges with defaul http adapter config" do
+ defaults = Gun.options(URI.parse("https://example.com"))
+ assert Keyword.has_key?(defaults, :a)
+ assert Keyword.has_key?(defaults, :b)
+ end
+
+ test "default ssl adapter opts with connection" do
+ uri = URI.parse("https://some-domain.com")
+
+ :ok = Conn.open(uri, :gun_connections)
+
+ opts = Gun.options(uri)
+
+ assert opts[:certificates_verification]
+ tls_opts = opts[:tls_opts]
+ assert tls_opts[:verify] == :verify_peer
+ assert tls_opts[:depth] == 20
+ assert tls_opts[:reuse_sessions] == false
+
+ assert opts[:original] == "some-domain.com:443"
+ assert opts[:close_conn] == false
+ assert is_pid(opts[:conn])
+ end
+
+ test "parses string proxy host & port" do
+ proxy = Config.get([:http, :proxy_url])
+ Config.put([:http, :proxy_url], "localhost:8123")
+ on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
+
+ uri = URI.parse("https://some-domain.com")
+ opts = Gun.options([receive_conn: false], uri)
+ assert opts[:proxy] == {'localhost', 8123}
+ end
+
+ test "parses tuple proxy scheme host and port" do
+ proxy = Config.get([:http, :proxy_url])
+ Config.put([:http, :proxy_url], {:socks, 'localhost', 1234})
+ on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
+
+ uri = URI.parse("https://some-domain.com")
+ opts = Gun.options([receive_conn: false], uri)
+ assert opts[:proxy] == {:socks, 'localhost', 1234}
+ end
+
+ test "passed opts have more weight than defaults" do
+ proxy = Config.get([:http, :proxy_url])
+ Config.put([:http, :proxy_url], {:socks5, 'localhost', 1234})
+ on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
+ uri = URI.parse("https://some-domain.com")
+ opts = Gun.options([receive_conn: false, proxy: {'example.com', 4321}], uri)
+
+ assert opts[:proxy] == {'example.com', 4321}
+ end
+ end
+
+ describe "after_request/1" do
+ test "body_as not chunks" do
+ uri = URI.parse("http://some-domain.com")
+ :ok = Conn.open(uri, :gun_connections)
+ opts = Gun.options(uri)
+ :ok = Gun.after_request(opts)
+ conn = opts[:conn]
+
+ assert %Connections{
+ conns: %{
+ "http:some-domain.com:80" => %Pleroma.Gun.Conn{
+ conn: ^conn,
+ conn_state: :idle,
+ used_by: []
+ }
+ }
+ } = Connections.get_state(:gun_connections)
+ end
+
+ test "body_as chunks" do
+ uri = URI.parse("http://some-domain.com")
+ :ok = Conn.open(uri, :gun_connections)
+ opts = Gun.options([body_as: :chunks], uri)
+ :ok = Gun.after_request(opts)
+ conn = opts[:conn]
+ self = self()
+
+ assert %Connections{
+ conns: %{
+ "http:some-domain.com:80" => %Pleroma.Gun.Conn{
+ conn: ^conn,
+ conn_state: :active,
+ used_by: [{^self, _}]
+ }
+ }
+ } = Connections.get_state(:gun_connections)
+ end
+
+ test "with no connection" do
+ uri = URI.parse("http://uniq-domain.com")
+
+ :ok = Conn.open(uri, :gun_connections)
+
+ opts = Gun.options([body_as: :chunks], uri)
+ conn = opts[:conn]
+ opts = Keyword.delete(opts, :conn)
+ self = self()
+
+ :ok = Gun.after_request(opts)
+
+ assert %Connections{
+ conns: %{
+ "http:uniq-domain.com:80" => %Pleroma.Gun.Conn{
+ conn: ^conn,
+ conn_state: :active,
+ used_by: [{^self, _}]
+ }
+ }
+ } = Connections.get_state(:gun_connections)
+ end
+
+ test "with ipv4" do
+ uri = URI.parse("http://127.0.0.1")
+ :ok = Conn.open(uri, :gun_connections)
+ opts = Gun.options(uri)
+ send(:gun_connections, {:gun_up, opts[:conn], :http})
+ :ok = Gun.after_request(opts)
+ conn = opts[:conn]
+
+ assert %Connections{
+ conns: %{
+ "http:127.0.0.1:80" => %Pleroma.Gun.Conn{
+ conn: ^conn,
+ conn_state: :idle,
+ used_by: []
+ }
+ }
+ } = Connections.get_state(:gun_connections)
+ end
+
+ test "with ipv6" do
+ uri = URI.parse("http://[2a03:2880:f10c:83:face:b00c:0:25de]")
+ :ok = Conn.open(uri, :gun_connections)
+ opts = Gun.options(uri)
+ send(:gun_connections, {:gun_up, opts[:conn], :http})
+ :ok = Gun.after_request(opts)
+ conn = opts[:conn]
+
+ assert %Connections{
+ conns: %{
+ "http:2a03:2880:f10c:83:face:b00c:0:25de:80" => %Pleroma.Gun.Conn{
+ conn: ^conn,
+ conn_state: :idle,
+ used_by: []
+ }
+ }
+ } = Connections.get_state(:gun_connections)
+ end
+ end
+
+ describe "format_host/1" do
+ test "with domain" do
+ assert Gun.format_host("example.com") == 'example.com'
+ end
+
+ test "with idna domain" do
+ assert Gun.format_host("ですexample.com") == 'xn--example-183fne.com'
+ end
+
+ test "with ipv4" do
+ assert Gun.format_host("127.0.0.1") == '127.0.0.1'
+ end
+
+ test "with ipv6" do
+ assert Gun.format_host("2a03:2880:f10c:83:face:b00c:0:25de") ==
+ '2a03:2880:f10c:83:face:b00c:0:25de'
+ end
+ end
+end
diff --git a/test/http/adapter_helper/hackney_test.exs b/test/http/adapter_helper/hackney_test.exs
new file mode 100644
index 000000000..82f5a7883
--- /dev/null
+++ b/test/http/adapter_helper/hackney_test.exs
@@ -0,0 +1,54 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.HTTP.AdapterHelper.HackneyTest do
+ use ExUnit.Case
+ use Pleroma.Tests.Helpers
+
+ alias Pleroma.Config
+ alias Pleroma.HTTP.AdapterHelper.Hackney
+
+ setup_all do
+ uri = URI.parse("http://domain.com")
+ {:ok, uri: uri}
+ end
+
+ describe "options/2" do
+ clear_config([:http, :adapter]) do
+ Config.put([:http, :adapter], a: 1, b: 2)
+ end
+
+ test "add proxy and opts from config", %{uri: uri} do
+ proxy = Config.get([:http, :proxy_url])
+ Config.put([:http, :proxy_url], "localhost:8123")
+ on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
+
+ opts = Hackney.options(uri)
+
+ assert opts[:a] == 1
+ assert opts[:b] == 2
+ assert opts[:proxy] == "localhost:8123"
+ end
+
+ test "respect connection opts and no proxy", %{uri: uri} do
+ opts = Hackney.options([a: 2, b: 1], uri)
+
+ assert opts[:a] == 2
+ assert opts[:b] == 1
+ refute Keyword.has_key?(opts, :proxy)
+ end
+
+ test "add opts for https" do
+ uri = URI.parse("https://domain.com")
+
+ opts = Hackney.options(uri)
+
+ assert opts[:ssl_options] == [
+ partial_chain: &:hackney_connect.partial_chain/1,
+ versions: [:tlsv1, :"tlsv1.1", :"tlsv1.2"],
+ server_name_indication: 'domain.com'
+ ]
+ end
+ end
+end
diff --git a/test/http/adapter_helper_test.exs b/test/http/adapter_helper_test.exs
new file mode 100644
index 000000000..24d501ad5
--- /dev/null
+++ b/test/http/adapter_helper_test.exs
@@ -0,0 +1,28 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.HTTP.AdapterHelperTest do
+ use ExUnit.Case, async: true
+
+ alias Pleroma.HTTP.AdapterHelper
+
+ describe "format_proxy/1" do
+ test "with nil" do
+ assert AdapterHelper.format_proxy(nil) == nil
+ end
+
+ test "with string" do
+ assert AdapterHelper.format_proxy("127.0.0.1:8123") == {{127, 0, 0, 1}, 8123}
+ end
+
+ test "localhost with port" do
+ assert AdapterHelper.format_proxy("localhost:8123") == {'localhost', 8123}
+ end
+
+ test "tuple" do
+ assert AdapterHelper.format_proxy({:socks4, :localhost, 9050}) ==
+ {:socks4, 'localhost', 9050}
+ end
+ end
+end
diff --git a/test/http/adapter_test.exs b/test/http/adapter_test.exs
deleted file mode 100644
index 4c805837c..000000000
--- a/test/http/adapter_test.exs
+++ /dev/null
@@ -1,27 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.HTTP.AdapterTest do
- use ExUnit.Case, async: true
-
- alias Pleroma.HTTP.Adapter
-
- describe "format_proxy/1" do
- test "with nil" do
- assert Adapter.format_proxy(nil) == nil
- end
-
- test "with string" do
- assert Adapter.format_proxy("127.0.0.1:8123") == {{127, 0, 0, 1}, 8123}
- end
-
- test "localhost with port" do
- assert Adapter.format_proxy("localhost:8123") == {'localhost', 8123}
- end
-
- test "tuple" do
- assert Adapter.format_proxy({:socks4, :localhost, 9050}) == {:socks4, 'localhost', 9050}
- end
- end
-end
--
cgit v1.2.3
From 23f407bf093723344e63eba6a63f5cd58aa7313e Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 3 Mar 2020 18:57:16 +0300
Subject: don't test gun itself
---
test/gun/gun_test.exs | 39 ---------------------------------------
1 file changed, 39 deletions(-)
delete mode 100644 test/gun/gun_test.exs
(limited to 'test')
diff --git a/test/gun/gun_test.exs b/test/gun/gun_test.exs
deleted file mode 100644
index 9f3e0f938..000000000
--- a/test/gun/gun_test.exs
+++ /dev/null
@@ -1,39 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.GunTest do
- use ExUnit.Case
- alias Pleroma.Gun
-
- @moduletag :integration
-
- test "opens connection and receive response" do
- {:ok, conn} = Gun.open('httpbin.org', 443)
- assert is_pid(conn)
- {:ok, _protocol} = Gun.await_up(conn)
- ref = :gun.get(conn, '/get?a=b&c=d')
- assert is_reference(ref)
-
- assert {:response, :nofin, 200, _} = Gun.await(conn, ref)
- assert json = receive_response(conn, ref)
-
- assert %{"args" => %{"a" => "b", "c" => "d"}} = Jason.decode!(json)
-
- {:ok, pid} = Task.start(fn -> Process.sleep(50) end)
-
- :ok = :gun.set_owner(conn, pid)
-
- assert :gun.info(conn).owner == pid
- end
-
- defp receive_response(conn, ref, acc \\ "") do
- case Gun.await(conn, ref) do
- {:data, :nofin, body} ->
- receive_response(conn, ref, acc <> body)
-
- {:data, :fin, body} ->
- acc <> body
- end
- end
-end
--
cgit v1.2.3
From 884d9710b209cc9981c7de61d4e95fd26cd83820 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 3 Mar 2020 19:24:14 +0300
Subject: refactoring for gun api modules
---
test/http/adapter_helper/gun_test.exs | 2 +-
test/http/connection_test.exs | 2 +-
test/http_test.exs | 4 +-
test/pool/connections_test.exs | 7 +-
test/reverse_proxy/client/tesla_test.exs | 4 +-
test/reverse_proxy/reverse_proxy_test.exs | 4 +-
test/support/gun_mock.ex | 155 ++++++++++++++++++++++++++++++
7 files changed, 166 insertions(+), 12 deletions(-)
create mode 100644 test/support/gun_mock.ex
(limited to 'test')
diff --git a/test/http/adapter_helper/gun_test.exs b/test/http/adapter_helper/gun_test.exs
index bc7e3f0e0..66ca416d9 100644
--- a/test/http/adapter_helper/gun_test.exs
+++ b/test/http/adapter_helper/gun_test.exs
@@ -12,7 +12,7 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
alias Pleroma.Pool.Connections
setup_all do
- {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.Gun.API.Mock)
+ {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.GunMock)
:ok
end
diff --git a/test/http/connection_test.exs b/test/http/connection_test.exs
index 37de11e7a..3f32898cb 100644
--- a/test/http/connection_test.exs
+++ b/test/http/connection_test.exs
@@ -10,7 +10,7 @@ defmodule Pleroma.HTTP.ConnectionTest do
alias Pleroma.HTTP.Connection
setup_all do
- {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.Gun.API.Mock)
+ {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.GunMock)
:ok
end
diff --git a/test/http_test.exs b/test/http_test.exs
index 83c27f6e1..d45d34f32 100644
--- a/test/http_test.exs
+++ b/test/http_test.exs
@@ -61,8 +61,8 @@ defmodule Pleroma.HTTPTest do
describe "connection pools" do
@describetag :integration
- clear_config(Pleroma.Gun.API) do
- Pleroma.Config.put(Pleroma.Gun.API, Pleroma.Gun)
+ clear_config(Pleroma.Gun) do
+ Pleroma.Config.put(Pleroma.Gun, Pleroma.Gun.API)
end
test "gun" do
diff --git a/test/pool/connections_test.exs b/test/pool/connections_test.exs
index a084f31b9..31dd5f6fa 100644
--- a/test/pool/connections_test.exs
+++ b/test/pool/connections_test.exs
@@ -6,12 +6,11 @@ defmodule Pleroma.Pool.ConnectionsTest do
use ExUnit.Case
use Pleroma.Tests.Helpers
import ExUnit.CaptureLog
- alias Pleroma.Gun.API
alias Pleroma.Gun.Conn
alias Pleroma.Pool.Connections
setup_all do
- {:ok, _} = Registry.start_link(keys: :unique, name: API.Mock)
+ {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.GunMock)
:ok
end
@@ -439,8 +438,8 @@ defmodule Pleroma.Pool.ConnectionsTest do
describe "integration test" do
@describetag :integration
- clear_config(API) do
- Pleroma.Config.put(API, Pleroma.Gun)
+ clear_config(Pleroma.Gun) do
+ Pleroma.Config.put(Pleroma.Gun, Pleroma.Gun.API)
end
test "opens connection and change owner", %{name: name} do
diff --git a/test/reverse_proxy/client/tesla_test.exs b/test/reverse_proxy/client/tesla_test.exs
index 231271b0d..78bd31530 100644
--- a/test/reverse_proxy/client/tesla_test.exs
+++ b/test/reverse_proxy/client/tesla_test.exs
@@ -8,8 +8,8 @@ defmodule Pleroma.ReverseProxy.Client.TeslaTest do
alias Pleroma.ReverseProxy.Client
@moduletag :integration
- clear_config_all(Pleroma.Gun.API) do
- Pleroma.Config.put(Pleroma.Gun.API, Pleroma.Gun)
+ clear_config_all(Pleroma.Gun) do
+ Pleroma.Config.put(Pleroma.Gun, Pleroma.Gun.API)
end
setup do
diff --git a/test/reverse_proxy/reverse_proxy_test.exs b/test/reverse_proxy/reverse_proxy_test.exs
index f61fc02c5..8e72698ee 100644
--- a/test/reverse_proxy/reverse_proxy_test.exs
+++ b/test/reverse_proxy/reverse_proxy_test.exs
@@ -349,8 +349,8 @@ defmodule Pleroma.ReverseProxyTest do
Pleroma.Config.put(Pleroma.ReverseProxy.Client, Pleroma.ReverseProxy.Client.Tesla)
end
- clear_config(Pleroma.Gun.API) do
- Pleroma.Config.put(Pleroma.Gun.API, Pleroma.Gun)
+ clear_config(Pleroma.Gun) do
+ Pleroma.Config.put(Pleroma.Gun, Pleroma.Gun.API)
end
setup do
diff --git a/test/support/gun_mock.ex b/test/support/gun_mock.ex
new file mode 100644
index 000000000..e13afd08c
--- /dev/null
+++ b/test/support/gun_mock.ex
@@ -0,0 +1,155 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.GunMock do
+ @behaviour Pleroma.Gun
+
+ alias Pleroma.Gun
+ alias Pleroma.GunMock
+
+ @impl Gun
+ def open('some-domain.com', 443, _) do
+ {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
+
+ Registry.register(GunMock, conn_pid, %{
+ origin_scheme: "https",
+ origin_host: 'some-domain.com',
+ origin_port: 443
+ })
+
+ {:ok, conn_pid}
+ end
+
+ @impl Gun
+ def open(ip, port, _)
+ when ip in [{10_755, 10_368, 61_708, 131, 64_206, 45_068, 0, 9_694}, {127, 0, 0, 1}] and
+ port in [80, 443] do
+ {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
+
+ scheme = if port == 443, do: "https", else: "http"
+
+ Registry.register(GunMock, conn_pid, %{
+ origin_scheme: scheme,
+ origin_host: ip,
+ origin_port: port
+ })
+
+ {:ok, conn_pid}
+ end
+
+ @impl Gun
+ def open('localhost', 1234, %{
+ protocols: [:socks],
+ proxy: {:socks5, 'localhost', 1234},
+ socks_opts: %{host: 'proxy-socks.com', port: 80, version: 5}
+ }) do
+ {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
+
+ Registry.register(GunMock, conn_pid, %{
+ origin_scheme: "http",
+ origin_host: 'proxy-socks.com',
+ origin_port: 80
+ })
+
+ {:ok, conn_pid}
+ end
+
+ @impl Gun
+ def open('localhost', 1234, %{
+ protocols: [:socks],
+ proxy: {:socks4, 'localhost', 1234},
+ socks_opts: %{
+ host: 'proxy-socks.com',
+ port: 443,
+ protocols: [:http2],
+ tls_opts: [],
+ transport: :tls,
+ version: 4
+ }
+ }) do
+ {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
+
+ Registry.register(GunMock, conn_pid, %{
+ origin_scheme: "https",
+ origin_host: 'proxy-socks.com',
+ origin_port: 443
+ })
+
+ {:ok, conn_pid}
+ end
+
+ @impl Gun
+ def open('gun-not-up.com', 80, _opts), do: {:error, :timeout}
+
+ @impl Gun
+ def open('example.com', port, _) when port in [443, 115] do
+ {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
+
+ Registry.register(GunMock, conn_pid, %{
+ origin_scheme: "https",
+ origin_host: 'example.com',
+ origin_port: 443
+ })
+
+ {:ok, conn_pid}
+ end
+
+ @impl Gun
+ def open(domain, 80, _) do
+ {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
+
+ Registry.register(GunMock, conn_pid, %{
+ origin_scheme: "http",
+ origin_host: domain,
+ origin_port: 80
+ })
+
+ {:ok, conn_pid}
+ end
+
+ @impl Gun
+ def open({127, 0, 0, 1}, 8123, _) do
+ Task.start_link(fn -> Process.sleep(1_000) end)
+ end
+
+ @impl Gun
+ def open('localhost', 9050, _) do
+ Task.start_link(fn -> Process.sleep(1_000) end)
+ end
+
+ @impl Gun
+ def await_up(_pid, _timeout), do: {:ok, :http}
+
+ @impl Gun
+ def set_owner(_pid, _owner), do: :ok
+
+ @impl Gun
+ def connect(pid, %{host: _, port: 80}) do
+ ref = make_ref()
+ Registry.register(GunMock, ref, pid)
+ ref
+ end
+
+ @impl Gun
+ def connect(pid, %{host: _, port: 443, protocols: [:http2], transport: :tls}) do
+ ref = make_ref()
+ Registry.register(GunMock, ref, pid)
+ ref
+ end
+
+ @impl Gun
+ def await(pid, ref) do
+ [{_, ^pid}] = Registry.lookup(GunMock, ref)
+ {:response, :fin, 200, []}
+ end
+
+ @impl Gun
+ def info(pid) do
+ [{_, info}] = Registry.lookup(GunMock, pid)
+ info
+ end
+
+ @impl Gun
+ def close(_pid), do: :ok
+end
--
cgit v1.2.3
From d9c5ae7c09c7cbf3f4f66e01b7ed69a3d6388916 Mon Sep 17 00:00:00 2001
From: Mark Felder
Date: Tue, 3 Mar 2020 17:16:24 -0600
Subject: Update Copyrights for gun related files
---
test/http/adapter_helper/hackney_test.exs | 2 +-
test/http/connection_test.exs | 2 +-
test/pool/connections_test.exs | 2 +-
test/reverse_proxy/client/tesla_test.exs | 2 +-
test/support/gun_mock.ex | 2 +-
5 files changed, 5 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/http/adapter_helper/hackney_test.exs b/test/http/adapter_helper/hackney_test.exs
index 82f5a7883..3306616ef 100644
--- a/test/http/adapter_helper/hackney_test.exs
+++ b/test/http/adapter_helper/hackney_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTP.AdapterHelper.HackneyTest do
diff --git a/test/http/connection_test.exs b/test/http/connection_test.exs
index 3f32898cb..5c1ecda0b 100644
--- a/test/http/connection_test.exs
+++ b/test/http/connection_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTP.ConnectionTest do
diff --git a/test/pool/connections_test.exs b/test/pool/connections_test.exs
index 31dd5f6fa..963fae665 100644
--- a/test/pool/connections_test.exs
+++ b/test/pool/connections_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Pool.ConnectionsTest do
diff --git a/test/reverse_proxy/client/tesla_test.exs b/test/reverse_proxy/client/tesla_test.exs
index 78bd31530..c8b0d5842 100644
--- a/test/reverse_proxy/client/tesla_test.exs
+++ b/test/reverse_proxy/client/tesla_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.ReverseProxy.Client.TeslaTest do
diff --git a/test/support/gun_mock.ex b/test/support/gun_mock.ex
index e13afd08c..9d664e366 100644
--- a/test/support/gun_mock.ex
+++ b/test/support/gun_mock.ex
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.GunMock do
--
cgit v1.2.3
From 6b2fb9160cd945cdd4b1265c793d1f85d559fccb Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 4 Mar 2020 09:23:42 +0300
Subject: otp version
---
test/otp_version_test.exs | 18 +++++++++++-------
1 file changed, 11 insertions(+), 7 deletions(-)
(limited to 'test')
diff --git a/test/otp_version_test.exs b/test/otp_version_test.exs
index af278cc72..7d2538ec8 100644
--- a/test/otp_version_test.exs
+++ b/test/otp_version_test.exs
@@ -9,30 +9,34 @@ defmodule Pleroma.OTPVersionTest do
describe "check/1" do
test "22.4" do
- assert OTPVersion.check(["test/fixtures/warnings/otp_version/22.4"]) == :ok
+ assert OTPVersion.get_version_from_files(["test/fixtures/warnings/otp_version/22.4"]) ==
+ "22.4"
end
test "22.1" do
- assert OTPVersion.check(["test/fixtures/warnings/otp_version/22.1"]) == {:error, "22.1"}
+ assert OTPVersion.get_version_from_files(["test/fixtures/warnings/otp_version/22.1"]) ==
+ "22.1"
end
test "21.1" do
- assert OTPVersion.check(["test/fixtures/warnings/otp_version/21.1"]) == {:error, "21.1"}
+ assert OTPVersion.get_version_from_files(["test/fixtures/warnings/otp_version/21.1"]) ==
+ "21.1"
end
test "23.0" do
- assert OTPVersion.check(["test/fixtures/warnings/otp_version/23.0"]) == :ok
+ assert OTPVersion.get_version_from_files(["test/fixtures/warnings/otp_version/23.0"]) ==
+ "23.0"
end
test "with non existance file" do
- assert OTPVersion.check([
+ assert OTPVersion.get_version_from_files([
"test/fixtures/warnings/otp_version/non-exising",
"test/fixtures/warnings/otp_version/22.4"
- ]) == :ok
+ ]) == "22.4"
end
test "empty paths" do
- assert OTPVersion.check([]) == :undefined
+ assert OTPVersion.get_version_from_files([]) == nil
end
end
end
--
cgit v1.2.3
From 22d52f5691d985e7daaa955e97e0722f038f6fae Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 4 Mar 2020 09:41:23 +0300
Subject: same copyright date format
---
test/web/activity_pub/mrf/anti_followbot_policy_test.exs | 2 +-
test/web/activity_pub/mrf/anti_link_spam_policy_test.exs | 2 +-
test/web/activity_pub/mrf/ensure_re_prepended_test.exs | 2 +-
test/web/activity_pub/mrf/no_placeholder_text_policy_test.exs | 2 +-
test/web/activity_pub/mrf/normalize_markup_test.exs | 2 +-
test/web/activity_pub/mrf/object_age_policy_test.exs | 2 +-
test/web/activity_pub/mrf/reject_non_public_test.exs | 2 +-
test/web/activity_pub/mrf/simple_policy_test.exs | 2 +-
8 files changed, 8 insertions(+), 8 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/mrf/anti_followbot_policy_test.exs b/test/web/activity_pub/mrf/anti_followbot_policy_test.exs
index 37a7bfcf7..fca0de7c6 100644
--- a/test/web/activity_pub/mrf/anti_followbot_policy_test.exs
+++ b/test/web/activity_pub/mrf/anti_followbot_policy_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.AntiFollowbotPolicyTest do
diff --git a/test/web/activity_pub/mrf/anti_link_spam_policy_test.exs b/test/web/activity_pub/mrf/anti_link_spam_policy_test.exs
index b524fdd23..fc0be6f91 100644
--- a/test/web/activity_pub/mrf/anti_link_spam_policy_test.exs
+++ b/test/web/activity_pub/mrf/anti_link_spam_policy_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.AntiLinkSpamPolicyTest do
diff --git a/test/web/activity_pub/mrf/ensure_re_prepended_test.exs b/test/web/activity_pub/mrf/ensure_re_prepended_test.exs
index dbc8b9e80..38ddec5bb 100644
--- a/test/web/activity_pub/mrf/ensure_re_prepended_test.exs
+++ b/test/web/activity_pub/mrf/ensure_re_prepended_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.EnsureRePrependedTest do
diff --git a/test/web/activity_pub/mrf/no_placeholder_text_policy_test.exs b/test/web/activity_pub/mrf/no_placeholder_text_policy_test.exs
index 63ed71129..64ea61dd4 100644
--- a/test/web/activity_pub/mrf/no_placeholder_text_policy_test.exs
+++ b/test/web/activity_pub/mrf/no_placeholder_text_policy_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.NoPlaceholderTextPolicyTest do
diff --git a/test/web/activity_pub/mrf/normalize_markup_test.exs b/test/web/activity_pub/mrf/normalize_markup_test.exs
index 0207be56b..9b39c45bd 100644
--- a/test/web/activity_pub/mrf/normalize_markup_test.exs
+++ b/test/web/activity_pub/mrf/normalize_markup_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.NormalizeMarkupTest do
diff --git a/test/web/activity_pub/mrf/object_age_policy_test.exs b/test/web/activity_pub/mrf/object_age_policy_test.exs
index 643609da4..e521fae44 100644
--- a/test/web/activity_pub/mrf/object_age_policy_test.exs
+++ b/test/web/activity_pub/mrf/object_age_policy_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do
diff --git a/test/web/activity_pub/mrf/reject_non_public_test.exs b/test/web/activity_pub/mrf/reject_non_public_test.exs
index fc1d190bb..5cc68bca8 100644
--- a/test/web/activity_pub/mrf/reject_non_public_test.exs
+++ b/test/web/activity_pub/mrf/reject_non_public_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.RejectNonPublicTest do
diff --git a/test/web/activity_pub/mrf/simple_policy_test.exs b/test/web/activity_pub/mrf/simple_policy_test.exs
index df0f223f8..e825a1514 100644
--- a/test/web/activity_pub/mrf/simple_policy_test.exs
+++ b/test/web/activity_pub/mrf/simple_policy_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do
--
cgit v1.2.3
From d6bebd4f9c8086dd87c75f3637a5d392a05f2daf Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 4 Mar 2020 18:13:24 +0300
Subject: moving some logic to tesla adapter
- checking original inside gun adapter
- flushing streams on max_body error
---
test/http/adapter_helper/gun_test.exs | 7 -------
test/http/connection_test.exs | 1 -
2 files changed, 8 deletions(-)
(limited to 'test')
diff --git a/test/http/adapter_helper/gun_test.exs b/test/http/adapter_helper/gun_test.exs
index 66ca416d9..c1bf909a6 100644
--- a/test/http/adapter_helper/gun_test.exs
+++ b/test/http/adapter_helper/gun_test.exs
@@ -35,8 +35,6 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
{&:ssl_verify_hostname.verify_fun/3, [check_hostname: 'example.com']}
assert File.exists?(tls_opts[:cacertfile])
-
- assert opts[:original] == "example.com:443"
end
test "https ipv4 with default port" do
@@ -46,8 +44,6 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
assert opts[:tls_opts][:verify_fun] ==
{&:ssl_verify_hostname.verify_fun/3, [check_hostname: '127.0.0.1']}
-
- assert opts[:original] == "127.0.0.1:443"
end
test "https ipv6 with default port" do
@@ -58,8 +54,6 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
assert opts[:tls_opts][:verify_fun] ==
{&:ssl_verify_hostname.verify_fun/3,
[check_hostname: '2a03:2880:f10c:83:face:b00c:0:25de']}
-
- assert opts[:original] == "2a03:2880:f10c:83:face:b00c:0:25de:443"
end
test "https url with non standart port" do
@@ -129,7 +123,6 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
assert tls_opts[:depth] == 20
assert tls_opts[:reuse_sessions] == false
- assert opts[:original] == "some-domain.com:443"
assert opts[:close_conn] == false
assert is_pid(opts[:conn])
end
diff --git a/test/http/connection_test.exs b/test/http/connection_test.exs
index 5c1ecda0b..d4db3798c 100644
--- a/test/http/connection_test.exs
+++ b/test/http/connection_test.exs
@@ -134,7 +134,6 @@ defmodule Pleroma.HTTP.ConnectionTest do
assert tls_opts[:depth] == 20
assert tls_opts[:reuse_sessions] == false
- assert opts[:original] == "some-domain.com:443"
assert opts[:close_conn] == false
assert is_pid(opts[:conn])
end
--
cgit v1.2.3
From f0753eed0fdddd30e127213c89a118dd2e087dc9 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Thu, 5 Mar 2020 17:31:06 +0300
Subject: removing try block in tesla request
added mocks for tests which fail with Tesla.Mock.Error
---
test/fixtures/users_mock/localhost.json | 41 ++++++++++++++++++++++
test/notification_test.exs | 20 +++++++++++
.../mrf/anti_link_spam_policy_test.exs | 9 +++++
test/web/activity_pub/relay_test.exs | 5 +++
.../controllers/notification_controller_test.exs | 13 +++++++
.../mastodon_api/views/notification_view_test.exs | 13 +++++++
test/web/mastodon_api/views/status_view_test.exs | 17 +++++++++
test/web/streamer/streamer_test.exs | 12 +++++++
8 files changed, 130 insertions(+)
create mode 100644 test/fixtures/users_mock/localhost.json
(limited to 'test')
diff --git a/test/fixtures/users_mock/localhost.json b/test/fixtures/users_mock/localhost.json
new file mode 100644
index 000000000..a49935db1
--- /dev/null
+++ b/test/fixtures/users_mock/localhost.json
@@ -0,0 +1,41 @@
+{
+ "@context": [
+ "https://www.w3.org/ns/activitystreams",
+ "http://localhost:4001/schemas/litepub-0.1.jsonld",
+ {
+ "@language": "und"
+ }
+ ],
+ "attachment": [],
+ "endpoints": {
+ "oauthAuthorizationEndpoint": "http://localhost:4001/oauth/authorize",
+ "oauthRegistrationEndpoint": "http://localhost:4001/api/v1/apps",
+ "oauthTokenEndpoint": "http://localhost:4001/oauth/token",
+ "sharedInbox": "http://localhost:4001/inbox"
+ },
+ "followers": "http://localhost:4001/users/{{nickname}}/followers",
+ "following": "http://localhost:4001/users/{{nickname}}/following",
+ "icon": {
+ "type": "Image",
+ "url": "http://localhost:4001/media/4e914f5b84e4a259a3f6c2d2edc9ab642f2ab05f3e3d9c52c81fc2d984b3d51e.jpg"
+ },
+ "id": "http://localhost:4001/users/{{nickname}}",
+ "image": {
+ "type": "Image",
+ "url": "http://localhost:4001/media/f739efddefeee49c6e67e947c4811fdc911785c16ae43da4c3684051fbf8da6a.jpg?name=f739efddefeee49c6e67e947c4811fdc911785c16ae43da4c3684051fbf8da6a.jpg"
+ },
+ "inbox": "http://localhost:4001/users/{{nickname}}/inbox",
+ "manuallyApprovesFollowers": false,
+ "name": "{{nickname}}",
+ "outbox": "http://localhost:4001/users/{{nickname}}/outbox",
+ "preferredUsername": "{{nickname}}",
+ "publicKey": {
+ "id": "http://localhost:4001/users/{{nickname}}#main-key",
+ "owner": "http://localhost:4001/users/{{nickname}}",
+ "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5DLtwGXNZElJyxFGfcVc\nXANhaMadj/iYYQwZjOJTV9QsbtiNBeIK54PJrYuU0/0YIdrvS1iqheX5IwXRhcwa\nhm3ZyLz7XeN9st7FBni4BmZMBtMpxAuYuu5p/jbWy13qAiYOhPreCx0wrWgm/lBD\n9mkgaxIxPooBE0S4ZWEJIDIV1Vft3AWcRUyWW1vIBK0uZzs6GYshbQZB952S0yo4\nFzI1hABGHncH8UvuFauh4EZ8tY7/X5I0pGRnDOcRN1dAht5w5yTA+6r5kebiFQjP\nIzN/eCO/a9Flrj9YGW7HDNtjSOH0A31PLRGlJtJO3yK57dnf5ppyCZGfL4emShQo\ncQIDAQAB\n-----END PUBLIC KEY-----\n\n"
+ },
+ "summary": "your friendly neighborhood pleroma developer
I like cute things and distributed systems, and really hate delete and redrafts",
+ "tag": [],
+ "type": "Person",
+ "url": "http://localhost:4001/users/{{nickname}}"
+}
\ No newline at end of file
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 56a581810..c71df4e07 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -649,12 +649,20 @@ defmodule Pleroma.NotificationTest do
"object" => remote_user.ap_id
}
+ remote_user_url = remote_user.ap_id
+
+ Tesla.Mock.mock(fn
+ %{method: :get, url: ^remote_user_url} ->
+ %Tesla.Env{status: 404, body: ""}
+ end)
+
{:ok, _delete_activity} = Transmogrifier.handle_incoming(delete_user_message)
ObanHelpers.perform_all()
assert Enum.empty?(Notification.for_user(local_user))
end
+ @tag capture_log: true
test "move activity generates a notification" do
%{ap_id: old_ap_id} = old_user = insert(:user)
%{ap_id: new_ap_id} = new_user = insert(:user, also_known_as: [old_ap_id])
@@ -664,6 +672,18 @@ defmodule Pleroma.NotificationTest do
User.follow(follower, old_user)
User.follow(other_follower, old_user)
+ old_user_url = old_user.ap_id
+
+ body =
+ File.read!("test/fixtures/users_mock/localhost.json")
+ |> String.replace("{{nickname}}", old_user.nickname)
+ |> Jason.encode!()
+
+ Tesla.Mock.mock(fn
+ %{method: :get, url: ^old_user_url} ->
+ %Tesla.Env{status: 200, body: body}
+ end)
+
Pleroma.Web.ActivityPub.ActivityPub.move(old_user, new_user)
ObanHelpers.perform_all()
diff --git a/test/web/activity_pub/mrf/anti_link_spam_policy_test.exs b/test/web/activity_pub/mrf/anti_link_spam_policy_test.exs
index fc0be6f91..1a13699be 100644
--- a/test/web/activity_pub/mrf/anti_link_spam_policy_test.exs
+++ b/test/web/activity_pub/mrf/anti_link_spam_policy_test.exs
@@ -110,6 +110,15 @@ defmodule Pleroma.Web.ActivityPub.MRF.AntiLinkSpamPolicyTest do
end
describe "with unknown actors" do
+ setup do
+ Tesla.Mock.mock(fn
+ %{method: :get, url: "http://invalid.actor"} ->
+ %Tesla.Env{status: 500, body: ""}
+ end)
+
+ :ok
+ end
+
test "it rejects posts without links" do
message =
@linkless_message
diff --git a/test/web/activity_pub/relay_test.exs b/test/web/activity_pub/relay_test.exs
index e3115dcd8..12bf90d90 100644
--- a/test/web/activity_pub/relay_test.exs
+++ b/test/web/activity_pub/relay_test.exs
@@ -89,6 +89,11 @@ defmodule Pleroma.Web.ActivityPub.RelayTest do
}
)
+ Tesla.Mock.mock(fn
+ %{method: :get, url: "http://mastodon.example.org/eee/99541947525187367"} ->
+ %Tesla.Env{status: 500, body: ""}
+ end)
+
assert capture_log(fn ->
assert Relay.publish(activity) == {:error, nil}
end) =~ "[error] error: nil"
diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs
index d452ddbdd..0f0a060d2 100644
--- a/test/web/mastodon_api/controllers/notification_controller_test.exs
+++ b/test/web/mastodon_api/controllers/notification_controller_test.exs
@@ -407,11 +407,24 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
assert length(json_response(conn, 200)) == 1
end
+ @tag capture_log: true
test "see move notifications with `with_move` parameter" do
old_user = insert(:user)
new_user = insert(:user, also_known_as: [old_user.ap_id])
%{user: follower, conn: conn} = oauth_access(["read:notifications"])
+ old_user_url = old_user.ap_id
+
+ body =
+ File.read!("test/fixtures/users_mock/localhost.json")
+ |> String.replace("{{nickname}}", old_user.nickname)
+ |> Jason.encode!()
+
+ Tesla.Mock.mock(fn
+ %{method: :get, url: ^old_user_url} ->
+ %Tesla.Env{status: 200, body: body}
+ end)
+
User.follow(follower, old_user)
Pleroma.Web.ActivityPub.ActivityPub.move(old_user, new_user)
Pleroma.Tests.ObanHelpers.perform_all()
diff --git a/test/web/mastodon_api/views/notification_view_test.exs b/test/web/mastodon_api/views/notification_view_test.exs
index 4df9c3c03..57e4c8f1e 100644
--- a/test/web/mastodon_api/views/notification_view_test.exs
+++ b/test/web/mastodon_api/views/notification_view_test.exs
@@ -108,11 +108,24 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
NotificationView.render("index.json", %{notifications: [notification], for: followed})
end
+ @tag capture_log: true
test "Move notification" do
old_user = insert(:user)
new_user = insert(:user, also_known_as: [old_user.ap_id])
follower = insert(:user)
+ old_user_url = old_user.ap_id
+
+ body =
+ File.read!("test/fixtures/users_mock/localhost.json")
+ |> String.replace("{{nickname}}", old_user.nickname)
+ |> Jason.encode!()
+
+ Tesla.Mock.mock(fn
+ %{method: :get, url: ^old_user_url} ->
+ %Tesla.Env{status: 200, body: body}
+ end)
+
User.follow(follower, old_user)
Pleroma.Web.ActivityPub.ActivityPub.move(old_user, new_user)
Pleroma.Tests.ObanHelpers.perform_all()
diff --git a/test/web/mastodon_api/views/status_view_test.exs b/test/web/mastodon_api/views/status_view_test.exs
index 191895c6f..7df72decb 100644
--- a/test/web/mastodon_api/views/status_view_test.exs
+++ b/test/web/mastodon_api/views/status_view_test.exs
@@ -92,6 +92,23 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
Repo.delete(user)
Cachex.clear(:user_cache)
+ finger_url =
+ "https://localhost/.well-known/webfinger?resource=acct:#{user.nickname}@localhost"
+
+ Tesla.Mock.mock_global(fn
+ %{method: :get, url: "http://localhost/.well-known/host-meta"} ->
+ %Tesla.Env{status: 404, body: ""}
+
+ %{method: :get, url: "https://localhost/.well-known/host-meta"} ->
+ %Tesla.Env{status: 404, body: ""}
+
+ %{
+ method: :get,
+ url: ^finger_url
+ } ->
+ %Tesla.Env{status: 404, body: ""}
+ end)
+
%{account: ms_user} = StatusView.render("show.json", activity: activity)
assert ms_user.acct == "erroruser@example.com"
diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs
index 339f99bbf..a04d70f21 100644
--- a/test/web/streamer/streamer_test.exs
+++ b/test/web/streamer/streamer_test.exs
@@ -122,6 +122,18 @@ defmodule Pleroma.Web.StreamerTest do
test "it sends follow activities to the 'user:notification' stream", %{
user: user
} do
+ user_url = user.ap_id
+
+ body =
+ File.read!("test/fixtures/users_mock/localhost.json")
+ |> String.replace("{{nickname}}", user.nickname)
+ |> Jason.encode!()
+
+ Tesla.Mock.mock_global(fn
+ %{method: :get, url: ^user_url} ->
+ %Tesla.Env{status: 200, body: body}
+ end)
+
user2 = insert(:user)
task = Task.async(fn -> assert_receive {:text, _}, @streamer_timeout end)
--
cgit v1.2.3
From 931111fd5518cb79449cf79ffe29cb774c55d5ff Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Thu, 5 Mar 2020 18:57:45 +0300
Subject: removing integration tests
---
test/http_test.exs | 25 ---
test/pool/connections_test.exs | 301 ------------------------------
test/reverse_proxy/client/tesla_test.exs | 93 ---------
test/reverse_proxy/reverse_proxy_test.exs | 41 ----
4 files changed, 460 deletions(-)
delete mode 100644 test/reverse_proxy/client/tesla_test.exs
(limited to 'test')
diff --git a/test/http_test.exs b/test/http_test.exs
index 4aa08afcb..fd254b590 100644
--- a/test/http_test.exs
+++ b/test/http_test.exs
@@ -58,29 +58,4 @@ defmodule Pleroma.HTTPTest do
}
end
end
-
- describe "connection pools" do
- @describetag :integration
- clear_config(Pleroma.Gun) do
- Pleroma.Config.put(Pleroma.Gun, Pleroma.Gun.API)
- end
-
- test "gun" do
- adapter = Application.get_env(:tesla, :adapter)
- Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
-
- on_exit(fn ->
- Application.put_env(:tesla, :adapter, adapter)
- end)
-
- options = [adapter: [pool: :federation]]
-
- assert {:ok, resp} = HTTP.get("https://httpbin.org/user-agent", [], options)
-
- assert resp.status == 200
-
- state = Pleroma.Pool.Connections.get_state(:gun_connections)
- assert state.conns["https:httpbin.org:443"]
- end
- end
end
diff --git a/test/pool/connections_test.exs b/test/pool/connections_test.exs
index 963fae665..753fd8b0b 100644
--- a/test/pool/connections_test.exs
+++ b/test/pool/connections_test.exs
@@ -435,307 +435,6 @@ defmodule Pleroma.Pool.ConnectionsTest do
} = Connections.get_state(name)
end
- describe "integration test" do
- @describetag :integration
-
- clear_config(Pleroma.Gun) do
- Pleroma.Config.put(Pleroma.Gun, Pleroma.Gun.API)
- end
-
- test "opens connection and change owner", %{name: name} do
- url = "https://httpbin.org"
- :ok = Conn.open(url, name)
- conn = Connections.checkin(url, name)
-
- pid = Process.whereis(name)
-
- assert :gun.info(conn).owner == pid
- end
-
- test "opens connection and reuse it on next request", %{name: name} do
- url = "http://httpbin.org"
- :ok = Conn.open(url, name)
- Process.sleep(250)
- conn = Connections.checkin(url, name)
-
- assert is_pid(conn)
- assert Process.alive?(conn)
-
- reused_conn = Connections.checkin(url, name)
-
- assert conn == reused_conn
-
- %Connections{
- conns: %{
- "http:httpbin.org:80" => %Conn{
- conn: ^conn,
- gun_state: :up
- }
- }
- } = Connections.get_state(name)
- end
-
- test "opens ssl connection and reuse it on next request", %{name: name} do
- url = "https://httpbin.org"
- :ok = Conn.open(url, name)
- Process.sleep(1_000)
- conn = Connections.checkin(url, name)
-
- assert is_pid(conn)
- assert Process.alive?(conn)
-
- reused_conn = Connections.checkin(url, name)
-
- assert conn == reused_conn
-
- %Connections{
- conns: %{
- "https:httpbin.org:443" => %Conn{
- conn: ^conn,
- gun_state: :up
- }
- }
- } = Connections.get_state(name)
- end
-
- test "remove frequently used and idle", %{name: name} do
- self = self()
- https1 = "https://www.google.com"
- https2 = "https://httpbin.org"
-
- :ok = Conn.open(https1, name)
- :ok = Conn.open(https2, name)
- Process.sleep(1_500)
- conn = Connections.checkin(https1, name)
-
- for _ <- 1..4 do
- Connections.checkin(https2, name)
- end
-
- %Connections{
- conns: %{
- "https:httpbin.org:443" => %Conn{
- conn: _,
- gun_state: :up
- },
- "https:www.google.com:443" => %Conn{
- conn: _,
- gun_state: :up
- }
- }
- } = Connections.get_state(name)
-
- :ok = Connections.checkout(conn, self, name)
- http = "http://httpbin.org"
- Process.sleep(1_000)
- :ok = Conn.open(http, name)
- conn = Connections.checkin(http, name)
-
- %Connections{
- conns: %{
- "http:httpbin.org:80" => %Conn{
- conn: ^conn,
- gun_state: :up
- },
- "https:httpbin.org:443" => %Conn{
- conn: _,
- gun_state: :up
- }
- }
- } = Connections.get_state(name)
- end
-
- test "remove earlier used and idle", %{name: name} do
- self = self()
-
- https1 = "https://www.google.com"
- https2 = "https://httpbin.org"
- :ok = Conn.open(https1, name)
- :ok = Conn.open(https2, name)
- Process.sleep(1_500)
-
- Connections.checkin(https1, name)
- conn = Connections.checkin(https1, name)
-
- Process.sleep(1_000)
- Connections.checkin(https2, name)
- Connections.checkin(https2, name)
-
- %Connections{
- conns: %{
- "https:httpbin.org:443" => %Conn{
- conn: _,
- gun_state: :up
- },
- "https:www.google.com:443" => %Conn{
- conn: ^conn,
- gun_state: :up
- }
- }
- } = Connections.get_state(name)
-
- :ok = Connections.checkout(conn, self, name)
- :ok = Connections.checkout(conn, self, name)
-
- http = "http://httpbin.org"
- :ok = Conn.open(http, name)
- Process.sleep(1_000)
-
- conn = Connections.checkin(http, name)
-
- %Connections{
- conns: %{
- "http:httpbin.org:80" => %Conn{
- conn: ^conn,
- gun_state: :up
- },
- "https:httpbin.org:443" => %Conn{
- conn: _,
- gun_state: :up
- }
- }
- } = Connections.get_state(name)
- end
-
- test "doesn't open new conn on pool overflow", %{name: name} do
- self = self()
-
- https1 = "https://www.google.com"
- https2 = "https://httpbin.org"
- :ok = Conn.open(https1, name)
- :ok = Conn.open(https2, name)
- Process.sleep(1_000)
- Connections.checkin(https1, name)
- conn1 = Connections.checkin(https1, name)
- conn2 = Connections.checkin(https2, name)
-
- %Connections{
- conns: %{
- "https:httpbin.org:443" => %Conn{
- conn: ^conn2,
- gun_state: :up,
- conn_state: :active,
- used_by: [{^self, _}]
- },
- "https:www.google.com:443" => %Conn{
- conn: ^conn1,
- gun_state: :up,
- conn_state: :active,
- used_by: [{^self, _}, {^self, _}]
- }
- }
- } = Connections.get_state(name)
-
- refute Connections.checkin("http://httpbin.org", name)
-
- %Connections{
- conns: %{
- "https:httpbin.org:443" => %Conn{
- conn: ^conn2,
- gun_state: :up,
- conn_state: :active,
- used_by: [{^self, _}]
- },
- "https:www.google.com:443" => %Conn{
- conn: ^conn1,
- gun_state: :up,
- conn_state: :active,
- used_by: [{^self, _}, {^self, _}]
- }
- }
- } = Connections.get_state(name)
- end
-
- test "get idle connection with the smallest crf", %{
- name: name
- } do
- self = self()
-
- https1 = "https://www.google.com"
- https2 = "https://httpbin.org"
-
- :ok = Conn.open(https1, name)
- :ok = Conn.open(https2, name)
- Process.sleep(1_500)
- Connections.checkin(https1, name)
- Connections.checkin(https2, name)
- Connections.checkin(https1, name)
- conn1 = Connections.checkin(https1, name)
- conn2 = Connections.checkin(https2, name)
-
- %Connections{
- conns: %{
- "https:httpbin.org:443" => %Conn{
- conn: ^conn2,
- gun_state: :up,
- conn_state: :active,
- used_by: [{^self, _}, {^self, _}],
- crf: crf2
- },
- "https:www.google.com:443" => %Conn{
- conn: ^conn1,
- gun_state: :up,
- conn_state: :active,
- used_by: [{^self, _}, {^self, _}, {^self, _}],
- crf: crf1
- }
- }
- } = Connections.get_state(name)
-
- assert crf1 > crf2
-
- :ok = Connections.checkout(conn1, self, name)
- :ok = Connections.checkout(conn1, self, name)
- :ok = Connections.checkout(conn1, self, name)
-
- :ok = Connections.checkout(conn2, self, name)
- :ok = Connections.checkout(conn2, self, name)
-
- %Connections{
- conns: %{
- "https:httpbin.org:443" => %Conn{
- conn: ^conn2,
- gun_state: :up,
- conn_state: :idle,
- used_by: []
- },
- "https:www.google.com:443" => %Conn{
- conn: ^conn1,
- gun_state: :up,
- conn_state: :idle,
- used_by: []
- }
- }
- } = Connections.get_state(name)
-
- http = "http://httpbin.org"
- :ok = Conn.open(http, name)
- Process.sleep(1_000)
- conn = Connections.checkin(http, name)
-
- %Connections{
- conns: %{
- "https:www.google.com:443" => %Conn{
- conn: ^conn1,
- gun_state: :up,
- conn_state: :idle,
- used_by: [],
- crf: crf1
- },
- "http:httpbin.org:80" => %Conn{
- conn: ^conn,
- gun_state: :up,
- conn_state: :active,
- used_by: [{^self, _}],
- crf: crf
- }
- }
- } = Connections.get_state(name)
-
- assert crf1 > crf
- end
- end
-
describe "with proxy" do
test "as ip", %{name: name} do
url = "http://proxy-string.com"
diff --git a/test/reverse_proxy/client/tesla_test.exs b/test/reverse_proxy/client/tesla_test.exs
deleted file mode 100644
index c8b0d5842..000000000
--- a/test/reverse_proxy/client/tesla_test.exs
+++ /dev/null
@@ -1,93 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.ReverseProxy.Client.TeslaTest do
- use ExUnit.Case
- use Pleroma.Tests.Helpers
- alias Pleroma.ReverseProxy.Client
- @moduletag :integration
-
- clear_config_all(Pleroma.Gun) do
- Pleroma.Config.put(Pleroma.Gun, Pleroma.Gun.API)
- end
-
- setup do
- Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
-
- on_exit(fn ->
- Application.put_env(:tesla, :adapter, Tesla.Mock)
- end)
- end
-
- test "get response body stream" do
- {:ok, status, headers, ref} =
- Client.Tesla.request(
- :get,
- "http://httpbin.org/stream-bytes/10",
- [{"accept", "application/octet-stream"}],
- "",
- []
- )
-
- assert status == 200
- assert headers != []
-
- {:ok, response, ref} = Client.Tesla.stream_body(ref)
- check_ref(ref)
- assert is_binary(response)
- assert byte_size(response) == 10
-
- assert :done == Client.Tesla.stream_body(ref)
- assert :ok = Client.Tesla.close(ref)
- end
-
- test "head response" do
- {:ok, status, headers} = Client.Tesla.request(:head, "https://httpbin.org/get", [], "")
-
- assert status == 200
- assert headers != []
- end
-
- test "get error response" do
- {:ok, status, headers, _body} =
- Client.Tesla.request(
- :get,
- "https://httpbin.org/status/500",
- [],
- ""
- )
-
- assert status == 500
- assert headers != []
- end
-
- describe "client error" do
- setup do
- adapter = Application.get_env(:tesla, :adapter)
- Application.put_env(:tesla, :adapter, Tesla.Adapter.Hackney)
-
- on_exit(fn -> Application.put_env(:tesla, :adapter, adapter) end)
- :ok
- end
-
- test "adapter doesn't support reading body in chunks" do
- assert_raise RuntimeError,
- "Elixir.Tesla.Adapter.Hackney doesn't support reading body in chunks",
- fn ->
- Client.Tesla.request(
- :get,
- "http://httpbin.org/stream-bytes/10",
- [{"accept", "application/octet-stream"}],
- ""
- )
- end
- end
- end
-
- defp check_ref(%{pid: pid, stream: stream} = ref) do
- assert is_pid(pid)
- assert is_reference(stream)
- assert ref[:fin]
- end
-end
diff --git a/test/reverse_proxy/reverse_proxy_test.exs b/test/reverse_proxy/reverse_proxy_test.exs
index 18aae5a6b..c17ab0f89 100644
--- a/test/reverse_proxy/reverse_proxy_test.exs
+++ b/test/reverse_proxy/reverse_proxy_test.exs
@@ -341,45 +341,4 @@ defmodule Pleroma.ReverseProxyTest do
assert {"content-disposition", "attachment; filename=\"filename.jpg\""} in conn.resp_headers
end
end
-
- describe "tesla client using gun integration" do
- @describetag :integration
-
- clear_config(Pleroma.ReverseProxy.Client) do
- Pleroma.Config.put(Pleroma.ReverseProxy.Client, Pleroma.ReverseProxy.Client.Tesla)
- end
-
- clear_config(Pleroma.Gun) do
- Pleroma.Config.put(Pleroma.Gun, Pleroma.Gun.API)
- end
-
- setup do
- adapter = Application.get_env(:tesla, :adapter)
- Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
-
- on_exit(fn ->
- Application.put_env(:tesla, :adapter, adapter)
- end)
- end
-
- test "common", %{conn: conn} do
- conn = ReverseProxy.call(conn, "http://httpbin.org/stream-bytes/10")
- assert byte_size(conn.resp_body) == 10
- assert conn.state == :chunked
- assert conn.status == 200
- end
-
- test "ssl", %{conn: conn} do
- conn = ReverseProxy.call(conn, "https://httpbin.org/stream-bytes/10")
- assert byte_size(conn.resp_body) == 10
- assert conn.state == :chunked
- assert conn.status == 200
- end
-
- test "follow redirects", %{conn: conn} do
- conn = ReverseProxy.call(conn, "https://httpbin.org/redirect/5")
- assert conn.state == :chunked
- assert conn.status == 200
- end
- end
end
--
cgit v1.2.3
From 56ff02f2ef56465b14c9670b930d154911cc7470 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Fri, 6 Mar 2020 20:23:58 +0300
Subject: removing GunMock to use Mox
---
test/http/adapter_helper/gun_test.exs | 88 +++++++++--------
test/http/adapter_helper/hackney_test.exs | 8 +-
test/http/connection_test.exs | 25 ++---
test/pool/connections_test.exs | 119 +++++++++++++++++++----
test/support/gun_mock.ex | 155 ------------------------------
test/test_helper.exs | 3 +
6 files changed, 168 insertions(+), 230 deletions(-)
delete mode 100644 test/support/gun_mock.ex
(limited to 'test')
diff --git a/test/http/adapter_helper/gun_test.exs b/test/http/adapter_helper/gun_test.exs
index c1bf909a6..b1b34858a 100644
--- a/test/http/adapter_helper/gun_test.exs
+++ b/test/http/adapter_helper/gun_test.exs
@@ -5,17 +5,29 @@
defmodule Pleroma.HTTP.AdapterHelper.GunTest do
use ExUnit.Case, async: true
use Pleroma.Tests.Helpers
+
import ExUnit.CaptureLog
+ import Mox
+
alias Pleroma.Config
alias Pleroma.Gun.Conn
alias Pleroma.HTTP.AdapterHelper.Gun
alias Pleroma.Pool.Connections
- setup_all do
- {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.GunMock)
+ setup :verify_on_exit!
+
+ defp gun_mock(_) do
+ gun_mock()
:ok
end
+ defp gun_mock do
+ Pleroma.GunMock
+ |> expect(:open, fn _, _, _ -> Task.start_link(fn -> Process.sleep(1000) end) end)
+ |> expect(:await_up, fn _, _ -> {:ok, :http} end)
+ |> expect(:set_owner, fn _, _ -> :ok end)
+ end
+
describe "options/1" do
clear_config([:http, :adapter]) do
Config.put([:http, :adapter], a: 1, b: 2)
@@ -24,23 +36,20 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
test "https url with default port" do
uri = URI.parse("https://example.com")
- opts = Gun.options(uri)
+ opts = Gun.options([receive_conn: false], uri)
assert opts[:certificates_verification]
- tls_opts = opts[:tls_opts]
- assert tls_opts[:verify] == :verify_peer
- assert tls_opts[:depth] == 20
- assert tls_opts[:reuse_sessions] == false
+ refute opts[:tls_opts] == []
- assert tls_opts[:verify_fun] ==
+ assert opts[:tls_opts][:verify_fun] ==
{&:ssl_verify_hostname.verify_fun/3, [check_hostname: 'example.com']}
- assert File.exists?(tls_opts[:cacertfile])
+ assert File.exists?(opts[:tls_opts][:cacertfile])
end
test "https ipv4 with default port" do
uri = URI.parse("https://127.0.0.1")
- opts = Gun.options(uri)
+ opts = Gun.options([receive_conn: false], uri)
assert opts[:tls_opts][:verify_fun] ==
{&:ssl_verify_hostname.verify_fun/3, [check_hostname: '127.0.0.1']}
@@ -49,7 +58,7 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
test "https ipv6 with default port" do
uri = URI.parse("https://[2a03:2880:f10c:83:face:b00c:0:25de]")
- opts = Gun.options(uri)
+ opts = Gun.options([receive_conn: false], uri)
assert opts[:tls_opts][:verify_fun] ==
{&:ssl_verify_hostname.verify_fun/3,
@@ -59,32 +68,14 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
test "https url with non standart port" do
uri = URI.parse("https://example.com:115")
- opts = Gun.options(uri)
+ opts = Gun.options([receive_conn: false], uri)
assert opts[:certificates_verification]
assert opts[:transport] == :tls
end
- test "receive conn by default" do
- uri = URI.parse("http://another-domain.com")
- :ok = Conn.open(uri, :gun_connections)
-
- received_opts = Gun.options(uri)
- assert received_opts[:close_conn] == false
- assert is_pid(received_opts[:conn])
- end
-
- test "don't receive conn if receive_conn is false" do
- uri = URI.parse("http://another-domain2.com")
- :ok = Conn.open(uri, :gun_connections)
-
- opts = [receive_conn: false]
- received_opts = Gun.options(opts, uri)
- assert received_opts[:close_conn] == nil
- assert received_opts[:conn] == nil
- end
-
test "get conn on next request" do
+ gun_mock()
level = Application.get_env(:logger, :level)
Logger.configure(level: :debug)
on_exit(fn -> Logger.configure(level: level) end)
@@ -105,12 +96,13 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
end
test "merges with defaul http adapter config" do
- defaults = Gun.options(URI.parse("https://example.com"))
+ defaults = Gun.options([receive_conn: false], URI.parse("https://example.com"))
assert Keyword.has_key?(defaults, :a)
assert Keyword.has_key?(defaults, :b)
end
test "default ssl adapter opts with connection" do
+ gun_mock()
uri = URI.parse("https://some-domain.com")
:ok = Conn.open(uri, :gun_connections)
@@ -118,10 +110,7 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
opts = Gun.options(uri)
assert opts[:certificates_verification]
- tls_opts = opts[:tls_opts]
- assert tls_opts[:verify] == :verify_peer
- assert tls_opts[:depth] == 20
- assert tls_opts[:reuse_sessions] == false
+ refute opts[:tls_opts] == []
assert opts[:close_conn] == false
assert is_pid(opts[:conn])
@@ -158,7 +147,32 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
end
end
+ describe "options/1 with receive_conn parameter" do
+ setup :gun_mock
+
+ test "receive conn by default" do
+ uri = URI.parse("http://another-domain.com")
+ :ok = Conn.open(uri, :gun_connections)
+
+ received_opts = Gun.options(uri)
+ assert received_opts[:close_conn] == false
+ assert is_pid(received_opts[:conn])
+ end
+
+ test "don't receive conn if receive_conn is false" do
+ uri = URI.parse("http://another-domain.com")
+ :ok = Conn.open(uri, :gun_connections)
+
+ opts = [receive_conn: false]
+ received_opts = Gun.options(opts, uri)
+ assert received_opts[:close_conn] == nil
+ assert received_opts[:conn] == nil
+ end
+ end
+
describe "after_request/1" do
+ setup :gun_mock
+
test "body_as not chunks" do
uri = URI.parse("http://some-domain.com")
:ok = Conn.open(uri, :gun_connections)
@@ -223,7 +237,6 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
uri = URI.parse("http://127.0.0.1")
:ok = Conn.open(uri, :gun_connections)
opts = Gun.options(uri)
- send(:gun_connections, {:gun_up, opts[:conn], :http})
:ok = Gun.after_request(opts)
conn = opts[:conn]
@@ -242,7 +255,6 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
uri = URI.parse("http://[2a03:2880:f10c:83:face:b00c:0:25de]")
:ok = Conn.open(uri, :gun_connections)
opts = Gun.options(uri)
- send(:gun_connections, {:gun_up, opts[:conn], :http})
:ok = Gun.after_request(opts)
conn = opts[:conn]
diff --git a/test/http/adapter_helper/hackney_test.exs b/test/http/adapter_helper/hackney_test.exs
index 3306616ef..5fda075f6 100644
--- a/test/http/adapter_helper/hackney_test.exs
+++ b/test/http/adapter_helper/hackney_test.exs
@@ -3,7 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTP.AdapterHelper.HackneyTest do
- use ExUnit.Case
+ use ExUnit.Case, async: true
use Pleroma.Tests.Helpers
alias Pleroma.Config
@@ -20,11 +20,7 @@ defmodule Pleroma.HTTP.AdapterHelper.HackneyTest do
end
test "add proxy and opts from config", %{uri: uri} do
- proxy = Config.get([:http, :proxy_url])
- Config.put([:http, :proxy_url], "localhost:8123")
- on_exit(fn -> Config.put([:http, :proxy_url], proxy) end)
-
- opts = Hackney.options(uri)
+ opts = Hackney.options([proxy: "localhost:8123"], uri)
assert opts[:a] == 1
assert opts[:b] == 2
diff --git a/test/http/connection_test.exs b/test/http/connection_test.exs
index d4db3798c..a5ddfd435 100644
--- a/test/http/connection_test.exs
+++ b/test/http/connection_test.exs
@@ -3,16 +3,16 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTP.ConnectionTest do
- use ExUnit.Case
+ use ExUnit.Case, async: true
use Pleroma.Tests.Helpers
+
import ExUnit.CaptureLog
+ import Mox
+
alias Pleroma.Config
alias Pleroma.HTTP.Connection
- setup_all do
- {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.GunMock)
- :ok
- end
+ setup :verify_on_exit!
describe "parse_host/1" do
test "as atom to charlist" do
@@ -123,16 +123,19 @@ defmodule Pleroma.HTTP.ConnectionTest do
uri = URI.parse("https://some-domain.com")
- pid = Process.whereis(:federation)
- :ok = Pleroma.Gun.Conn.open(uri, :gun_connections, genserver_pid: pid)
+ Pleroma.GunMock
+ |> expect(:open, fn 'some-domain.com', 443, _ ->
+ Task.start_link(fn -> Process.sleep(1000) end)
+ end)
+ |> expect(:await_up, fn _, _ -> {:ok, :http2} end)
+ |> expect(:set_owner, fn _, _ -> :ok end)
+
+ :ok = Pleroma.Gun.Conn.open(uri, :gun_connections)
opts = Connection.options(uri)
assert opts[:certificates_verification]
- tls_opts = opts[:tls_opts]
- assert tls_opts[:verify] == :verify_peer
- assert tls_opts[:depth] == 20
- assert tls_opts[:reuse_sessions] == false
+ refute opts[:tls_opts] == []
assert opts[:close_conn] == false
assert is_pid(opts[:conn])
diff --git a/test/pool/connections_test.exs b/test/pool/connections_test.exs
index 753fd8b0b..06f32b74e 100644
--- a/test/pool/connections_test.exs
+++ b/test/pool/connections_test.exs
@@ -3,39 +3,83 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Pool.ConnectionsTest do
- use ExUnit.Case
+ use ExUnit.Case, async: true
use Pleroma.Tests.Helpers
+
import ExUnit.CaptureLog
+ import Mox
+
alias Pleroma.Gun.Conn
+ alias Pleroma.GunMock
alias Pleroma.Pool.Connections
+ setup :verify_on_exit!
+
setup_all do
+ name = :test_connections
+ {:ok, pid} = Connections.start_link({name, [checkin_timeout: 150]})
{:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.GunMock)
- :ok
+
+ on_exit(fn ->
+ if Process.alive?(pid), do: GenServer.stop(name)
+ end)
+
+ {:ok, name: name}
end
- clear_config([:connections_pool, :retry]) do
- Pleroma.Config.put([:connections_pool, :retry], 5)
+ defp open_mock(num \\ 1) do
+ GunMock
+ |> expect(:open, num, &start_and_register(&1, &2, &3))
+ |> expect(:await_up, num, fn _, _ -> {:ok, :http} end)
+ |> expect(:set_owner, num, fn _, _ -> :ok end)
end
- setup do
- name = :test_connections
- adapter = Application.get_env(:tesla, :adapter)
- Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
+ defp connect_mock(mock) do
+ mock
+ |> expect(:connect, &connect(&1, &2))
+ |> expect(:await, &await(&1, &2))
+ end
- {:ok, pid} = Connections.start_link({name, [max_connections: 2, checkin_timeout: 1_500]})
+ defp info_mock(mock), do: expect(mock, :info, &info(&1))
- on_exit(fn ->
- Application.put_env(:tesla, :adapter, adapter)
+ defp start_and_register('gun-not-up.com', _, _), do: {:error, :timeout}
- if Process.alive?(pid) do
- GenServer.stop(name)
+ defp start_and_register(host, port, _) do
+ {:ok, pid} = Task.start_link(fn -> Process.sleep(1000) end)
+
+ scheme =
+ case port do
+ 443 -> "https"
+ _ -> "http"
end
- end)
- {:ok, name: name}
+ Registry.register(GunMock, pid, %{
+ origin_scheme: scheme,
+ origin_host: host,
+ origin_port: port
+ })
+
+ {:ok, pid}
+ end
+
+ defp info(pid) do
+ [{_, info}] = Registry.lookup(GunMock, pid)
+ info
end
+ defp connect(pid, _) do
+ ref = make_ref()
+ Registry.register(GunMock, ref, pid)
+ ref
+ end
+
+ defp await(pid, ref) do
+ [{_, ^pid}] = Registry.lookup(GunMock, ref)
+ {:response, :fin, 200, []}
+ end
+
+ defp now, do: :os.system_time(:second)
+
describe "alive?/2" do
test "is alive", %{name: name} do
assert Connections.alive?(name)
@@ -47,6 +91,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "opens connection and reuse it on next request", %{name: name} do
+ open_mock()
url = "http://some-domain.com"
key = "http:some-domain.com:80"
refute Connections.checkin(url, name)
@@ -112,6 +157,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "reuse connection for idna domains", %{name: name} do
+ open_mock()
url = "http://ですsome-domain.com"
refute Connections.checkin(url, name)
@@ -140,6 +186,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "reuse for ipv4", %{name: name} do
+ open_mock()
url = "http://127.0.0.1"
refute Connections.checkin(url, name)
@@ -183,6 +230,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "reuse for ipv6", %{name: name} do
+ open_mock()
url = "http://[2a03:2880:f10c:83:face:b00c:0:25de]"
refute Connections.checkin(url, name)
@@ -212,6 +260,10 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "up and down ipv4", %{name: name} do
+ open_mock()
+ |> info_mock()
+ |> allow(self(), name)
+
self = self()
url = "http://127.0.0.1"
:ok = Conn.open(url, name)
@@ -233,6 +285,11 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "up and down ipv6", %{name: name} do
self = self()
+
+ open_mock()
+ |> info_mock()
+ |> allow(self, name)
+
url = "http://[2a03:2880:f10c:83:face:b00c:0:25de]"
:ok = Conn.open(url, name)
conn = Connections.checkin(url, name)
@@ -252,6 +309,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "reuses connection based on protocol", %{name: name} do
+ open_mock(2)
http_url = "http://some-domain.com"
http_key = "http:some-domain.com:80"
https_url = "https://some-domain.com"
@@ -290,6 +348,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "connection can't get up", %{name: name} do
+ expect(GunMock, :open, &start_and_register(&1, &2, &3))
url = "http://gun-not-up.com"
assert capture_log(fn ->
@@ -301,6 +360,11 @@ defmodule Pleroma.Pool.ConnectionsTest do
test "process gun_down message and then gun_up", %{name: name} do
self = self()
+
+ open_mock()
+ |> info_mock()
+ |> allow(self, name)
+
url = "http://gun-down-and-up.com"
key = "http:gun-down-and-up.com:80"
:ok = Conn.open(url, name)
@@ -351,6 +415,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "async processes get same conn for same domain", %{name: name} do
+ open_mock()
url = "http://some-domain.com"
:ok = Conn.open(url, name)
@@ -383,6 +448,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "remove frequently used and idle", %{name: name} do
+ open_mock(3)
self = self()
http_url = "http://some-domain.com"
https_url = "https://some-domain.com"
@@ -437,6 +503,9 @@ defmodule Pleroma.Pool.ConnectionsTest do
describe "with proxy" do
test "as ip", %{name: name} do
+ open_mock()
+ |> connect_mock()
+
url = "http://proxy-string.com"
key = "http:proxy-string.com:80"
:ok = Conn.open(url, name, proxy: {{127, 0, 0, 1}, 8123})
@@ -458,6 +527,9 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "as host", %{name: name} do
+ open_mock()
+ |> connect_mock()
+
url = "http://proxy-tuple-atom.com"
:ok = Conn.open(url, name, proxy: {'localhost', 9050})
conn = Connections.checkin(url, name)
@@ -477,6 +549,9 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "as ip and ssl", %{name: name} do
+ open_mock()
+ |> connect_mock()
+
url = "https://proxy-string.com"
:ok = Conn.open(url, name, proxy: {{127, 0, 0, 1}, 8123})
@@ -497,6 +572,9 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "as host and ssl", %{name: name} do
+ open_mock()
+ |> connect_mock()
+
url = "https://proxy-tuple-atom.com"
:ok = Conn.open(url, name, proxy: {'localhost', 9050})
conn = Connections.checkin(url, name)
@@ -516,6 +594,8 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "with socks type", %{name: name} do
+ open_mock()
+
url = "http://proxy-socks.com"
:ok = Conn.open(url, name, proxy: {:socks5, 'localhost', 1234})
@@ -537,6 +617,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
test "with socks4 type and ssl", %{name: name} do
+ open_mock()
url = "https://proxy-socks.com"
:ok = Conn.open(url, name, proxy: {:socks4, 'localhost', 1234})
@@ -667,15 +748,13 @@ defmodule Pleroma.Pool.ConnectionsTest do
end
end
- test "count/1", %{name: name} do
+ test "count/1" do
+ name = :test_count
+ {:ok, _} = Connections.start_link({name, [checkin_timeout: 150]})
assert Connections.count(name) == 0
Connections.add_conn(name, "1", %Conn{conn: self()})
assert Connections.count(name) == 1
Connections.remove_conn(name, "1")
assert Connections.count(name) == 0
end
-
- defp now do
- :os.system_time(:second)
- end
end
diff --git a/test/support/gun_mock.ex b/test/support/gun_mock.ex
deleted file mode 100644
index 9d664e366..000000000
--- a/test/support/gun_mock.ex
+++ /dev/null
@@ -1,155 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.GunMock do
- @behaviour Pleroma.Gun
-
- alias Pleroma.Gun
- alias Pleroma.GunMock
-
- @impl Gun
- def open('some-domain.com', 443, _) do
- {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
-
- Registry.register(GunMock, conn_pid, %{
- origin_scheme: "https",
- origin_host: 'some-domain.com',
- origin_port: 443
- })
-
- {:ok, conn_pid}
- end
-
- @impl Gun
- def open(ip, port, _)
- when ip in [{10_755, 10_368, 61_708, 131, 64_206, 45_068, 0, 9_694}, {127, 0, 0, 1}] and
- port in [80, 443] do
- {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
-
- scheme = if port == 443, do: "https", else: "http"
-
- Registry.register(GunMock, conn_pid, %{
- origin_scheme: scheme,
- origin_host: ip,
- origin_port: port
- })
-
- {:ok, conn_pid}
- end
-
- @impl Gun
- def open('localhost', 1234, %{
- protocols: [:socks],
- proxy: {:socks5, 'localhost', 1234},
- socks_opts: %{host: 'proxy-socks.com', port: 80, version: 5}
- }) do
- {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
-
- Registry.register(GunMock, conn_pid, %{
- origin_scheme: "http",
- origin_host: 'proxy-socks.com',
- origin_port: 80
- })
-
- {:ok, conn_pid}
- end
-
- @impl Gun
- def open('localhost', 1234, %{
- protocols: [:socks],
- proxy: {:socks4, 'localhost', 1234},
- socks_opts: %{
- host: 'proxy-socks.com',
- port: 443,
- protocols: [:http2],
- tls_opts: [],
- transport: :tls,
- version: 4
- }
- }) do
- {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
-
- Registry.register(GunMock, conn_pid, %{
- origin_scheme: "https",
- origin_host: 'proxy-socks.com',
- origin_port: 443
- })
-
- {:ok, conn_pid}
- end
-
- @impl Gun
- def open('gun-not-up.com', 80, _opts), do: {:error, :timeout}
-
- @impl Gun
- def open('example.com', port, _) when port in [443, 115] do
- {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
-
- Registry.register(GunMock, conn_pid, %{
- origin_scheme: "https",
- origin_host: 'example.com',
- origin_port: 443
- })
-
- {:ok, conn_pid}
- end
-
- @impl Gun
- def open(domain, 80, _) do
- {:ok, conn_pid} = Task.start_link(fn -> Process.sleep(1_000) end)
-
- Registry.register(GunMock, conn_pid, %{
- origin_scheme: "http",
- origin_host: domain,
- origin_port: 80
- })
-
- {:ok, conn_pid}
- end
-
- @impl Gun
- def open({127, 0, 0, 1}, 8123, _) do
- Task.start_link(fn -> Process.sleep(1_000) end)
- end
-
- @impl Gun
- def open('localhost', 9050, _) do
- Task.start_link(fn -> Process.sleep(1_000) end)
- end
-
- @impl Gun
- def await_up(_pid, _timeout), do: {:ok, :http}
-
- @impl Gun
- def set_owner(_pid, _owner), do: :ok
-
- @impl Gun
- def connect(pid, %{host: _, port: 80}) do
- ref = make_ref()
- Registry.register(GunMock, ref, pid)
- ref
- end
-
- @impl Gun
- def connect(pid, %{host: _, port: 443, protocols: [:http2], transport: :tls}) do
- ref = make_ref()
- Registry.register(GunMock, ref, pid)
- ref
- end
-
- @impl Gun
- def await(pid, ref) do
- [{_, ^pid}] = Registry.lookup(GunMock, ref)
- {:response, :fin, 200, []}
- end
-
- @impl Gun
- def info(pid) do
- [{_, info}] = Registry.lookup(GunMock, pid)
- info
- end
-
- @impl Gun
- def close(_pid), do: :ok
-end
diff --git a/test/test_helper.exs b/test/test_helper.exs
index 6b91d2b46..ee880e226 100644
--- a/test/test_helper.exs
+++ b/test/test_helper.exs
@@ -6,7 +6,10 @@ os_exclude = if :os.type() == {:unix, :darwin}, do: [skip_on_mac: true], else: [
ExUnit.start(exclude: [:federated | os_exclude])
Ecto.Adapters.SQL.Sandbox.mode(Pleroma.Repo, :manual)
+
Mox.defmock(Pleroma.ReverseProxy.ClientMock, for: Pleroma.ReverseProxy.Client)
+Mox.defmock(Pleroma.GunMock, for: Pleroma.Gun)
+
{:ok, _} = Application.ensure_all_started(:ex_machina)
ExUnit.after_suite(fn _results ->
--
cgit v1.2.3
From 14678a7708fb43e60f2f3b610f15d5090616d85c Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Sat, 7 Mar 2020 10:12:34 +0300
Subject: using `stub` instead `expect`
---
test/http/adapter_helper/gun_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/http/adapter_helper/gun_test.exs b/test/http/adapter_helper/gun_test.exs
index b1b34858a..c65b89786 100644
--- a/test/http/adapter_helper/gun_test.exs
+++ b/test/http/adapter_helper/gun_test.exs
@@ -23,7 +23,7 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
defp gun_mock do
Pleroma.GunMock
- |> expect(:open, fn _, _, _ -> Task.start_link(fn -> Process.sleep(1000) end) end)
+ |> stub(:open, fn _, _, _ -> Task.start_link(fn -> Process.sleep(1000) end) end)
|> expect(:await_up, fn _, _ -> {:ok, :http} end)
|> expect(:set_owner, fn _, _ -> :ok end)
end
--
cgit v1.2.3
From 9f884a263904c8b243507d35b29da712a31fb444 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Sat, 7 Mar 2020 11:01:37 +0300
Subject: tests changes
---
test/http/adapter_helper/gun_test.exs | 4 +--
test/http/connection_test.exs | 28 -------------------
test/http_test.exs | 2 +-
test/reverse_proxy/reverse_proxy_test.exs | 45 ++++++++++++++++---------------
4 files changed, 27 insertions(+), 52 deletions(-)
(limited to 'test')
diff --git a/test/http/adapter_helper/gun_test.exs b/test/http/adapter_helper/gun_test.exs
index c65b89786..66622b605 100644
--- a/test/http/adapter_helper/gun_test.exs
+++ b/test/http/adapter_helper/gun_test.exs
@@ -24,8 +24,8 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
defp gun_mock do
Pleroma.GunMock
|> stub(:open, fn _, _, _ -> Task.start_link(fn -> Process.sleep(1000) end) end)
- |> expect(:await_up, fn _, _ -> {:ok, :http} end)
- |> expect(:set_owner, fn _, _ -> :ok end)
+ |> stub(:await_up, fn _, _ -> {:ok, :http} end)
+ |> stub(:set_owner, fn _, _ -> :ok end)
end
describe "options/1" do
diff --git a/test/http/connection_test.exs b/test/http/connection_test.exs
index a5ddfd435..25a2bac1c 100644
--- a/test/http/connection_test.exs
+++ b/test/http/connection_test.exs
@@ -7,13 +7,10 @@ defmodule Pleroma.HTTP.ConnectionTest do
use Pleroma.Tests.Helpers
import ExUnit.CaptureLog
- import Mox
alias Pleroma.Config
alias Pleroma.HTTP.Connection
- setup :verify_on_exit!
-
describe "parse_host/1" do
test "as atom to charlist" do
assert Connection.parse_host(:localhost) == 'localhost'
@@ -115,30 +112,5 @@ defmodule Pleroma.HTTP.ConnectionTest do
assert opts[:proxy] == {'example.com', 4321}
end
-
- test "default ssl adapter opts with connection" do
- adapter = Application.get_env(:tesla, :adapter)
- Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
- on_exit(fn -> Application.put_env(:tesla, :adapter, adapter) end)
-
- uri = URI.parse("https://some-domain.com")
-
- Pleroma.GunMock
- |> expect(:open, fn 'some-domain.com', 443, _ ->
- Task.start_link(fn -> Process.sleep(1000) end)
- end)
- |> expect(:await_up, fn _, _ -> {:ok, :http2} end)
- |> expect(:set_owner, fn _, _ -> :ok end)
-
- :ok = Pleroma.Gun.Conn.open(uri, :gun_connections)
-
- opts = Connection.options(uri)
-
- assert opts[:certificates_verification]
- refute opts[:tls_opts] == []
-
- assert opts[:close_conn] == false
- assert is_pid(opts[:conn])
- end
end
end
diff --git a/test/http_test.exs b/test/http_test.exs
index fd254b590..618485b55 100644
--- a/test/http_test.exs
+++ b/test/http_test.exs
@@ -3,7 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTPTest do
- use ExUnit.Case
+ use ExUnit.Case, async: true
use Pleroma.Tests.Helpers
import Tesla.Mock
alias Pleroma.HTTP
diff --git a/test/reverse_proxy/reverse_proxy_test.exs b/test/reverse_proxy/reverse_proxy_test.exs
index c17ab0f89..abdfddcb7 100644
--- a/test/reverse_proxy/reverse_proxy_test.exs
+++ b/test/reverse_proxy/reverse_proxy_test.exs
@@ -3,14 +3,17 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.ReverseProxyTest do
- use Pleroma.Web.ConnCase
+ use Pleroma.Web.ConnCase, async: true
+
import ExUnit.CaptureLog
import Mox
+
alias Pleroma.ReverseProxy
alias Pleroma.ReverseProxy.ClientMock
+ alias Plug.Conn
setup_all do
- {:ok, _} = Registry.start_link(keys: :unique, name: Pleroma.ReverseProxy.ClientMock)
+ {:ok, _} = Registry.start_link(keys: :unique, name: ClientMock)
:ok
end
@@ -21,7 +24,7 @@ defmodule Pleroma.ReverseProxyTest do
ClientMock
|> expect(:request, fn :get, url, _, _, _ ->
- Registry.register(Pleroma.ReverseProxy.ClientMock, url, 0)
+ Registry.register(ClientMock, url, 0)
{:ok, 200,
[
@@ -30,13 +33,13 @@ defmodule Pleroma.ReverseProxyTest do
], %{url: url}}
end)
|> expect(:stream_body, invokes, fn %{url: url} = client ->
- case Registry.lookup(Pleroma.ReverseProxy.ClientMock, url) do
+ case Registry.lookup(ClientMock, url) do
[{_, 0}] ->
- Registry.update_value(Pleroma.ReverseProxy.ClientMock, url, &(&1 + 1))
+ Registry.update_value(ClientMock, url, &(&1 + 1))
{:ok, json, client}
[{_, 1}] ->
- Registry.unregister(Pleroma.ReverseProxy.ClientMock, url)
+ Registry.unregister(ClientMock, url)
:done
end
end)
@@ -81,7 +84,7 @@ defmodule Pleroma.ReverseProxyTest do
defp stream_mock(invokes, with_close? \\ false) do
ClientMock
|> expect(:request, fn :get, "/stream-bytes/" <> length, _, _, _ ->
- Registry.register(Pleroma.ReverseProxy.ClientMock, "/stream-bytes/" <> length, 0)
+ Registry.register(ClientMock, "/stream-bytes/" <> length, 0)
{:ok, 200, [{"content-type", "application/octet-stream"}],
%{url: "/stream-bytes/" <> length}}
@@ -89,10 +92,10 @@ defmodule Pleroma.ReverseProxyTest do
|> expect(:stream_body, invokes, fn %{url: "/stream-bytes/" <> length} = client ->
max = String.to_integer(length)
- case Registry.lookup(Pleroma.ReverseProxy.ClientMock, "/stream-bytes/" <> length) do
+ case Registry.lookup(ClientMock, "/stream-bytes/" <> length) do
[{_, current}] when current < max ->
Registry.update_value(
- Pleroma.ReverseProxy.ClientMock,
+ ClientMock,
"/stream-bytes/" <> length,
&(&1 + 10)
)
@@ -100,7 +103,7 @@ defmodule Pleroma.ReverseProxyTest do
{:ok, "0123456789", client}
[{_, ^max}] ->
- Registry.unregister(Pleroma.ReverseProxy.ClientMock, "/stream-bytes/" <> length)
+ Registry.unregister(ClientMock, "/stream-bytes/" <> length)
:done
end
end)
@@ -214,24 +217,24 @@ defmodule Pleroma.ReverseProxyTest do
conn = ReverseProxy.call(conn, "/stream-bytes/200")
assert conn.state == :chunked
assert byte_size(conn.resp_body) == 200
- assert Plug.Conn.get_resp_header(conn, "content-type") == ["application/octet-stream"]
+ assert Conn.get_resp_header(conn, "content-type") == ["application/octet-stream"]
end
defp headers_mock(_) do
ClientMock
|> expect(:request, fn :get, "/headers", headers, _, _ ->
- Registry.register(Pleroma.ReverseProxy.ClientMock, "/headers", 0)
+ Registry.register(ClientMock, "/headers", 0)
{:ok, 200, [{"content-type", "application/json"}], %{url: "/headers", headers: headers}}
end)
|> expect(:stream_body, 2, fn %{url: url, headers: headers} = client ->
- case Registry.lookup(Pleroma.ReverseProxy.ClientMock, url) do
+ case Registry.lookup(ClientMock, url) do
[{_, 0}] ->
- Registry.update_value(Pleroma.ReverseProxy.ClientMock, url, &(&1 + 1))
+ Registry.update_value(ClientMock, url, &(&1 + 1))
headers = for {k, v} <- headers, into: %{}, do: {String.capitalize(k), v}
{:ok, Jason.encode!(%{headers: headers}), client}
[{_, 1}] ->
- Registry.unregister(Pleroma.ReverseProxy.ClientMock, url)
+ Registry.unregister(ClientMock, url)
:done
end
end)
@@ -244,7 +247,7 @@ defmodule Pleroma.ReverseProxyTest do
test "header passes", %{conn: conn} do
conn =
- Plug.Conn.put_req_header(
+ Conn.put_req_header(
conn,
"accept",
"text/html"
@@ -257,7 +260,7 @@ defmodule Pleroma.ReverseProxyTest do
test "header is filtered", %{conn: conn} do
conn =
- Plug.Conn.put_req_header(
+ Conn.put_req_header(
conn,
"accept-language",
"en-US"
@@ -301,18 +304,18 @@ defmodule Pleroma.ReverseProxyTest do
defp disposition_headers_mock(headers) do
ClientMock
|> expect(:request, fn :get, "/disposition", _, _, _ ->
- Registry.register(Pleroma.ReverseProxy.ClientMock, "/disposition", 0)
+ Registry.register(ClientMock, "/disposition", 0)
{:ok, 200, headers, %{url: "/disposition"}}
end)
|> expect(:stream_body, 2, fn %{url: "/disposition"} = client ->
- case Registry.lookup(Pleroma.ReverseProxy.ClientMock, "/disposition") do
+ case Registry.lookup(ClientMock, "/disposition") do
[{_, 0}] ->
- Registry.update_value(Pleroma.ReverseProxy.ClientMock, "/disposition", &(&1 + 1))
+ Registry.update_value(ClientMock, "/disposition", &(&1 + 1))
{:ok, "", client}
[{_, 1}] ->
- Registry.unregister(Pleroma.ReverseProxy.ClientMock, "/disposition")
+ Registry.unregister(ClientMock, "/disposition")
:done
end
end)
--
cgit v1.2.3
From 426f5ee48a09dbf321c013db08cc849c8929d86d Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 10 Mar 2020 15:31:44 +0300
Subject: tesla adapter can't be changed in adminFE
---
test/web/admin_api/admin_api_controller_test.exs | 21 ++-------------------
1 file changed, 2 insertions(+), 19 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index d6b839948..76240e5bc 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -2513,8 +2513,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
"value" => "Tesla.Adapter.Httpc",
"db" => [":adapter"]
}
- ],
- "need_reboot" => true
+ ]
}
end
@@ -2586,9 +2585,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
test "common config example", %{conn: conn} do
- adapter = Application.get_env(:tesla, :adapter)
- on_exit(fn -> Application.put_env(:tesla, :adapter, adapter) end)
-
conn =
post(conn, "/api/pleroma/admin/config", %{
configs: [
@@ -2607,16 +2603,10 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
%{"tuple" => [":regex4", "~r/https:\/\/example.com/s"]},
%{"tuple" => [":name", "Pleroma"]}
]
- },
- %{
- "group" => ":tesla",
- "key" => ":adapter",
- "value" => "Tesla.Adapter.Httpc"
}
]
})
- assert Application.get_env(:tesla, :adapter) == Tesla.Adapter.Httpc
assert Config.get([Pleroma.Captcha.NotReal, :name]) == "Pleroma"
assert json_response(conn, 200) == %{
@@ -2648,15 +2638,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
":regex4",
":name"
]
- },
- %{
- "group" => ":tesla",
- "key" => ":adapter",
- "value" => "Tesla.Adapter.Httpc",
- "db" => [":adapter"]
}
- ],
- "need_reboot" => true
+ ]
}
end
--
cgit v1.2.3
From f39e1b9eff859c0795911212c59304f68fca92bc Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 10 Mar 2020 15:54:11 +0300
Subject: add verify tls_opts only when we open connection
for other requests tesla will add tls_opts
---
test/http/adapter_helper/gun_test.exs | 37 +++++------------------------------
test/http/connection_test.exs | 19 ++++++++++++++++++
2 files changed, 24 insertions(+), 32 deletions(-)
(limited to 'test')
diff --git a/test/http/adapter_helper/gun_test.exs b/test/http/adapter_helper/gun_test.exs
index 66622b605..6af8be15d 100644
--- a/test/http/adapter_helper/gun_test.exs
+++ b/test/http/adapter_helper/gun_test.exs
@@ -38,31 +38,23 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
opts = Gun.options([receive_conn: false], uri)
assert opts[:certificates_verification]
- refute opts[:tls_opts] == []
-
- assert opts[:tls_opts][:verify_fun] ==
- {&:ssl_verify_hostname.verify_fun/3, [check_hostname: 'example.com']}
-
- assert File.exists?(opts[:tls_opts][:cacertfile])
+ assert opts[:tls_opts][:log_level] == :warning
end
test "https ipv4 with default port" do
uri = URI.parse("https://127.0.0.1")
opts = Gun.options([receive_conn: false], uri)
-
- assert opts[:tls_opts][:verify_fun] ==
- {&:ssl_verify_hostname.verify_fun/3, [check_hostname: '127.0.0.1']}
+ assert opts[:certificates_verification]
+ assert opts[:tls_opts][:log_level] == :warning
end
test "https ipv6 with default port" do
uri = URI.parse("https://[2a03:2880:f10c:83:face:b00c:0:25de]")
opts = Gun.options([receive_conn: false], uri)
-
- assert opts[:tls_opts][:verify_fun] ==
- {&:ssl_verify_hostname.verify_fun/3,
- [check_hostname: '2a03:2880:f10c:83:face:b00c:0:25de']}
+ assert opts[:certificates_verification]
+ assert opts[:tls_opts][:log_level] == :warning
end
test "https url with non standart port" do
@@ -269,23 +261,4 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
} = Connections.get_state(:gun_connections)
end
end
-
- describe "format_host/1" do
- test "with domain" do
- assert Gun.format_host("example.com") == 'example.com'
- end
-
- test "with idna domain" do
- assert Gun.format_host("ですexample.com") == 'xn--example-183fne.com'
- end
-
- test "with ipv4" do
- assert Gun.format_host("127.0.0.1") == '127.0.0.1'
- end
-
- test "with ipv6" do
- assert Gun.format_host("2a03:2880:f10c:83:face:b00c:0:25de") ==
- '2a03:2880:f10c:83:face:b00c:0:25de'
- end
- end
end
diff --git a/test/http/connection_test.exs b/test/http/connection_test.exs
index 25a2bac1c..0f62eddd2 100644
--- a/test/http/connection_test.exs
+++ b/test/http/connection_test.exs
@@ -113,4 +113,23 @@ defmodule Pleroma.HTTP.ConnectionTest do
assert opts[:proxy] == {'example.com', 4321}
end
end
+
+ describe "format_host/1" do
+ test "with domain" do
+ assert Connection.format_host("example.com") == 'example.com'
+ end
+
+ test "with idna domain" do
+ assert Connection.format_host("ですexample.com") == 'xn--example-183fne.com'
+ end
+
+ test "with ipv4" do
+ assert Connection.format_host("127.0.0.1") == '127.0.0.1'
+ end
+
+ test "with ipv6" do
+ assert Connection.format_host("2a03:2880:f10c:83:face:b00c:0:25de") ==
+ '2a03:2880:f10c:83:face:b00c:0:25de'
+ end
+ end
end
--
cgit v1.2.3
From 863ec33ba2a90708d199f18683ffe0c4658c710a Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Wed, 11 Mar 2020 12:21:44 +0100
Subject: Add support for funkwhale Audio activity
reel2bits fixture not included as it lacks the Actor fixture for it.
Closes: https://git.pleroma.social/pleroma/pleroma/issues/1624
Closes: https://git.pleroma.social/pleroma/pleroma/issues/764
---
test/fixtures/tesla_mock/funkwhale_audio.json | 44 ++++++++++++++++++++++++
test/fixtures/tesla_mock/funkwhale_channel.json | 44 ++++++++++++++++++++++++
test/support/http_request_mock.ex | 15 ++++++++
test/web/mastodon_api/views/status_view_test.exs | 16 +++++++++
test/web/oauth/oauth_controller_test.exs | 2 +-
5 files changed, 120 insertions(+), 1 deletion(-)
create mode 100644 test/fixtures/tesla_mock/funkwhale_audio.json
create mode 100644 test/fixtures/tesla_mock/funkwhale_channel.json
(limited to 'test')
diff --git a/test/fixtures/tesla_mock/funkwhale_audio.json b/test/fixtures/tesla_mock/funkwhale_audio.json
new file mode 100644
index 000000000..15736b1f8
--- /dev/null
+++ b/test/fixtures/tesla_mock/funkwhale_audio.json
@@ -0,0 +1,44 @@
+{
+ "id": "https://channels.tests.funkwhale.audio/federation/music/uploads/42342395-0208-4fee-a38d-259a6dae0871",
+ "type": "Audio",
+ "name": "Compositions - Test Audio for Pleroma",
+ "attributedTo": "https://channels.tests.funkwhale.audio/federation/actors/compositions",
+ "published": "2020-03-11T10:01:52.714918+00:00",
+ "to": "https://www.w3.org/ns/activitystreams#Public",
+ "url": [
+ {
+ "type": "Link",
+ "mimeType": "audio/ogg",
+ "href": "https://channels.tests.funkwhale.audio/api/v1/listen/3901e5d8-0445-49d5-9711-e096cf32e515/?upload=42342395-0208-4fee-a38d-259a6dae0871&download=false"
+ },
+ {
+ "type": "Link",
+ "mimeType": "text/html",
+ "href": "https://channels.tests.funkwhale.audio/library/tracks/74"
+ }
+ ],
+ "content": "This is a test Audio for Pleroma.
",
+ "mediaType": "text/html",
+ "tag": [
+ {
+ "type": "Hashtag",
+ "name": "#funkwhale"
+ },
+ {
+ "type": "Hashtag",
+ "name": "#test"
+ },
+ {
+ "type": "Hashtag",
+ "name": "#tests"
+ }
+ ],
+ "summary": "#funkwhale #test #tests",
+ "@context": [
+ "https://www.w3.org/ns/activitystreams",
+ "https://w3id.org/security/v1",
+ {
+ "manuallyApprovesFollowers": "as:manuallyApprovesFollowers"
+ }
+ ]
+}
diff --git a/test/fixtures/tesla_mock/funkwhale_channel.json b/test/fixtures/tesla_mock/funkwhale_channel.json
new file mode 100644
index 000000000..cf9ee8151
--- /dev/null
+++ b/test/fixtures/tesla_mock/funkwhale_channel.json
@@ -0,0 +1,44 @@
+{
+ "id": "https://channels.tests.funkwhale.audio/federation/actors/compositions",
+ "outbox": "https://channels.tests.funkwhale.audio/federation/actors/compositions/outbox",
+ "inbox": "https://channels.tests.funkwhale.audio/federation/actors/compositions/inbox",
+ "preferredUsername": "compositions",
+ "type": "Person",
+ "name": "Compositions",
+ "followers": "https://channels.tests.funkwhale.audio/federation/actors/compositions/followers",
+ "following": "https://channels.tests.funkwhale.audio/federation/actors/compositions/following",
+ "manuallyApprovesFollowers": false,
+ "url": [
+ {
+ "type": "Link",
+ "href": "https://channels.tests.funkwhale.audio/channels/compositions",
+ "mediaType": "text/html"
+ },
+ {
+ "type": "Link",
+ "href": "https://channels.tests.funkwhale.audio/api/v1/channels/compositions/rss",
+ "mediaType": "application/rss+xml"
+ }
+ ],
+ "icon": {
+ "type": "Image",
+ "url": "https://channels.tests.funkwhale.audio/media/attachments/75/b4/f1/nosmile.jpeg",
+ "mediaType": "image/jpeg"
+ },
+ "summary": "I'm testing federation with the fediverse :)
",
+ "@context": [
+ "https://www.w3.org/ns/activitystreams",
+ "https://w3id.org/security/v1",
+ {
+ "manuallyApprovesFollowers": "as:manuallyApprovesFollowers"
+ }
+ ],
+ "publicKey": {
+ "owner": "https://channels.tests.funkwhale.audio/federation/actors/compositions",
+ "publicKeyPem": "-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAv25u57oZfVLV3KltS+HcsdSx9Op4MmzIes1J8Wu8s0KbdXf2zEwS\nsVqyHgs/XCbnzsR3FqyJTo46D2BVnvZcuU5srNcR2I2HMaqQ0oVdnATE4K6KdcgV\nN+98pMWo56B8LTgE1VpvqbsrXLi9jCTzjrkebVMOP+ZVu+64v1qdgddseblYMnBZ\nct0s7ONbHnqrWlTGf5wES1uIZTVdn5r4MduZG+Uenfi1opBS0lUUxfWdW9r0oF2b\nyneZUyaUCbEroeKbqsweXCWVgnMarUOsgqC42KM4cf95lySSwTSaUtZYIbTw7s9W\n2jveU/rVg8BYZu5JK5obgBoxtlUeUoSswwIDAQAB\n-----END RSA PUBLIC KEY-----\n",
+ "id": "https://channels.tests.funkwhale.audio/federation/actors/compositions#main-key"
+ },
+ "endpoints": {
+ "sharedInbox": "https://channels.tests.funkwhale.audio/federation/shared/inbox"
+ }
+}
diff --git a/test/support/http_request_mock.ex b/test/support/http_request_mock.ex
index d46887865..0079d8c44 100644
--- a/test/support/http_request_mock.ex
+++ b/test/support/http_request_mock.ex
@@ -1273,6 +1273,21 @@ defmodule HttpRequestMock do
{:ok, %Tesla.Env{status: 200, body: File.read!("test/fixtures/tesla_mock/rin.json")}}
end
+ def get(
+ "https://channels.tests.funkwhale.audio/federation/music/uploads/42342395-0208-4fee-a38d-259a6dae0871",
+ _,
+ _,
+ _
+ ) do
+ {:ok,
+ %Tesla.Env{status: 200, body: File.read!("test/fixtures/tesla_mock/funkwhale_audio.json")}}
+ end
+
+ def get("https://channels.tests.funkwhale.audio/federation/actors/compositions", _, _, _) do
+ {:ok,
+ %Tesla.Env{status: 200, body: File.read!("test/fixtures/tesla_mock/funkwhale_channel.json")}}
+ end
+
def get("http://example.com/rel_me/error", _, _, _) do
{:ok, %Tesla.Env{status: 404, body: ""}}
end
diff --git a/test/web/mastodon_api/views/status_view_test.exs b/test/web/mastodon_api/views/status_view_test.exs
index 191895c6f..3e1812a1f 100644
--- a/test/web/mastodon_api/views/status_view_test.exs
+++ b/test/web/mastodon_api/views/status_view_test.exs
@@ -420,6 +420,22 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
assert length(represented[:media_attachments]) == 1
end
+ test "funkwhale audio" do
+ user = insert(:user)
+
+ {:ok, object} =
+ Pleroma.Object.Fetcher.fetch_object_from_id(
+ "https://channels.tests.funkwhale.audio/federation/music/uploads/42342395-0208-4fee-a38d-259a6dae0871"
+ )
+
+ %Activity{} = activity = Activity.get_create_by_object_ap_id(object.data["id"])
+
+ represented = StatusView.render("show.json", %{for: user, activity: activity})
+
+ assert represented[:id] == to_string(activity.id)
+ assert length(represented[:media_attachments]) == 1
+ end
+
test "a Mobilizon event" do
user = insert(:user)
diff --git a/test/web/oauth/oauth_controller_test.exs b/test/web/oauth/oauth_controller_test.exs
index cff469c28..5f86d999c 100644
--- a/test/web/oauth/oauth_controller_test.exs
+++ b/test/web/oauth/oauth_controller_test.exs
@@ -581,7 +581,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
# In case scope param is missing, expecting _all_ app-supported scopes to be granted
for user <- [non_admin, admin],
{requested_scopes, expected_scopes} <-
- %{scopes_subset => scopes_subset, nil => app_scopes} do
+ %{scopes_subset => scopes_subset, nil: app_scopes} do
conn =
post(
build_conn(),
--
cgit v1.2.3
From 1306b92997dc6e76e5d617d529dbc229d5aee200 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Thu, 12 Mar 2020 18:28:54 +0300
Subject: clean up
---
test/http/adapter_helper/gun_test.exs | 12 ++++--------
test/pool/connections_test.exs | 2 +-
2 files changed, 5 insertions(+), 9 deletions(-)
(limited to 'test')
diff --git a/test/http/adapter_helper/gun_test.exs b/test/http/adapter_helper/gun_test.exs
index 6af8be15d..18025b986 100644
--- a/test/http/adapter_helper/gun_test.exs
+++ b/test/http/adapter_helper/gun_test.exs
@@ -6,7 +6,6 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
use ExUnit.Case, async: true
use Pleroma.Tests.Helpers
- import ExUnit.CaptureLog
import Mox
alias Pleroma.Config
@@ -63,7 +62,6 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
opts = Gun.options([receive_conn: false], uri)
assert opts[:certificates_verification]
- assert opts[:transport] == :tls
end
test "get conn on next request" do
@@ -73,14 +71,12 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
on_exit(fn -> Logger.configure(level: level) end)
uri = URI.parse("http://some-domain2.com")
- assert capture_log(fn ->
- opts = Gun.options(uri)
+ opts = Gun.options(uri)
- assert opts[:conn] == nil
- assert opts[:close_conn] == nil
- end) =~
- "Gun connections pool checkin was not successful. Trying to open conn for next request."
+ assert opts[:conn] == nil
+ assert opts[:close_conn] == nil
+ Process.sleep(50)
opts = Gun.options(uri)
assert is_pid(opts[:conn])
diff --git a/test/pool/connections_test.exs b/test/pool/connections_test.exs
index 06f32b74e..aeda54875 100644
--- a/test/pool/connections_test.exs
+++ b/test/pool/connections_test.exs
@@ -355,7 +355,7 @@ defmodule Pleroma.Pool.ConnectionsTest do
refute Conn.open(url, name)
refute Connections.checkin(url, name)
end) =~
- "Received error on opening connection http://gun-not-up.com {:error, :timeout}"
+ "Opening connection to http://gun-not-up.com failed with error {:error, :timeout}"
end
test "process gun_down message and then gun_up", %{name: name} do
--
cgit v1.2.3
From 7c8003c3fcdcab075b9722ab236bf2d1d0e0e8cd Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Sun, 15 Mar 2020 21:00:12 +0300
Subject: [#1364] Improved control over generation / sending of notifications.
Fixed blocking / muting users notifications issue. Added tests.
---
test/notification_test.exs | 112 ++++++++++++++++++++++++++++++++++++++++++---
1 file changed, 106 insertions(+), 6 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 56a581810..bc2d80f05 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -6,12 +6,14 @@ defmodule Pleroma.NotificationTest do
use Pleroma.DataCase
import Pleroma.Factory
+ import Mock
alias Pleroma.Notification
alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
alias Pleroma.Web.ActivityPub.Transmogrifier
alias Pleroma.Web.CommonAPI
+ alias Pleroma.Web.Push
alias Pleroma.Web.Streamer
describe "create_notifications" do
@@ -382,7 +384,7 @@ defmodule Pleroma.NotificationTest do
end
end
- describe "notification target determination" do
+ describe "notification target determination / get_notified_from_activity/2" do
test "it sends notifications to addressed users in new messages" do
user = insert(:user)
other_user = insert(:user)
@@ -392,7 +394,9 @@ defmodule Pleroma.NotificationTest do
"status" => "hey @#{other_user.nickname}!"
})
- assert other_user in Notification.get_notified_from_activity(activity)
+ {enabled_receivers, _disabled_receivers} = Notification.get_notified_from_activity(activity)
+
+ assert other_user in enabled_receivers
end
test "it sends notifications to mentioned users in new messages" do
@@ -420,7 +424,9 @@ defmodule Pleroma.NotificationTest do
{:ok, activity} = Transmogrifier.handle_incoming(create_activity)
- assert other_user in Notification.get_notified_from_activity(activity)
+ {enabled_receivers, _disabled_receivers} = Notification.get_notified_from_activity(activity)
+
+ assert other_user in enabled_receivers
end
test "it does not send notifications to users who are only cc in new messages" do
@@ -442,7 +448,9 @@ defmodule Pleroma.NotificationTest do
{:ok, activity} = Transmogrifier.handle_incoming(create_activity)
- assert other_user not in Notification.get_notified_from_activity(activity)
+ {enabled_receivers, _disabled_receivers} = Notification.get_notified_from_activity(activity)
+
+ assert other_user not in enabled_receivers
end
test "it does not send notification to mentioned users in likes" do
@@ -457,7 +465,10 @@ defmodule Pleroma.NotificationTest do
{:ok, activity_two, _} = CommonAPI.favorite(activity_one.id, third_user)
- assert other_user not in Notification.get_notified_from_activity(activity_two)
+ {enabled_receivers, _disabled_receivers} =
+ Notification.get_notified_from_activity(activity_two)
+
+ assert other_user not in enabled_receivers
end
test "it does not send notification to mentioned users in announces" do
@@ -472,7 +483,96 @@ defmodule Pleroma.NotificationTest do
{:ok, activity_two, _} = CommonAPI.repeat(activity_one.id, third_user)
- assert other_user not in Notification.get_notified_from_activity(activity_two)
+ {enabled_receivers, _disabled_receivers} =
+ Notification.get_notified_from_activity(activity_two)
+
+ assert other_user not in enabled_receivers
+ end
+
+ test_with_mock "it returns blocking recipient in disabled recipients list",
+ Push,
+ [:passthrough],
+ [] do
+ user = insert(:user)
+ other_user = insert(:user)
+ {:ok, _user_relationship} = User.block(other_user, user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"})
+
+ {enabled_receivers, disabled_receivers} = Notification.get_notified_from_activity(activity)
+
+ assert [] == enabled_receivers
+ assert [other_user] == disabled_receivers
+
+ assert 1 == length(Repo.all(Notification))
+ refute called(Push.send(:_))
+ end
+
+ test_with_mock "it returns notification-muting recipient in disabled recipients list",
+ Push,
+ [:passthrough],
+ [] do
+ user = insert(:user)
+ other_user = insert(:user)
+ {:ok, _user_relationships} = User.mute(other_user, user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"})
+
+ {enabled_receivers, disabled_receivers} = Notification.get_notified_from_activity(activity)
+
+ assert [] == enabled_receivers
+ assert [other_user] == disabled_receivers
+
+ assert 1 == length(Repo.all(Notification))
+ refute called(Push.send(:_))
+ end
+
+ test_with_mock "it returns thread-muting recipient in disabled recipients list",
+ Push,
+ [:passthrough],
+ [] do
+ user = insert(:user)
+ other_user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"})
+
+ {:ok, _} = CommonAPI.add_mute(other_user, activity)
+
+ {:ok, same_context_activity} =
+ CommonAPI.post(user, %{
+ "status" => "hey-hey-hey @#{other_user.nickname}!",
+ "in_reply_to_status_id" => activity.id
+ })
+
+ {enabled_receivers, disabled_receivers} =
+ Notification.get_notified_from_activity(same_context_activity)
+
+ assert [other_user] == disabled_receivers
+ refute other_user in enabled_receivers
+
+ [pre_mute_notification, post_mute_notification] =
+ Repo.all(from(n in Notification, where: n.user_id == ^other_user.id, order_by: n.id))
+
+ pre_mute_notification_id = pre_mute_notification.id
+ post_mute_notification_id = post_mute_notification.id
+
+ assert called(
+ Push.send(
+ :meck.is(fn
+ %Notification{id: ^pre_mute_notification_id} -> true
+ _ -> false
+ end)
+ )
+ )
+
+ refute called(
+ Push.send(
+ :meck.is(fn
+ %Notification{id: ^post_mute_notification_id} -> true
+ _ -> false
+ end)
+ )
+ )
end
end
--
cgit v1.2.3
From d198e7fa2a0c92be4e99c5a765de85096d318bfe Mon Sep 17 00:00:00 2001
From: eugenijm
Date: Tue, 28 Jan 2020 09:47:59 +0300
Subject: Admin API: `PATCH /api/pleroma/admin/users/:nickname/change_password`
---
test/web/admin_api/admin_api_controller_test.exs | 26 ++++++++++++++++++++++++
1 file changed, 26 insertions(+)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index e4c152fb7..0c1214f05 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -3389,6 +3389,32 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
end
+ describe "PATCH /users/:nickname/change_password" do
+ test "changes password", %{conn: conn, admin: admin} do
+ user = insert(:user)
+ assert user.password_reset_pending == false
+
+ conn =
+ patch(conn, "/api/pleroma/admin/users/#{user.nickname}/change_password", %{
+ "new_password" => "password"
+ })
+
+ assert json_response(conn, 200) == %{"status" => "success"}
+
+ ObanHelpers.perform_all()
+
+ assert User.get_by_id(user.id).password_reset_pending == true
+
+ [log_entry1, log_entry2] = ModerationLog |> Repo.all() |> Enum.sort()
+
+ assert ModerationLog.get_log_entry_message(log_entry1) ==
+ "@#{admin.nickname} changed password for users: @#{user.nickname}"
+
+ assert ModerationLog.get_log_entry_message(log_entry2) ==
+ "@#{admin.nickname} forced password reset for users: @#{user.nickname}"
+ end
+ end
+
describe "PATCH /users/:nickname/force_password_reset" do
test "sets password_reset_pending to true", %{conn: conn} do
user = insert(:user)
--
cgit v1.2.3
From 13cce9c0debbf9a80ed5da26cb34ca563e5e1417 Mon Sep 17 00:00:00 2001
From: eugenijm
Date: Fri, 31 Jan 2020 21:07:46 +0300
Subject: Admin API: `PATCH /api/pleroma/admin/users/:nickname/credentials`,
`GET /api/pleroma/admin/users/:nickname/credentials`.
---
test/web/admin_api/admin_api_controller_test.exs | 57 +++++++++++++++++++++---
1 file changed, 50 insertions(+), 7 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 0c1214f05..0a317cf88 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -3389,30 +3389,73 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
end
- describe "PATCH /users/:nickname/change_password" do
- test "changes password", %{conn: conn, admin: admin} do
+ describe "GET /users/:nickname/credentials" do
+ test "gets the user credentials", %{conn: conn} do
+ user = insert(:user)
+ conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/credentials")
+
+ response = assert json_response(conn, 200)
+ assert response["email"] == user.email
+ end
+
+ test "returns 403 if requested by a non-admin" do
+ user = insert(:user)
+
+ conn =
+ build_conn()
+ |> assign(:user, user)
+ |> get("/api/pleroma/admin/users/#{user.nickname}/credentials")
+
+ assert json_response(conn, :forbidden)
+ end
+ end
+
+ describe "PATCH /users/:nickname/credentials" do
+ test "changes password and email", %{conn: conn, admin: admin} do
user = insert(:user)
assert user.password_reset_pending == false
conn =
- patch(conn, "/api/pleroma/admin/users/#{user.nickname}/change_password", %{
- "new_password" => "password"
+ patch(conn, "/api/pleroma/admin/users/#{user.nickname}/credentials", %{
+ "password" => "new_password",
+ "email" => "new_email@example.com",
+ "name" => "new_name"
})
assert json_response(conn, 200) == %{"status" => "success"}
ObanHelpers.perform_all()
- assert User.get_by_id(user.id).password_reset_pending == true
+ updated_user = User.get_by_id(user.id)
- [log_entry1, log_entry2] = ModerationLog |> Repo.all() |> Enum.sort()
+ assert updated_user.email == "new_email@example.com"
+ assert updated_user.name == "new_name"
+ assert updated_user.password_hash != user.password_hash
+ assert updated_user.password_reset_pending == true
+
+ [log_entry2, log_entry1] = ModerationLog |> Repo.all() |> Enum.sort()
assert ModerationLog.get_log_entry_message(log_entry1) ==
- "@#{admin.nickname} changed password for users: @#{user.nickname}"
+ "@#{admin.nickname} updated users: @#{user.nickname}"
assert ModerationLog.get_log_entry_message(log_entry2) ==
"@#{admin.nickname} forced password reset for users: @#{user.nickname}"
end
+
+ test "returns 403 if requested by a non-admin" do
+ user = insert(:user)
+
+ conn =
+ build_conn()
+ |> assign(:user, user)
+ |> patch("/api/pleroma/admin/users/#{user.nickname}/credentials", %{
+ "password" => "new_password",
+ "email" => "new_email@example.com",
+ "name" => "new_name"
+ })
+
+ assert json_response(conn, :forbidden)
+ end
end
describe "PATCH /users/:nickname/force_password_reset" do
--
cgit v1.2.3
From 74388336852b18d5d5f108a8305f1a038301f7a1 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Mon, 16 Mar 2020 21:58:10 +0300
Subject: [#1364] Improved notification-related tests.
---
test/notification_test.exs | 121 +++++++++++++++++++++++++++++----------------
1 file changed, 78 insertions(+), 43 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index bc2d80f05..a7282c929 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -82,6 +82,80 @@ defmodule Pleroma.NotificationTest do
end
end
+ describe "CommonApi.post/2 notification-related functionality" do
+ test_with_mock "creates but does NOT send notification to blocker user",
+ Push,
+ [:passthrough],
+ [] do
+ user = insert(:user)
+ blocker = insert(:user)
+ {:ok, _user_relationship} = User.block(blocker, user)
+
+ {:ok, _activity} = CommonAPI.post(user, %{"status" => "hey @#{blocker.nickname}!"})
+
+ blocker_id = blocker.id
+ assert [%Notification{user_id: ^blocker_id}] = Repo.all(Notification)
+ refute called(Push.send(:_))
+ end
+
+ test_with_mock "creates but does NOT send notification to notification-muter user",
+ Push,
+ [:passthrough],
+ [] do
+ user = insert(:user)
+ muter = insert(:user)
+ {:ok, _user_relationships} = User.mute(muter, user)
+
+ {:ok, _activity} = CommonAPI.post(user, %{"status" => "hey @#{muter.nickname}!"})
+
+ muter_id = muter.id
+ assert [%Notification{user_id: ^muter_id}] = Repo.all(Notification)
+ refute called(Push.send(:_))
+ end
+
+ test_with_mock "creates but does NOT send notification to thread-muter user",
+ Push,
+ [:passthrough],
+ [] do
+ user = insert(:user)
+ thread_muter = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{thread_muter.nickname}!"})
+
+ {:ok, _} = CommonAPI.add_mute(thread_muter, activity)
+
+ {:ok, _same_context_activity} =
+ CommonAPI.post(user, %{
+ "status" => "hey-hey-hey @#{thread_muter.nickname}!",
+ "in_reply_to_status_id" => activity.id
+ })
+
+ [pre_mute_notification, post_mute_notification] =
+ Repo.all(from(n in Notification, where: n.user_id == ^thread_muter.id, order_by: n.id))
+
+ pre_mute_notification_id = pre_mute_notification.id
+ post_mute_notification_id = post_mute_notification.id
+
+ assert called(
+ Push.send(
+ :meck.is(fn
+ %Notification{id: ^pre_mute_notification_id} -> true
+ _ -> false
+ end)
+ )
+ )
+
+ refute called(
+ Push.send(
+ :meck.is(fn
+ %Notification{id: ^post_mute_notification_id} -> true
+ _ -> false
+ end)
+ )
+ )
+ end
+ end
+
describe "create_notification" do
@tag needs_streamer: true
test "it creates a notification for user and send to the 'user' and the 'user:notification' stream" do
@@ -489,10 +563,7 @@ defmodule Pleroma.NotificationTest do
assert other_user not in enabled_receivers
end
- test_with_mock "it returns blocking recipient in disabled recipients list",
- Push,
- [:passthrough],
- [] do
+ test "it returns blocking recipient in disabled recipients list" do
user = insert(:user)
other_user = insert(:user)
{:ok, _user_relationship} = User.block(other_user, user)
@@ -503,15 +574,9 @@ defmodule Pleroma.NotificationTest do
assert [] == enabled_receivers
assert [other_user] == disabled_receivers
-
- assert 1 == length(Repo.all(Notification))
- refute called(Push.send(:_))
end
- test_with_mock "it returns notification-muting recipient in disabled recipients list",
- Push,
- [:passthrough],
- [] do
+ test "it returns notification-muting recipient in disabled recipients list" do
user = insert(:user)
other_user = insert(:user)
{:ok, _user_relationships} = User.mute(other_user, user)
@@ -522,15 +587,9 @@ defmodule Pleroma.NotificationTest do
assert [] == enabled_receivers
assert [other_user] == disabled_receivers
-
- assert 1 == length(Repo.all(Notification))
- refute called(Push.send(:_))
end
- test_with_mock "it returns thread-muting recipient in disabled recipients list",
- Push,
- [:passthrough],
- [] do
+ test "it returns thread-muting recipient in disabled recipients list" do
user = insert(:user)
other_user = insert(:user)
@@ -549,30 +608,6 @@ defmodule Pleroma.NotificationTest do
assert [other_user] == disabled_receivers
refute other_user in enabled_receivers
-
- [pre_mute_notification, post_mute_notification] =
- Repo.all(from(n in Notification, where: n.user_id == ^other_user.id, order_by: n.id))
-
- pre_mute_notification_id = pre_mute_notification.id
- post_mute_notification_id = post_mute_notification.id
-
- assert called(
- Push.send(
- :meck.is(fn
- %Notification{id: ^pre_mute_notification_id} -> true
- _ -> false
- end)
- )
- )
-
- refute called(
- Push.send(
- :meck.is(fn
- %Notification{id: ^post_mute_notification_id} -> true
- _ -> false
- end)
- )
- )
end
end
@@ -820,7 +855,7 @@ defmodule Pleroma.NotificationTest do
assert Notification.for_user(user) == []
end
- test "it doesn't return notificatitons for blocked domain" do
+ test "it doesn't return notifications for blocked domain" do
user = insert(:user)
blocked = insert(:user, ap_id: "http://some-domain.com")
{:ok, user} = User.block_domain(user, "some-domain.com")
--
cgit v1.2.3
From d3cf7e19fbe089b3a6d62d6a26f3dfc866a6669d Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Tue, 17 Mar 2020 13:02:10 +0100
Subject: activity_pub_controller_test.exs: test posting with AP C2S uploaded
media
---
.../activity_pub/activity_pub_controller_test.exs | 34 ++++++++++++++++++++--
1 file changed, 32 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs
index bd8e0b5cc..2bd494a37 100644
--- a/test/web/activity_pub/activity_pub_controller_test.exs
+++ b/test/web/activity_pub/activity_pub_controller_test.exs
@@ -1241,16 +1241,46 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
filename: "an_image.jpg"
}
- conn =
+ object =
conn
|> assign(:user, user)
|> post("/api/ap/upload_media", %{"file" => image, "description" => desc})
+ |> json_response(:created)
- assert object = json_response(conn, :created)
assert object["name"] == desc
assert object["type"] == "Document"
assert object["actor"] == user.ap_id
+ assert [%{"href" => object_href}] = object["url"]
+
+ activity_request = %{
+ "@context" => "https://www.w3.org/ns/activitystreams",
+ "type" => "Create",
+ "object" => %{
+ "type" => "Note",
+ "content" => "AP C2S test, attachment",
+ "attachment" => [object]
+ },
+ "to" => "https://www.w3.org/ns/activitystreams#Public",
+ "cc" => []
+ }
+
+ activity_response =
+ conn
+ |> assign(:user, user)
+ |> post("/users/#{user.nickname}/outbox", activity_request)
+ |> json_response(:created)
+
+ assert activity_response["id"]
+ assert activity_response["object"]
+ assert activity_response["actor"] == user.ap_id
+
+ assert %Object{data: %{"attachment" => [attachment]}} = Object.normalize(activity_response["object"])
+ assert attachment["type"] == "Document"
+ assert attachment["name"] == desc
+ assert [%{"href" => attachment_href}] = attachment["url"]
+ assert attachment_href == object_href
+ # Fails if unauthenticated
conn
|> post("/api/ap/upload_media", %{"file" => image, "description" => desc})
|> json_response(403)
--
cgit v1.2.3
From f9d622d25a744f58fbaf8370ad4435597bb15bf0 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Thu, 19 Mar 2020 15:08:49 +0100
Subject: WIP
---
test/web/activity_pub/activity_pub_controller_test.exs | 18 ++++++++++++++----
1 file changed, 14 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs
index 2bd494a37..01c955c0a 100644
--- a/test/web/activity_pub/activity_pub_controller_test.exs
+++ b/test/web/activity_pub/activity_pub_controller_test.exs
@@ -1250,7 +1250,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
assert object["name"] == desc
assert object["type"] == "Document"
assert object["actor"] == user.ap_id
- assert [%{"href" => object_href}] = object["url"]
+ assert [%{"href" => object_href, "mediaType" => object_mediatype}] = object["url"]
+ assert is_binary(object_href)
+ assert object_mediatype == "image/jpeg"
activity_request = %{
"@context" => "https://www.w3.org/ns/activitystreams",
@@ -1274,11 +1276,19 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
assert activity_response["object"]
assert activity_response["actor"] == user.ap_id
- assert %Object{data: %{"attachment" => [attachment]}} = Object.normalize(activity_response["object"])
+ assert %Object{data: %{"attachment" => [attachment]}} =
+ Object.normalize(activity_response["object"])
+
assert attachment["type"] == "Document"
assert attachment["name"] == desc
- assert [%{"href" => attachment_href}] = attachment["url"]
- assert attachment_href == object_href
+
+ assert [
+ %{
+ "href" => ^object_href,
+ "type" => "Link",
+ "mediaType" => ^object_mediatype
+ }
+ ] = attachment["url"]
# Fails if unauthenticated
conn
--
cgit v1.2.3
From c1fd4f665335ba67336bd1b2fab2d9df5e247e08 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Thu, 19 Mar 2020 19:10:03 +0100
Subject: transmogrifier.ex: rework fix_attachment for better IR
---
test/web/activity_pub/transmogrifier_test.exs | 30 +++++----------------------
1 file changed, 5 insertions(+), 25 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index efbca82f6..242d933e7 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -1228,19 +1228,13 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
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"
+ "mediaType" => "video/mp4"
}
- ],
- "width" => 480
+ ]
}
assert object.data["url"] ==
@@ -2067,11 +2061,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
%{
"mediaType" => "video/mp4",
"url" => [
- %{
- "href" => "https://peertube.moe/stat-480.mp4",
- "mediaType" => "video/mp4",
- "type" => "Link"
- }
+ %{"href" => "https://peertube.moe/stat-480.mp4", "mediaType" => "video/mp4"}
]
}
]
@@ -2089,23 +2079,13 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
%{
"mediaType" => "video/mp4",
"url" => [
- %{
- "href" => "https://pe.er/stat-480.mp4",
- "mediaType" => "video/mp4",
- "type" => "Link"
- }
+ %{"href" => "https://pe.er/stat-480.mp4", "mediaType" => "video/mp4"}
]
},
%{
- "href" => "https://pe.er/stat-480.mp4",
"mediaType" => "video/mp4",
- "mimeType" => "video/mp4",
"url" => [
- %{
- "href" => "https://pe.er/stat-480.mp4",
- "mediaType" => "video/mp4",
- "type" => "Link"
- }
+ %{"href" => "https://pe.er/stat-480.mp4", "mediaType" => "video/mp4"}
]
}
]
--
cgit v1.2.3
From 6c1232b486dcad5a644b4292697d08ebe3000cb3 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 20 Mar 2020 15:00:28 +0100
Subject: NotificationController: Fix test.
---
test/web/mastodon_api/controllers/notification_controller_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs
index e407b8297..adbb78da6 100644
--- a/test/web/mastodon_api/controllers/notification_controller_test.exs
+++ b/test/web/mastodon_api/controllers/notification_controller_test.exs
@@ -310,7 +310,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
{:ok, mention_activity} = CommonAPI.post(other_user, %{"status" => "hey @#{user.nickname}"})
{:ok, create_activity} = CommonAPI.post(user, %{"status" => "hey"})
- {:ok, favorite_activity, _} = CommonAPI.favorite(create_activity.id, other_user)
+ {:ok, favorite_activity} = CommonAPI.favorite(other_user, create_activity.id)
{:ok, reblog_activity, _} = CommonAPI.repeat(create_activity.id, other_user)
{:ok, _, _, follow_activity} = CommonAPI.follow(other_user, user)
--
cgit v1.2.3
From 7f9b5284fa7dd1d9100de730a6fe0c93739d1b30 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Fri, 20 Mar 2020 20:58:47 +0300
Subject: updating clear_config
---
test/http/adapter_helper/gun_test.exs | 4 +---
test/http/adapter_helper/hackney_test.exs | 5 +----
test/http/connection_test.exs | 2 +-
3 files changed, 3 insertions(+), 8 deletions(-)
(limited to 'test')
diff --git a/test/http/adapter_helper/gun_test.exs b/test/http/adapter_helper/gun_test.exs
index 18025b986..2e961826e 100644
--- a/test/http/adapter_helper/gun_test.exs
+++ b/test/http/adapter_helper/gun_test.exs
@@ -28,9 +28,7 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do
end
describe "options/1" do
- clear_config([:http, :adapter]) do
- Config.put([:http, :adapter], a: 1, b: 2)
- end
+ setup do: clear_config([:http, :adapter], a: 1, b: 2)
test "https url with default port" do
uri = URI.parse("https://example.com")
diff --git a/test/http/adapter_helper/hackney_test.exs b/test/http/adapter_helper/hackney_test.exs
index 5fda075f6..3f7e708e0 100644
--- a/test/http/adapter_helper/hackney_test.exs
+++ b/test/http/adapter_helper/hackney_test.exs
@@ -6,7 +6,6 @@ defmodule Pleroma.HTTP.AdapterHelper.HackneyTest do
use ExUnit.Case, async: true
use Pleroma.Tests.Helpers
- alias Pleroma.Config
alias Pleroma.HTTP.AdapterHelper.Hackney
setup_all do
@@ -15,9 +14,7 @@ defmodule Pleroma.HTTP.AdapterHelper.HackneyTest do
end
describe "options/2" do
- clear_config([:http, :adapter]) do
- Config.put([:http, :adapter], a: 1, b: 2)
- end
+ setup do: clear_config([:http, :adapter], a: 1, b: 2)
test "add proxy and opts from config", %{uri: uri} do
opts = Hackney.options([proxy: "localhost:8123"], uri)
diff --git a/test/http/connection_test.exs b/test/http/connection_test.exs
index 0f62eddd2..5cc78ad5b 100644
--- a/test/http/connection_test.exs
+++ b/test/http/connection_test.exs
@@ -82,7 +82,7 @@ defmodule Pleroma.HTTP.ConnectionTest do
end
describe "options/3" do
- clear_config([:http, :proxy_url])
+ setup do: clear_config([:http, :proxy_url])
test "without proxy_url in config" do
Config.delete([:http, :proxy_url])
--
cgit v1.2.3
From 15be6ba9c200b2a4ae153d26876be1b5cbb6357e Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Sun, 22 Mar 2020 16:38:12 +0100
Subject: AccountView: fix for other forms of
in bio
Closes: https://git.pleroma.social/pleroma/pleroma/issues/1643
---
.../controllers/account_controller/update_credentials_test.exs | 4 ++--
test/web/mastodon_api/views/account_view_test.exs | 7 ++++---
2 files changed, 6 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
index 43538cb17..51cebe567 100644
--- a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
@@ -76,7 +76,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
conn =
patch(conn, "/api/v1/accounts/update_credentials", %{
- "note" => "I drink #cofe with @#{user2.nickname}"
+ "note" => "I drink #cofe with @#{user2.nickname}\n\nsuya.."
})
assert user_data = json_response(conn, 200)
@@ -84,7 +84,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
assert user_data["note"] ==
~s(I drink #cofe with @#{user2.nickname})
+ }" class="u-url mention" href="#{user2.ap_id}" rel="ugc">@#{user2.nickname}
suya..)
end
test "updates the user's locking status", %{conn: conn} do
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index d60ed7b64..983886c6b 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -32,7 +32,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
background: background_image,
nickname: "shp@shitposter.club",
name: ":karjalanpiirakka: shp",
- bio: "valid html",
+ bio:
+ "valid html. a
b
c
d
f",
inserted_at: ~N[2017-08-15 15:47:06.597036]
})
@@ -46,7 +47,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
followers_count: 3,
following_count: 0,
statuses_count: 5,
- note: "valid html",
+ note: "valid html. a
b
c
d
f",
url: user.ap_id,
avatar: "http://localhost:4001/images/avi.png",
avatar_static: "http://localhost:4001/images/avi.png",
@@ -63,7 +64,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
fields: [],
bot: false,
source: %{
- note: "valid html",
+ note: "valid html. a\nb\nc\nd\nf",
sensitive: false,
pleroma: %{
actor_type: "Person",
--
cgit v1.2.3
From a6ee6784bc74b311d454112c427f41b1fdec6ce0 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Fri, 28 Feb 2020 11:16:40 +0300
Subject: creating trusted app from adminFE & mix task
---
test/support/factory.ex | 2 +-
test/tasks/app_test.exs | 65 ++++++++
test/web/admin_api/admin_api_controller_test.exs | 185 +++++++++++++++++++++
.../controllers/account_controller_test.exs | 67 ++++++++
4 files changed, 318 insertions(+), 1 deletion(-)
create mode 100644 test/tasks/app_test.exs
(limited to 'test')
diff --git a/test/support/factory.ex b/test/support/factory.ex
index af639b6cd..f0b797fd4 100644
--- a/test/support/factory.ex
+++ b/test/support/factory.ex
@@ -294,7 +294,7 @@ defmodule Pleroma.Factory do
def oauth_app_factory do
%Pleroma.Web.OAuth.App{
- client_name: "Some client",
+ client_name: sequence(:client_name, &"Some client #{&1}"),
redirect_uris: "https://example.com/callback",
scopes: ["read", "write", "follow", "push", "admin"],
website: "https://example.com",
diff --git a/test/tasks/app_test.exs b/test/tasks/app_test.exs
new file mode 100644
index 000000000..b8f03566d
--- /dev/null
+++ b/test/tasks/app_test.exs
@@ -0,0 +1,65 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Mix.Tasks.Pleroma.AppTest do
+ use Pleroma.DataCase, async: true
+
+ setup_all do
+ Mix.shell(Mix.Shell.Process)
+
+ on_exit(fn ->
+ Mix.shell(Mix.Shell.IO)
+ end)
+ end
+
+ describe "creates new app" do
+ test "with default scopes" do
+ name = "Some name"
+ redirect = "https://example.com"
+ Mix.Tasks.Pleroma.App.run(["create", "-n", name, "-r", redirect])
+
+ assert_app(name, redirect, ["read", "write", "follow", "push"])
+ end
+
+ test "with custom scopes" do
+ name = "Another name"
+ redirect = "https://example.com"
+
+ Mix.Tasks.Pleroma.App.run([
+ "create",
+ "-n",
+ name,
+ "-r",
+ redirect,
+ "-s",
+ "read,write,follow,push,admin"
+ ])
+
+ assert_app(name, redirect, ["read", "write", "follow", "push", "admin"])
+ end
+ end
+
+ test "with errors" do
+ Mix.Tasks.Pleroma.App.run(["create"])
+ {:mix_shell, :error, ["Creating failed:"]}
+ {:mix_shell, :error, ["name: can't be blank"]}
+ {:mix_shell, :error, ["redirect_uris: can't be blank"]}
+ end
+
+ defp assert_app(name, redirect, scopes) do
+ app = Repo.get_by(Pleroma.Web.OAuth.App, client_name: name)
+
+ assert_received {:mix_shell, :info, [message]}
+ assert message == "#{name} successfully created:"
+
+ assert_received {:mix_shell, :info, [message]}
+ assert message == "App client_id: #{app.client_id}"
+
+ assert_received {:mix_shell, :info, [message]}
+ assert message == "App client_secret: #{app.client_secret}"
+
+ assert app.scopes == scopes
+ assert app.redirect_uris == redirect
+ end
+end
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 0a902585d..d77e8d1d2 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -3623,6 +3623,191 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
response["status_visibility"]
end
end
+
+ describe "POST /api/pleroma/admin/oauth_app" do
+ test "errors", %{conn: conn} do
+ response = conn |> post("/api/pleroma/admin/oauth_app", %{}) |> json_response(200)
+
+ assert response == %{"name" => "can't be blank", "redirect_uris" => "can't be blank"}
+ end
+
+ test "success", %{conn: conn} do
+ base_url = Pleroma.Web.base_url()
+ app_name = "Trusted app"
+
+ response =
+ conn
+ |> post("/api/pleroma/admin/oauth_app", %{
+ name: app_name,
+ redirect_uris: base_url
+ })
+ |> json_response(200)
+
+ assert %{
+ "client_id" => _,
+ "client_secret" => _,
+ "name" => ^app_name,
+ "redirect_uri" => ^base_url,
+ "trusted" => false
+ } = response
+ end
+
+ test "with trusted", %{conn: conn} do
+ base_url = Pleroma.Web.base_url()
+ app_name = "Trusted app"
+
+ response =
+ conn
+ |> post("/api/pleroma/admin/oauth_app", %{
+ name: app_name,
+ redirect_uris: base_url,
+ trusted: true
+ })
+ |> json_response(200)
+
+ assert %{
+ "client_id" => _,
+ "client_secret" => _,
+ "name" => ^app_name,
+ "redirect_uri" => ^base_url,
+ "trusted" => true
+ } = response
+ end
+ end
+
+ describe "GET /api/pleroma/admin/oauth_app" do
+ setup do
+ app = insert(:oauth_app)
+ {:ok, app: app}
+ end
+
+ test "list", %{conn: conn} do
+ response =
+ conn
+ |> get("/api/pleroma/admin/oauth_app")
+ |> json_response(200)
+
+ assert %{"apps" => apps, "count" => count, "page_size" => _} = response
+
+ assert length(apps) == count
+ end
+
+ test "with page size", %{conn: conn} do
+ insert(:oauth_app)
+ page_size = 1
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/oauth_app", %{page_size: to_string(page_size)})
+ |> json_response(200)
+
+ assert %{"apps" => apps, "count" => _, "page_size" => ^page_size} = response
+
+ assert length(apps) == page_size
+ end
+
+ test "search by client name", %{conn: conn, app: app} do
+ response =
+ conn
+ |> get("/api/pleroma/admin/oauth_app", %{name: app.client_name})
+ |> json_response(200)
+
+ assert %{"apps" => [returned], "count" => _, "page_size" => _} = response
+
+ assert returned["client_id"] == app.client_id
+ assert returned["name"] == app.client_name
+ end
+
+ test "search by client id", %{conn: conn, app: app} do
+ response =
+ conn
+ |> get("/api/pleroma/admin/oauth_app", %{client_id: app.client_id})
+ |> json_response(200)
+
+ assert %{"apps" => [returned], "count" => _, "page_size" => _} = response
+
+ assert returned["client_id"] == app.client_id
+ assert returned["name"] == app.client_name
+ end
+
+ test "only trusted", %{conn: conn} do
+ app = insert(:oauth_app, trusted: true)
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/oauth_app", %{trusted: true})
+ |> json_response(200)
+
+ assert %{"apps" => [returned], "count" => _, "page_size" => _} = response
+
+ assert returned["client_id"] == app.client_id
+ assert returned["name"] == app.client_name
+ end
+ end
+
+ describe "DELETE /api/pleroma/admin/oauth_app/:id" do
+ test "with id", %{conn: conn} do
+ app = insert(:oauth_app)
+
+ response =
+ conn
+ |> delete("/api/pleroma/admin/oauth_app/" <> to_string(app.id))
+ |> json_response(:no_content)
+
+ assert response == ""
+ end
+
+ test "with non existance id", %{conn: conn} do
+ response =
+ conn
+ |> delete("/api/pleroma/admin/oauth_app/0")
+ |> json_response(:bad_request)
+
+ assert response == ""
+ end
+ end
+
+ describe "PATCH /api/pleroma/admin/oauth_app/:id" do
+ test "with id", %{conn: conn} do
+ app = insert(:oauth_app)
+
+ name = "another name"
+ url = "https://example.com"
+ scopes = ["admin"]
+ id = app.id
+ website = "http://website.com"
+
+ response =
+ conn
+ |> patch("/api/pleroma/admin/oauth_app/" <> to_string(app.id), %{
+ name: name,
+ trusted: true,
+ redirect_uris: url,
+ scopes: scopes,
+ website: website
+ })
+ |> json_response(200)
+
+ assert %{
+ "client_id" => _,
+ "client_secret" => _,
+ "id" => ^id,
+ "name" => ^name,
+ "redirect_uri" => ^url,
+ "trusted" => true,
+ "website" => ^website
+ } = response
+ end
+
+ test "without id", %{conn: conn} do
+ response =
+ conn
+ |> patch("/api/pleroma/admin/oauth_app/0")
+ |> json_response(:bad_request)
+
+ assert response == ""
+ end
+ end
end
# Needed for testing
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index a9fa0ce48..f770232df 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -942,6 +942,73 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
res = post(conn, "/api/v1/accounts", valid_params)
assert json_response(res, 403) == %{"error" => "Invalid credentials"}
end
+
+ test "registration from trusted app" do
+ clear_config([Pleroma.Captcha, :enabled], true)
+ app = insert(:oauth_app, trusted: true, scopes: ["read", "write", "follow", "push"])
+
+ conn =
+ build_conn()
+ |> post("/oauth/token", %{
+ "grant_type" => "client_credentials",
+ "client_id" => app.client_id,
+ "client_secret" => app.client_secret
+ })
+
+ assert %{"access_token" => token, "token_type" => "Bearer"} = json_response(conn, 200)
+
+ response =
+ build_conn()
+ |> Plug.Conn.put_req_header("authorization", "Bearer " <> token)
+ |> post("/api/v1/accounts", %{
+ nickname: "nickanme",
+ agreement: true,
+ email: "email@example.com",
+ fullname: "Lain",
+ username: "Lain",
+ password: "some_password",
+ confirm: "some_password"
+ })
+ |> json_response(200)
+
+ assert %{
+ "access_token" => access_token,
+ "created_at" => _,
+ "scope" => ["read", "write", "follow", "push"],
+ "token_type" => "Bearer"
+ } = response
+
+ response =
+ build_conn()
+ |> Plug.Conn.put_req_header("authorization", "Bearer " <> access_token)
+ |> get("/api/v1/accounts/verify_credentials")
+ |> json_response(200)
+
+ assert %{
+ "acct" => "Lain",
+ "bot" => false,
+ "display_name" => "Lain",
+ "follow_requests_count" => 0,
+ "followers_count" => 0,
+ "following_count" => 0,
+ "locked" => false,
+ "note" => "",
+ "source" => %{
+ "fields" => [],
+ "note" => "",
+ "pleroma" => %{
+ "actor_type" => "Person",
+ "discoverable" => false,
+ "no_rich_text" => false,
+ "show_role" => true
+ },
+ "privacy" => "public",
+ "sensitive" => false
+ },
+ "statuses_count" => 0,
+ "username" => "Lain"
+ } = response
+ end
end
describe "create account by app / rate limit" do
--
cgit v1.2.3
From eec1fcaf55bdcbc2d3aed4eaf044bb8ef6c4effa Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 23 Mar 2020 15:58:55 +0100
Subject: Home timeline tests: Add failing test for relationships
---
.../controllers/timeline_controller_test.exs | 57 ++++++++++++++++++++--
1 file changed, 53 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/timeline_controller_test.exs b/test/web/mastodon_api/controllers/timeline_controller_test.exs
index 6fedb4223..47849fc48 100644
--- a/test/web/mastodon_api/controllers/timeline_controller_test.exs
+++ b/test/web/mastodon_api/controllers/timeline_controller_test.exs
@@ -21,9 +21,12 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
setup do: oauth_access(["read:statuses"])
test "the home timeline", %{user: user, conn: conn} do
- following = insert(:user)
+ following = insert(:user, nickname: "followed")
+ third_user = insert(:user, nickname: "repeated")
- {:ok, _activity} = CommonAPI.post(following, %{"status" => "test"})
+ {:ok, _activity} = CommonAPI.post(following, %{"status" => "post"})
+ {:ok, activity} = CommonAPI.post(third_user, %{"status" => "repeated post"})
+ {:ok, _, _} = CommonAPI.repeat(activity.id, following)
ret_conn = get(conn, "/api/v1/timelines/home")
@@ -31,9 +34,55 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
{:ok, _user} = User.follow(user, following)
- conn = get(conn, "/api/v1/timelines/home")
+ ret_conn = get(conn, "/api/v1/timelines/home")
- assert [%{"content" => "test"}] = json_response(conn, :ok)
+ assert [
+ %{
+ "reblog" => %{
+ "content" => "repeated post",
+ "account" => %{
+ "pleroma" => %{
+ "relationship" => %{"following" => false, "followed_by" => false}
+ }
+ }
+ },
+ "account" => %{"pleroma" => %{"relationship" => %{"following" => true}}}
+ },
+ %{
+ "content" => "post",
+ "account" => %{
+ "acct" => "followed",
+ "pleroma" => %{"relationship" => %{"following" => true}}
+ }
+ }
+ ] = json_response(ret_conn, :ok)
+
+ {:ok, _user} = User.follow(third_user, user)
+
+ ret_conn = get(conn, "/api/v1/timelines/home")
+
+ assert [
+ %{
+ "reblog" => %{
+ "content" => "repeated post",
+ "account" => %{
+ "acct" => "repeated",
+ "pleroma" => %{
+ # This part does not match correctly
+ "relationship" => %{"following" => false, "followed_by" => true}
+ }
+ }
+ },
+ "account" => %{"pleroma" => %{"relationship" => %{"following" => true}}}
+ },
+ %{
+ "content" => "post",
+ "account" => %{
+ "acct" => "followed",
+ "pleroma" => %{"relationship" => %{"following" => true}}
+ }
+ }
+ ] = json_response(ret_conn, :ok)
end
test "the home timeline when the direct messages are excluded", %{user: user, conn: conn} do
--
cgit v1.2.3
From d1a9716a988fe9f670033ad46cc9637038fbd1e8 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 24 Mar 2020 17:38:18 +0400
Subject: Fix activity deletion
---
test/web/activity_pub/activity_pub_test.exs | 6 ++++++
1 file changed, 6 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index a43dd34f0..049b14498 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -1425,6 +1425,12 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
assert Repo.get(Object, object.id).data["type"] == "Tombstone"
end
+ test "it doesn't fail when an activity was already deleted" do
+ {:ok, delete} = insert(:note_activity) |> Object.normalize() |> ActivityPub.delete()
+
+ assert {:ok, ^delete} = delete |> Object.normalize() |> ActivityPub.delete()
+ end
+
test "decrements user note count only for public activities" do
user = insert(:user, note_count: 10)
--
cgit v1.2.3
From 4a2538967caf5b0f9970cc5f973c16ea5d776aa3 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 24 Mar 2020 20:18:27 +0400
Subject: Support pagination in conversations
---
.../controllers/pleroma_api_controller_test.exs | 17 +++++++++++++++++
1 file changed, 17 insertions(+)
(limited to 'test')
diff --git a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
index 32250f06f..8bf7eb3be 100644
--- a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
@@ -169,6 +169,23 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
id_one = activity.id
id_two = activity_two.id
assert [%{"id" => ^id_one}, %{"id" => ^id_two}] = result
+
+ {:ok, %{id: id_three}} =
+ CommonAPI.post(other_user, %{
+ "status" => "Bye!",
+ "in_reply_to_status_id" => activity.id,
+ "in_reply_to_conversation_id" => participation.id
+ })
+
+ assert [%{"id" => ^id_two}, %{"id" => ^id_three}] =
+ conn
+ |> get("/api/v1/pleroma/conversations/#{participation.id}/statuses?limit=2")
+ |> json_response(:ok)
+
+ assert [%{"id" => ^id_three}] =
+ conn
+ |> get("/api/v1/pleroma/conversations/#{participation.id}/statuses?min_id=#{id_two}")
+ |> json_response(:ok)
end
test "PATCH /api/v1/pleroma/conversations/:id" do
--
cgit v1.2.3
From 13cbb9f6ada8dcb15bb7ed12be4d88a18c5db7f7 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Tue, 24 Mar 2020 22:14:26 +0300
Subject: Implemented preloading of relationships with parent activities'
actors for statuses/timeline rendering. Applied preloading for notifications
rendering. Fixed announces rendering issue (preloading-related).
---
test/web/mastodon_api/controllers/timeline_controller_test.exs | 1 -
1 file changed, 1 deletion(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/timeline_controller_test.exs b/test/web/mastodon_api/controllers/timeline_controller_test.exs
index 47849fc48..97b1c3e66 100644
--- a/test/web/mastodon_api/controllers/timeline_controller_test.exs
+++ b/test/web/mastodon_api/controllers/timeline_controller_test.exs
@@ -68,7 +68,6 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
"account" => %{
"acct" => "repeated",
"pleroma" => %{
- # This part does not match correctly
"relationship" => %{"following" => false, "followed_by" => true}
}
}
--
cgit v1.2.3
From 64165d1df95bc3a22260dafa4584471427685864 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Tue, 24 Mar 2020 20:21:27 +0100
Subject: node_info_test.exs: Add test on the default feature list
---
test/web/node_info_test.exs | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
(limited to 'test')
diff --git a/test/web/node_info_test.exs b/test/web/node_info_test.exs
index ee10ad5db..e8922a8ee 100644
--- a/test/web/node_info_test.exs
+++ b/test/web/node_info_test.exs
@@ -128,6 +128,27 @@ defmodule Pleroma.Web.NodeInfoTest do
end
end
+ test "it shows default features flags", %{conn: conn} do
+ response =
+ conn
+ |> get("/nodeinfo/2.1.json")
+ |> json_response(:ok)
+
+ assert response["metadata"]["features"] --
+ [
+ "pleroma_api",
+ "mastodon_api",
+ "mastodon_api_streaming",
+ "polls",
+ "pleroma_explicit_addressing",
+ "shareable_emoji_packs",
+ "multifetch",
+ "chat",
+ "relay",
+ "pleroma_emoji_reactions"
+ ] == []
+ end
+
test "it shows MRF transparency data if enabled", %{conn: conn} do
config = Pleroma.Config.get([:instance, :rewrite_policy])
Pleroma.Config.put([:instance, :rewrite_policy], [Pleroma.Web.ActivityPub.MRF.SimplePolicy])
--
cgit v1.2.3
From 03a18cf037d7a9b4ba84ff456b434d65e3290965 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Tue, 24 Mar 2020 20:39:19 +0100
Subject: node_info_test: Bump default features list
---
test/web/node_info_test.exs | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/node_info_test.exs b/test/web/node_info_test.exs
index 01a67afd7..e5eebced1 100644
--- a/test/web/node_info_test.exs
+++ b/test/web/node_info_test.exs
@@ -145,7 +145,8 @@ defmodule Pleroma.Web.NodeInfoTest do
"multifetch",
"chat",
"relay",
- "pleroma_emoji_reactions"
+ "pleroma_emoji_reactions",
+ "pleroma:api/v1/notifications:include_types_filter"
] == []
end
--
cgit v1.2.3
From e743c2232970e321c833604b232520587ad8e402 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Wed, 25 Mar 2020 09:04:00 +0300
Subject: Fixed incorrect usage of "relations" as a short form of
"relationships".
---
test/user_test.exs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/user_test.exs b/test/user_test.exs
index b07fed42b..f3d044a80 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -86,7 +86,7 @@ defmodule Pleroma.UserTest do
{:ok, user: insert(:user)}
end
- test "outgoing_relations_ap_ids/1", %{user: user} do
+ test "outgoing_relationships_ap_ids/1", %{user: user} do
rel_types = [:block, :mute, :notification_mute, :reblog_mute, :inverse_subscription]
ap_ids_by_rel =
@@ -124,10 +124,10 @@ defmodule Pleroma.UserTest do
assert ap_ids_by_rel[:inverse_subscription] ==
Enum.sort(Enum.map(User.subscriber_users(user), & &1.ap_id))
- outgoing_relations_ap_ids = User.outgoing_relations_ap_ids(user, rel_types)
+ outgoing_relationships_ap_ids = User.outgoing_relationships_ap_ids(user, rel_types)
assert ap_ids_by_rel ==
- Enum.into(outgoing_relations_ap_ids, %{}, fn {k, v} -> {k, Enum.sort(v)} end)
+ Enum.into(outgoing_relationships_ap_ids, %{}, fn {k, v} -> {k, Enum.sort(v)} end)
end
end
--
cgit v1.2.3
From 9081a071eecd0eeb4b67008754555e9c9d73eae7 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 25 Mar 2020 18:46:17 +0400
Subject: Add a test for accounts/update_credentials
---
.../account_controller/update_credentials_test.exs | 12 ++++++++++++
1 file changed, 12 insertions(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
index 51cebe567..b693c1a47 100644
--- a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
@@ -118,6 +118,18 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
assert user_data["pleroma"]["hide_followers"] == true
end
+ test "updates the user's discoverable status", %{conn: conn} do
+ assert %{"source" => %{"pleroma" => %{"discoverable" => true}}} =
+ conn
+ |> patch("/api/v1/accounts/update_credentials", %{discoverable: "true"})
+ |> json_response(:ok)
+
+ assert %{"source" => %{"pleroma" => %{"discoverable" => false}}} =
+ conn
+ |> patch("/api/v1/accounts/update_credentials", %{discoverable: "false"})
+ |> json_response(:ok)
+ end
+
test "updates the user's hide_followers_count and hide_follows_count", %{conn: conn} do
conn =
patch(conn, "/api/v1/accounts/update_credentials", %{
--
cgit v1.2.3
From 460e41585c2cd3f137c0f80173da60167fb318bf Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Wed, 25 Mar 2020 20:33:34 +0300
Subject: Further preloading (more endpoints), refactoring, tests.
---
test/web/mastodon_api/views/account_view_test.exs | 111 +++++++++++----------
.../mastodon_api/views/notification_view_test.exs | 42 ++++----
test/web/mastodon_api/views/status_view_test.exs | 15 ++-
3 files changed, 95 insertions(+), 73 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index 983886c6b..ede62903f 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -4,8 +4,11 @@
defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
use Pleroma.DataCase
+
import Pleroma.Factory
+
alias Pleroma.User
+ alias Pleroma.UserRelationship
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.MastodonAPI.AccountView
@@ -182,6 +185,29 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
end
describe "relationship" do
+ defp test_relationship_rendering(user, other_user, expected_result) do
+ opts = %{user: user, target: other_user}
+ assert expected_result == AccountView.render("relationship.json", opts)
+
+ relationships_opt = UserRelationship.view_relationships_option(user, [other_user])
+ opts = Map.put(opts, :relationships, relationships_opt)
+ assert expected_result == AccountView.render("relationship.json", opts)
+ end
+
+ @blank_response %{
+ following: false,
+ followed_by: false,
+ blocking: false,
+ blocked_by: false,
+ muting: false,
+ muting_notifications: false,
+ subscribing: false,
+ requested: false,
+ domain_blocking: false,
+ showing_reblogs: true,
+ endorsed: false
+ }
+
test "represent a relationship for the following and followed user" do
user = insert(:user)
other_user = insert(:user)
@@ -192,23 +218,21 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
{:ok, _user_relationships} = User.mute(user, other_user, true)
{:ok, _reblog_mute} = CommonAPI.hide_reblogs(user, other_user)
- expected = %{
- id: to_string(other_user.id),
- following: true,
- followed_by: true,
- blocking: false,
- blocked_by: false,
- muting: true,
- muting_notifications: true,
- subscribing: true,
- requested: false,
- domain_blocking: false,
- showing_reblogs: false,
- endorsed: false
- }
-
- assert expected ==
- AccountView.render("relationship.json", %{user: user, target: other_user})
+ expected =
+ Map.merge(
+ @blank_response,
+ %{
+ following: true,
+ followed_by: true,
+ muting: true,
+ muting_notifications: true,
+ subscribing: true,
+ showing_reblogs: false,
+ id: to_string(other_user.id)
+ }
+ )
+
+ test_relationship_rendering(user, other_user, expected)
end
test "represent a relationship for the blocking and blocked user" do
@@ -220,23 +244,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
{:ok, _user_relationship} = User.block(user, other_user)
{:ok, _user_relationship} = User.block(other_user, user)
- expected = %{
- id: to_string(other_user.id),
- following: false,
- followed_by: false,
- blocking: true,
- blocked_by: true,
- muting: false,
- muting_notifications: false,
- subscribing: false,
- requested: false,
- domain_blocking: false,
- showing_reblogs: true,
- endorsed: false
- }
+ expected =
+ Map.merge(
+ @blank_response,
+ %{following: false, blocking: true, blocked_by: true, id: to_string(other_user.id)}
+ )
- assert expected ==
- AccountView.render("relationship.json", %{user: user, target: other_user})
+ test_relationship_rendering(user, other_user, expected)
end
test "represent a relationship for the user blocking a domain" do
@@ -245,8 +259,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
{:ok, user} = User.block_domain(user, "bad.site")
- assert %{domain_blocking: true, blocking: false} =
- AccountView.render("relationship.json", %{user: user, target: other_user})
+ expected =
+ Map.merge(
+ @blank_response,
+ %{domain_blocking: true, blocking: false, id: to_string(other_user.id)}
+ )
+
+ test_relationship_rendering(user, other_user, expected)
end
test "represent a relationship for the user with a pending follow request" do
@@ -257,23 +276,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
user = User.get_cached_by_id(user.id)
other_user = User.get_cached_by_id(other_user.id)
- expected = %{
- id: to_string(other_user.id),
- following: false,
- followed_by: false,
- blocking: false,
- blocked_by: false,
- muting: false,
- muting_notifications: false,
- subscribing: false,
- requested: true,
- domain_blocking: false,
- showing_reblogs: true,
- endorsed: false
- }
+ expected =
+ Map.merge(
+ @blank_response,
+ %{requested: true, following: false, id: to_string(other_user.id)}
+ )
- assert expected ==
- AccountView.render("relationship.json", %{user: user, target: other_user})
+ test_relationship_rendering(user, other_user, expected)
end
end
diff --git a/test/web/mastodon_api/views/notification_view_test.exs b/test/web/mastodon_api/views/notification_view_test.exs
index d04c3022f..7965af00a 100644
--- a/test/web/mastodon_api/views/notification_view_test.exs
+++ b/test/web/mastodon_api/views/notification_view_test.exs
@@ -16,6 +16,21 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
alias Pleroma.Web.MastodonAPI.StatusView
import Pleroma.Factory
+ defp test_notifications_rendering(notifications, user, expected_result) do
+ result = NotificationView.render("index.json", %{notifications: notifications, for: user})
+
+ assert expected_result == result
+
+ result =
+ NotificationView.render("index.json", %{
+ notifications: notifications,
+ for: user,
+ relationships: nil
+ })
+
+ assert expected_result == result
+ end
+
test "Mention notification" do
user = insert(:user)
mentioned_user = insert(:user)
@@ -32,10 +47,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
created_at: Utils.to_masto_date(notification.inserted_at)
}
- result =
- NotificationView.render("index.json", %{notifications: [notification], for: mentioned_user})
-
- assert [expected] == result
+ test_notifications_rendering([notification], mentioned_user, [expected])
end
test "Favourite notification" do
@@ -55,9 +67,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
created_at: Utils.to_masto_date(notification.inserted_at)
}
- result = NotificationView.render("index.json", %{notifications: [notification], for: user})
-
- assert [expected] == result
+ test_notifications_rendering([notification], user, [expected])
end
test "Reblog notification" do
@@ -77,9 +87,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
created_at: Utils.to_masto_date(notification.inserted_at)
}
- result = NotificationView.render("index.json", %{notifications: [notification], for: user})
-
- assert [expected] == result
+ test_notifications_rendering([notification], user, [expected])
end
test "Follow notification" do
@@ -96,16 +104,12 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
created_at: Utils.to_masto_date(notification.inserted_at)
}
- result =
- NotificationView.render("index.json", %{notifications: [notification], for: followed})
-
- assert [expected] == result
+ test_notifications_rendering([notification], followed, [expected])
User.perform(:delete, follower)
notification = Notification |> Repo.one() |> Repo.preload(:activity)
- assert [] ==
- NotificationView.render("index.json", %{notifications: [notification], for: followed})
+ test_notifications_rendering([notification], followed, [])
end
test "Move notification" do
@@ -131,8 +135,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
created_at: Utils.to_masto_date(notification.inserted_at)
}
- assert [expected] ==
- NotificationView.render("index.json", %{notifications: [notification], for: follower})
+ test_notifications_rendering([notification], follower, [expected])
end
test "EmojiReact notification" do
@@ -158,7 +161,6 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
created_at: Utils.to_masto_date(notification.inserted_at)
}
- assert expected ==
- NotificationView.render("show.json", %{notification: notification, for: user})
+ test_notifications_rendering([notification], user, [expected])
end
end
diff --git a/test/web/mastodon_api/views/status_view_test.exs b/test/web/mastodon_api/views/status_view_test.exs
index 191895c6f..9191730cd 100644
--- a/test/web/mastodon_api/views/status_view_test.exs
+++ b/test/web/mastodon_api/views/status_view_test.exs
@@ -12,10 +12,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
alias Pleroma.Object
alias Pleroma.Repo
alias Pleroma.User
+ alias Pleroma.UserRelationship
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.CommonAPI.Utils
alias Pleroma.Web.MastodonAPI.AccountView
alias Pleroma.Web.MastodonAPI.StatusView
+
import Pleroma.Factory
import Tesla.Mock
@@ -212,12 +214,21 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
{:ok, _user_relationships} = User.mute(user, other_user)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "test"})
- status = StatusView.render("show.json", %{activity: activity})
+ relationships_opt = UserRelationship.view_relationships_option(user, [other_user])
+
+ opts = %{activity: activity}
+ status = StatusView.render("show.json", opts)
assert status.muted == false
- status = StatusView.render("show.json", %{activity: activity, for: user})
+ status = StatusView.render("show.json", Map.put(opts, :relationships, relationships_opt))
+ assert status.muted == false
+
+ for_opts = %{activity: activity, for: user}
+ status = StatusView.render("show.json", for_opts)
+ assert status.muted == true
+ status = StatusView.render("show.json", Map.put(for_opts, :relationships, relationships_opt))
assert status.muted == true
end
--
cgit v1.2.3
From 0adaab8e753b0ec22feccfc03d301073327a6d31 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 26 Mar 2020 15:37:42 +0100
Subject: Bump copyright dates.
---
test/web/activity_pub/object_validators/note_validator_test.exs | 2 +-
test/web/activity_pub/pipeline_test.exs | 2 +-
test/web/activity_pub/side_effects_test.exs | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validators/note_validator_test.exs b/test/web/activity_pub/object_validators/note_validator_test.exs
index 2bcd75e25..30c481ffb 100644
--- a/test/web/activity_pub/object_validators/note_validator_test.exs
+++ b/test/web/activity_pub/object_validators/note_validator_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.ObjectValidators.NoteValidatorTest do
diff --git a/test/web/activity_pub/pipeline_test.exs b/test/web/activity_pub/pipeline_test.exs
index 318d306af..f3c437498 100644
--- a/test/web/activity_pub/pipeline_test.exs
+++ b/test/web/activity_pub/pipeline_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.PipelineTest do
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index ef91954ae..b67bd14b3 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
--
cgit v1.2.3
From dfbc05d4965a04a82d4c4c5b8842f4117757f30e Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Fri, 27 Mar 2020 08:01:03 +0300
Subject: Misc refactoring / tweaks (`ThreadMute.exists?/2`).
---
test/web/mastodon_api/views/account_view_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index ede62903f..0d1c3ecb3 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -186,7 +186,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
describe "relationship" do
defp test_relationship_rendering(user, other_user, expected_result) do
- opts = %{user: user, target: other_user}
+ opts = %{user: user, target: other_user, relationships: nil}
assert expected_result == AccountView.render("relationship.json", opts)
relationships_opt = UserRelationship.view_relationships_option(user, [other_user])
--
cgit v1.2.3
From be9d18461a5ed6bd835e2eba8d3b54ba61fc51fb Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Sat, 28 Mar 2020 18:49:03 +0300
Subject: FollowingRelationship storage & performance optimizations (state
turned `ecto_enum`-driven integer, reorganized indices etc.).
---
test/following_relationship_test.exs | 8 ++++----
test/tasks/user_test.exs | 2 +-
test/user_test.exs | 9 +++++----
test/web/activity_pub/transmogrifier_test.exs | 2 +-
test/web/common_api/common_api_test.exs | 4 ++--
.../mastodon_api/controllers/follow_request_controller_test.exs | 4 ++--
test/web/streamer/streamer_test.exs | 6 +++---
7 files changed, 18 insertions(+), 17 deletions(-)
(limited to 'test')
diff --git a/test/following_relationship_test.exs b/test/following_relationship_test.exs
index 865bb3838..17a468abb 100644
--- a/test/following_relationship_test.exs
+++ b/test/following_relationship_test.exs
@@ -15,28 +15,28 @@ defmodule Pleroma.FollowingRelationshipTest do
test "returns following addresses without internal.fetch" do
user = insert(:user)
fetch_actor = InternalFetchActor.get_actor()
- FollowingRelationship.follow(fetch_actor, user, "accept")
+ FollowingRelationship.follow(fetch_actor, user, :follow_accept)
assert FollowingRelationship.following(fetch_actor) == [user.follower_address]
end
test "returns following addresses without relay" do
user = insert(:user)
relay_actor = Relay.get_actor()
- FollowingRelationship.follow(relay_actor, user, "accept")
+ FollowingRelationship.follow(relay_actor, user, :follow_accept)
assert FollowingRelationship.following(relay_actor) == [user.follower_address]
end
test "returns following addresses without remote user" do
user = insert(:user)
actor = insert(:user, local: false)
- FollowingRelationship.follow(actor, user, "accept")
+ FollowingRelationship.follow(actor, user, :follow_accept)
assert FollowingRelationship.following(actor) == [user.follower_address]
end
test "returns following addresses with local user" do
user = insert(:user)
actor = insert(:user, local: true)
- FollowingRelationship.follow(actor, user, "accept")
+ FollowingRelationship.follow(actor, user, :follow_accept)
assert FollowingRelationship.following(actor) == [
actor.follower_address,
diff --git a/test/tasks/user_test.exs b/test/tasks/user_test.exs
index b45f37263..8df835b56 100644
--- a/test/tasks/user_test.exs
+++ b/test/tasks/user_test.exs
@@ -140,7 +140,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do
test "user is unsubscribed" do
followed = insert(:user)
user = insert(:user)
- User.follow(user, followed, "accept")
+ User.follow(user, followed, :follow_accept)
Mix.Tasks.Pleroma.User.run(["unsubscribe", user.nickname])
diff --git a/test/user_test.exs b/test/user_test.exs
index 8055ebd08..e7dfc5980 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -194,7 +194,8 @@ defmodule Pleroma.UserTest do
CommonAPI.follow(pending_follower, locked)
CommonAPI.follow(pending_follower, locked)
CommonAPI.follow(accepted_follower, locked)
- Pleroma.FollowingRelationship.update(accepted_follower, locked, "accept")
+
+ Pleroma.FollowingRelationship.update(accepted_follower, locked, :follow_accept)
assert [^pending_follower] = User.get_follow_requests(locked)
end
@@ -319,7 +320,7 @@ defmodule Pleroma.UserTest do
following_address: "http://localhost:4001/users/fuser2/following"
})
- {:ok, user} = User.follow(user, followed, "accept")
+ {:ok, user} = User.follow(user, followed, :follow_accept)
{:ok, user, _activity} = User.unfollow(user, followed)
@@ -332,7 +333,7 @@ defmodule Pleroma.UserTest do
followed = insert(:user)
user = insert(:user)
- {:ok, user} = User.follow(user, followed, "accept")
+ {:ok, user} = User.follow(user, followed, :follow_accept)
assert User.following(user) == [user.follower_address, followed.follower_address]
@@ -353,7 +354,7 @@ defmodule Pleroma.UserTest do
test "test if a user is following another user" do
followed = insert(:user)
user = insert(:user)
- User.follow(user, followed, "accept")
+ User.follow(user, followed, :follow_accept)
assert User.following?(user, followed)
refute User.following?(followed, user)
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index b2cabbd30..b998f0d78 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -1622,7 +1622,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
})
user_two = insert(:user)
- Pleroma.FollowingRelationship.follow(user_two, user, "accept")
+ Pleroma.FollowingRelationship.follow(user_two, user, :follow_accept)
{:ok, activity} = CommonAPI.post(user, %{"status" => "test"})
{:ok, unrelated_activity} = CommonAPI.post(user_two, %{"status" => "test"})
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index 0da0bd2e2..e53a7cedd 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -562,7 +562,7 @@ defmodule Pleroma.Web.CommonAPITest do
assert {:ok, follower, followed, %{id: activity_id, data: %{"state" => "pending"}}} =
CommonAPI.follow(follower, followed)
- assert User.get_follow_state(follower, followed) == "pending"
+ assert User.get_follow_state(follower, followed) == :follow_pending
assert {:ok, follower} = CommonAPI.unfollow(follower, followed)
assert User.get_follow_state(follower, followed) == nil
@@ -584,7 +584,7 @@ defmodule Pleroma.Web.CommonAPITest do
assert {:ok, follower, followed, %{id: activity_id, data: %{"state" => "pending"}}} =
CommonAPI.follow(follower, followed)
- assert User.get_follow_state(follower, followed) == "pending"
+ assert User.get_follow_state(follower, followed) == :follow_pending
assert {:ok, follower} = CommonAPI.unfollow(follower, followed)
assert User.get_follow_state(follower, followed) == nil
diff --git a/test/web/mastodon_api/controllers/follow_request_controller_test.exs b/test/web/mastodon_api/controllers/follow_request_controller_test.exs
index dd848821a..d8dbe4800 100644
--- a/test/web/mastodon_api/controllers/follow_request_controller_test.exs
+++ b/test/web/mastodon_api/controllers/follow_request_controller_test.exs
@@ -21,7 +21,7 @@ defmodule Pleroma.Web.MastodonAPI.FollowRequestControllerTest do
other_user = insert(:user)
{:ok, _activity} = ActivityPub.follow(other_user, user)
- {:ok, other_user} = User.follow(other_user, user, "pending")
+ {:ok, other_user} = User.follow(other_user, user, :follow_pending)
assert User.following?(other_user, user) == false
@@ -35,7 +35,7 @@ defmodule Pleroma.Web.MastodonAPI.FollowRequestControllerTest do
other_user = insert(:user)
{:ok, _activity} = ActivityPub.follow(other_user, user)
- {:ok, other_user} = User.follow(other_user, user, "pending")
+ {:ok, other_user} = User.follow(other_user, user, :follow_pending)
user = User.get_cached_by_id(user.id)
other_user = User.get_cached_by_id(other_user.id)
diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs
index a5d6e8ecf..ad8ce030b 100644
--- a/test/web/streamer/streamer_test.exs
+++ b/test/web/streamer/streamer_test.exs
@@ -197,7 +197,7 @@ defmodule Pleroma.Web.StreamerTest do
Pleroma.Config.put([:instance, :skip_thread_containment], false)
author = insert(:user)
user = insert(:user)
- User.follow(user, author, "accept")
+ User.follow(user, author, :follow_accept)
activity =
insert(:note_activity,
@@ -220,7 +220,7 @@ defmodule Pleroma.Web.StreamerTest do
Pleroma.Config.put([:instance, :skip_thread_containment], true)
author = insert(:user)
user = insert(:user)
- User.follow(user, author, "accept")
+ User.follow(user, author, :follow_accept)
activity =
insert(:note_activity,
@@ -243,7 +243,7 @@ defmodule Pleroma.Web.StreamerTest do
Pleroma.Config.put([:instance, :skip_thread_containment], false)
author = insert(:user)
user = insert(:user, skip_thread_containment: true)
- User.follow(user, author, "accept")
+ User.follow(user, author, :follow_accept)
activity =
insert(:note_activity,
--
cgit v1.2.3
From b607ae1a1c0ef6557094ec0fb10ba2d19d621f7f Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Mon, 30 Mar 2020 13:50:00 +0300
Subject: removing grouped reports admin api endpoint
---
test/web/admin_api/admin_api_controller_test.exs | 203 -----------------------
1 file changed, 203 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index c9e228cc8..ea0c92502 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -21,7 +21,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
alias Pleroma.UserInviteToken
alias Pleroma.Web.ActivityPub.Relay
alias Pleroma.Web.CommonAPI
- alias Pleroma.Web.MastodonAPI.StatusView
alias Pleroma.Web.MediaProxy
setup_all do
@@ -1586,208 +1585,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
end
- describe "GET /api/pleroma/admin/grouped_reports" do
- setup do
- [reporter, target_user] = insert_pair(:user)
-
- date1 = (DateTime.to_unix(DateTime.utc_now()) + 1000) |> DateTime.from_unix!()
- date2 = (DateTime.to_unix(DateTime.utc_now()) + 2000) |> DateTime.from_unix!()
- date3 = (DateTime.to_unix(DateTime.utc_now()) + 3000) |> DateTime.from_unix!()
-
- first_status =
- insert(:note_activity, user: target_user, data_attrs: %{"published" => date1})
-
- second_status =
- insert(:note_activity, user: target_user, data_attrs: %{"published" => date2})
-
- third_status =
- insert(:note_activity, user: target_user, data_attrs: %{"published" => date3})
-
- {:ok, first_report} =
- CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "status_ids" => [first_status.id, second_status.id, third_status.id]
- })
-
- {:ok, second_report} =
- CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "status_ids" => [first_status.id, second_status.id]
- })
-
- {:ok, third_report} =
- CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "status_ids" => [first_status.id]
- })
-
- %{
- first_status: Activity.get_by_ap_id_with_object(first_status.data["id"]),
- second_status: Activity.get_by_ap_id_with_object(second_status.data["id"]),
- third_status: Activity.get_by_ap_id_with_object(third_status.data["id"]),
- first_report: first_report,
- first_status_reports: [first_report, second_report, third_report],
- second_status_reports: [first_report, second_report],
- third_status_reports: [first_report],
- target_user: target_user,
- reporter: reporter
- }
- end
-
- test "returns reports grouped by status", %{
- conn: conn,
- first_status: first_status,
- second_status: second_status,
- third_status: third_status,
- first_status_reports: first_status_reports,
- second_status_reports: second_status_reports,
- third_status_reports: third_status_reports,
- target_user: target_user,
- reporter: reporter
- } do
- response =
- conn
- |> get("/api/pleroma/admin/grouped_reports")
- |> json_response(:ok)
-
- assert length(response["reports"]) == 3
-
- first_group = Enum.find(response["reports"], &(&1["status"]["id"] == first_status.id))
-
- second_group = Enum.find(response["reports"], &(&1["status"]["id"] == second_status.id))
-
- third_group = Enum.find(response["reports"], &(&1["status"]["id"] == third_status.id))
-
- assert length(first_group["reports"]) == 3
- assert length(second_group["reports"]) == 2
- assert length(third_group["reports"]) == 1
-
- assert first_group["date"] ==
- Enum.max_by(first_status_reports, fn act ->
- NaiveDateTime.from_iso8601!(act.data["published"])
- end).data["published"]
-
- assert first_group["status"] ==
- Map.put(
- stringify_keys(StatusView.render("show.json", %{activity: first_status})),
- "deleted",
- false
- )
-
- assert(first_group["account"]["id"] == target_user.id)
-
- assert length(first_group["actors"]) == 1
- assert hd(first_group["actors"])["id"] == reporter.id
-
- assert Enum.map(first_group["reports"], & &1["id"]) --
- Enum.map(first_status_reports, & &1.id) == []
-
- assert second_group["date"] ==
- Enum.max_by(second_status_reports, fn act ->
- NaiveDateTime.from_iso8601!(act.data["published"])
- end).data["published"]
-
- assert second_group["status"] ==
- Map.put(
- stringify_keys(StatusView.render("show.json", %{activity: second_status})),
- "deleted",
- false
- )
-
- assert second_group["account"]["id"] == target_user.id
-
- assert length(second_group["actors"]) == 1
- assert hd(second_group["actors"])["id"] == reporter.id
-
- assert Enum.map(second_group["reports"], & &1["id"]) --
- Enum.map(second_status_reports, & &1.id) == []
-
- assert third_group["date"] ==
- Enum.max_by(third_status_reports, fn act ->
- NaiveDateTime.from_iso8601!(act.data["published"])
- end).data["published"]
-
- assert third_group["status"] ==
- Map.put(
- stringify_keys(StatusView.render("show.json", %{activity: third_status})),
- "deleted",
- false
- )
-
- assert third_group["account"]["id"] == target_user.id
-
- assert length(third_group["actors"]) == 1
- assert hd(third_group["actors"])["id"] == reporter.id
-
- assert Enum.map(third_group["reports"], & &1["id"]) --
- Enum.map(third_status_reports, & &1.id) == []
- end
-
- test "reopened report renders status data", %{
- conn: conn,
- first_report: first_report,
- first_status: first_status
- } do
- {:ok, _} = CommonAPI.update_report_state(first_report.id, "resolved")
-
- response =
- conn
- |> get("/api/pleroma/admin/grouped_reports")
- |> json_response(:ok)
-
- first_group = Enum.find(response["reports"], &(&1["status"]["id"] == first_status.id))
-
- assert first_group["status"] ==
- Map.put(
- stringify_keys(StatusView.render("show.json", %{activity: first_status})),
- "deleted",
- false
- )
- end
-
- test "reopened report does not render status data if status has been deleted", %{
- conn: conn,
- first_report: first_report,
- first_status: first_status,
- target_user: target_user
- } do
- {:ok, _} = CommonAPI.update_report_state(first_report.id, "resolved")
- {:ok, _} = CommonAPI.delete(first_status.id, target_user)
-
- refute Activity.get_by_ap_id(first_status.id)
-
- response =
- conn
- |> get("/api/pleroma/admin/grouped_reports")
- |> json_response(:ok)
-
- assert Enum.find(response["reports"], &(&1["status"]["deleted"] == true))["status"][
- "deleted"
- ] == true
-
- assert length(Enum.filter(response["reports"], &(&1["status"]["deleted"] == false))) == 2
- end
-
- test "account not empty if status was deleted", %{
- conn: conn,
- first_report: first_report,
- first_status: first_status,
- target_user: target_user
- } do
- {:ok, _} = CommonAPI.update_report_state(first_report.id, "resolved")
- {:ok, _} = CommonAPI.delete(first_status.id, target_user)
-
- refute Activity.get_by_ap_id(first_status.id)
-
- response =
- conn
- |> get("/api/pleroma/admin/grouped_reports")
- |> json_response(:ok)
-
- assert Enum.find(response["reports"], &(&1["status"]["deleted"] == true))["account"]
- end
- end
-
describe "PUT /api/pleroma/admin/statuses/:id" do
setup do
activity = insert(:note_activity)
--
cgit v1.2.3
From 643f15e77b7cdaaf2c22a876c98e5680edc32dc3 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 31 Mar 2020 16:11:38 +0200
Subject: Validators: ObjectID is an http uri.
---
.../object_validators/types/object_id_test.exs | 38 ++++++++++++++++++++++
1 file changed, 38 insertions(+)
create mode 100644 test/web/activity_pub/object_validators/types/object_id_test.exs
(limited to 'test')
diff --git a/test/web/activity_pub/object_validators/types/object_id_test.exs b/test/web/activity_pub/object_validators/types/object_id_test.exs
new file mode 100644
index 000000000..f4c5ed1dc
--- /dev/null
+++ b/test/web/activity_pub/object_validators/types/object_id_test.exs
@@ -0,0 +1,38 @@
+defmodule Pleroma.Web.ObjectValidators.Types.ObjectIDTest do
+ alias Pleroma.Web.ActivityPub.ObjectValidators.Types.ObjectID
+ use Pleroma.DataCase
+
+ @uris [
+ "http://lain.com/users/lain",
+ "http://lain.com",
+ "https://lain.com/object/1"
+ ]
+
+ @non_uris [
+ "https://",
+ "rin"
+ ]
+
+ test "it rejects integers" do
+ assert :error == ObjectID.cast(1)
+ end
+
+ test "it accepts http uris" do
+ Enum.each(@uris, fn uri ->
+ assert {:ok, uri} == ObjectID.cast(uri)
+ end)
+ end
+
+ test "it accepts an object with a nested uri id" do
+ Enum.each(@uris, fn uri ->
+ assert {:ok, uri} == ObjectID.cast(%{"id" => uri})
+ end)
+ end
+
+ test "it rejects non-uri strings" do
+ Enum.each(@non_uris, fn non_uri ->
+ assert :error == ObjectID.cast(non_uri)
+ assert :error == ObjectID.cast(%{"id" => non_uri})
+ end)
+ end
+end
--
cgit v1.2.3
From df5f89c0d6d8d385434d5d8a51719fa41631d7b2 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 31 Mar 2020 18:22:25 +0300
Subject: test for default features and changelog entry
---
test/web/node_info_test.exs | 92 +++++++++++++++++++++++----------------------
1 file changed, 48 insertions(+), 44 deletions(-)
(limited to 'test')
diff --git a/test/web/node_info_test.exs b/test/web/node_info_test.exs
index e5eebced1..9bcc07b37 100644
--- a/test/web/node_info_test.exs
+++ b/test/web/node_info_test.exs
@@ -7,6 +7,8 @@ defmodule Pleroma.Web.NodeInfoTest do
import Pleroma.Factory
+ alias Pleroma.Config
+
setup do: clear_config([:mrf_simple])
setup do: clear_config(:instance)
@@ -47,7 +49,7 @@ defmodule Pleroma.Web.NodeInfoTest do
assert result = json_response(conn, 200)
- assert Pleroma.Config.get([Pleroma.User, :restricted_nicknames]) ==
+ assert Config.get([Pleroma.User, :restricted_nicknames]) ==
result["metadata"]["restrictedNicknames"]
end
@@ -65,10 +67,10 @@ defmodule Pleroma.Web.NodeInfoTest do
end
test "returns fieldsLimits field", %{conn: conn} do
- Pleroma.Config.put([:instance, :max_account_fields], 10)
- Pleroma.Config.put([:instance, :max_remote_account_fields], 15)
- Pleroma.Config.put([:instance, :account_field_name_length], 255)
- Pleroma.Config.put([:instance, :account_field_value_length], 2048)
+ Config.put([:instance, :max_account_fields], 10)
+ Config.put([:instance, :max_remote_account_fields], 15)
+ Config.put([:instance, :account_field_name_length], 255)
+ Config.put([:instance, :account_field_value_length], 2048)
response =
conn
@@ -82,8 +84,8 @@ defmodule Pleroma.Web.NodeInfoTest do
end
test "it returns the safe_dm_mentions feature if enabled", %{conn: conn} do
- option = Pleroma.Config.get([:instance, :safe_dm_mentions])
- Pleroma.Config.put([:instance, :safe_dm_mentions], true)
+ option = Config.get([:instance, :safe_dm_mentions])
+ Config.put([:instance, :safe_dm_mentions], true)
response =
conn
@@ -92,7 +94,7 @@ defmodule Pleroma.Web.NodeInfoTest do
assert "safe_dm_mentions" in response["metadata"]["features"]
- Pleroma.Config.put([:instance, :safe_dm_mentions], false)
+ Config.put([:instance, :safe_dm_mentions], false)
response =
conn
@@ -101,14 +103,14 @@ defmodule Pleroma.Web.NodeInfoTest do
refute "safe_dm_mentions" in response["metadata"]["features"]
- Pleroma.Config.put([:instance, :safe_dm_mentions], option)
+ Config.put([:instance, :safe_dm_mentions], option)
end
describe "`metadata/federation/enabled`" do
setup do: clear_config([:instance, :federating])
test "it shows if federation is enabled/disabled", %{conn: conn} do
- Pleroma.Config.put([:instance, :federating], true)
+ Config.put([:instance, :federating], true)
response =
conn
@@ -117,7 +119,7 @@ defmodule Pleroma.Web.NodeInfoTest do
assert response["metadata"]["federation"]["enabled"] == true
- Pleroma.Config.put([:instance, :federating], false)
+ Config.put([:instance, :federating], false)
response =
conn
@@ -134,31 +136,33 @@ defmodule Pleroma.Web.NodeInfoTest do
|> get("/nodeinfo/2.1.json")
|> json_response(:ok)
- assert response["metadata"]["features"] --
- [
- "pleroma_api",
- "mastodon_api",
- "mastodon_api_streaming",
- "polls",
- "pleroma_explicit_addressing",
- "shareable_emoji_packs",
- "multifetch",
- "chat",
- "relay",
- "pleroma_emoji_reactions",
- "pleroma:api/v1/notifications:include_types_filter"
- ] == []
+ default_features = [
+ "pleroma_api",
+ "mastodon_api",
+ "mastodon_api_streaming",
+ "polls",
+ "pleroma_explicit_addressing",
+ "shareable_emoji_packs",
+ "multifetch",
+ "pleroma_emoji_reactions",
+ "pleroma:api/v1/notifications:include_types_filter"
+ ]
+
+ assert MapSet.subset?(
+ MapSet.new(default_features),
+ MapSet.new(response["metadata"]["features"])
+ )
end
test "it shows MRF transparency data if enabled", %{conn: conn} do
- config = Pleroma.Config.get([:instance, :rewrite_policy])
- Pleroma.Config.put([:instance, :rewrite_policy], [Pleroma.Web.ActivityPub.MRF.SimplePolicy])
+ config = Config.get([:instance, :rewrite_policy])
+ Config.put([:instance, :rewrite_policy], [Pleroma.Web.ActivityPub.MRF.SimplePolicy])
- option = Pleroma.Config.get([:instance, :mrf_transparency])
- Pleroma.Config.put([:instance, :mrf_transparency], true)
+ option = Config.get([:instance, :mrf_transparency])
+ Config.put([:instance, :mrf_transparency], true)
simple_config = %{"reject" => ["example.com"]}
- Pleroma.Config.put(:mrf_simple, simple_config)
+ Config.put(:mrf_simple, simple_config)
response =
conn
@@ -167,25 +171,25 @@ defmodule Pleroma.Web.NodeInfoTest do
assert response["metadata"]["federation"]["mrf_simple"] == simple_config
- Pleroma.Config.put([:instance, :rewrite_policy], config)
- Pleroma.Config.put([:instance, :mrf_transparency], option)
- Pleroma.Config.put(:mrf_simple, %{})
+ Config.put([:instance, :rewrite_policy], config)
+ Config.put([:instance, :mrf_transparency], option)
+ Config.put(:mrf_simple, %{})
end
test "it performs exclusions from MRF transparency data if configured", %{conn: conn} do
- config = Pleroma.Config.get([:instance, :rewrite_policy])
- Pleroma.Config.put([:instance, :rewrite_policy], [Pleroma.Web.ActivityPub.MRF.SimplePolicy])
+ config = Config.get([:instance, :rewrite_policy])
+ Config.put([:instance, :rewrite_policy], [Pleroma.Web.ActivityPub.MRF.SimplePolicy])
- option = Pleroma.Config.get([:instance, :mrf_transparency])
- Pleroma.Config.put([:instance, :mrf_transparency], true)
+ option = Config.get([:instance, :mrf_transparency])
+ Config.put([:instance, :mrf_transparency], true)
- exclusions = Pleroma.Config.get([:instance, :mrf_transparency_exclusions])
- Pleroma.Config.put([:instance, :mrf_transparency_exclusions], ["other.site"])
+ exclusions = Config.get([:instance, :mrf_transparency_exclusions])
+ Config.put([:instance, :mrf_transparency_exclusions], ["other.site"])
simple_config = %{"reject" => ["example.com", "other.site"]}
expected_config = %{"reject" => ["example.com"]}
- Pleroma.Config.put(:mrf_simple, simple_config)
+ Config.put(:mrf_simple, simple_config)
response =
conn
@@ -195,9 +199,9 @@ defmodule Pleroma.Web.NodeInfoTest do
assert response["metadata"]["federation"]["mrf_simple"] == expected_config
assert response["metadata"]["federation"]["exclusions"] == true
- Pleroma.Config.put([:instance, :rewrite_policy], config)
- Pleroma.Config.put([:instance, :mrf_transparency], option)
- Pleroma.Config.put([:instance, :mrf_transparency_exclusions], exclusions)
- Pleroma.Config.put(:mrf_simple, %{})
+ Config.put([:instance, :rewrite_policy], config)
+ Config.put([:instance, :mrf_transparency], option)
+ Config.put([:instance, :mrf_transparency_exclusions], exclusions)
+ Config.put(:mrf_simple, %{})
end
end
--
cgit v1.2.3
From aebec1bac9831da2bed5ee571225d92dc99a5d59 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 31 Mar 2020 17:47:34 +0200
Subject: Validator Test: Small refactor.
---
test/web/activity_pub/object_validators/types/object_id_test.exs | 9 ++++-----
1 file changed, 4 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validators/types/object_id_test.exs b/test/web/activity_pub/object_validators/types/object_id_test.exs
index f4c5ed1dc..834213182 100644
--- a/test/web/activity_pub/object_validators/types/object_id_test.exs
+++ b/test/web/activity_pub/object_validators/types/object_id_test.exs
@@ -10,13 +10,12 @@ defmodule Pleroma.Web.ObjectValidators.Types.ObjectIDTest do
@non_uris [
"https://",
- "rin"
+ "rin",
+ 1,
+ :x,
+ %{"1" => 2}
]
- test "it rejects integers" do
- assert :error == ObjectID.cast(1)
- end
-
test "it accepts http uris" do
Enum.each(@uris, fn uri ->
assert {:ok, uri} == ObjectID.cast(uri)
--
cgit v1.2.3
From dbf9d719f98770056ac906b3087e7ed501cd64e6 Mon Sep 17 00:00:00 2001
From: kPherox
Date: Wed, 1 Apr 2020 00:05:13 +0900
Subject: split test for update profile fields
---
.../account_controller/update_credentials_test.exs | 68 ++++++++++++----------
1 file changed, 38 insertions(+), 30 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
index b693c1a47..8687d7995 100644
--- a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
@@ -273,7 +273,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
test "update fields", %{conn: conn} do
fields = [
%{"name" => "foo", "value" => ""},
- %{"name" => "link", "value" => "cofe.io"}
+ %{"name" => "link.io", "value" => "cofe.io"}
]
account_data =
@@ -283,7 +283,10 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
assert account_data["fields"] == [
%{"name" => "foo", "value" => "bar"},
- %{"name" => "link", "value" => ~S(cofe.io)}
+ %{
+ "name" => "link.io",
+ "value" => ~S(cofe.io)
+ }
]
assert account_data["source"]["fields"] == [
@@ -291,14 +294,16 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
"name" => "foo",
"value" => ""
},
- %{"name" => "link", "value" => "cofe.io"}
+ %{"name" => "link.io", "value" => "cofe.io"}
]
+ end
+ test "update fields by urlencoded", %{conn: conn} do
fields =
[
"fields_attributes[1][name]=link",
- "fields_attributes[1][value]=cofe.io",
- "fields_attributes[0][name]=foo",
+ "fields_attributes[1][value]=http://cofe.io",
+ "fields_attributes[0][name]=foo",
"fields_attributes[0][value]=bar"
]
|> Enum.join("&")
@@ -310,32 +315,49 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
|> json_response(200)
assert account["fields"] == [
- %{"name" => "foo", "value" => "bar"},
- %{"name" => "link", "value" => ~S(cofe.io)}
+ %{"name" => "foo", "value" => "bar"},
+ %{
+ "name" => "link",
+ "value" => ~S(http://cofe.io)
+ }
]
assert account["source"]["fields"] == [
- %{
- "name" => "foo",
- "value" => "bar"
- },
- %{"name" => "link", "value" => "cofe.io"}
+ %{"name" => "foo", "value" => "bar"},
+ %{"name" => "link", "value" => "http://cofe.io"}
]
+ end
+ test "update fields with empty name", %{conn: conn} do
+ fields = [
+ %{"name" => "foo", "value" => ""},
+ %{"name" => "", "value" => "bar"}
+ ]
+
+ account =
+ conn
+ |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
+ |> json_response(200)
+
+ assert account["fields"] == [
+ %{"name" => "foo", "value" => ""}
+ ]
+ end
+
+ test "update fields when invalid request", %{conn: conn} do
name_limit = Pleroma.Config.get([:instance, :account_field_name_length])
value_limit = Pleroma.Config.get([:instance, :account_field_value_length])
+ long_name = Enum.map(0..name_limit, fn _ -> "x" end) |> Enum.join()
long_value = Enum.map(0..value_limit, fn _ -> "x" end) |> Enum.join()
- fields = [%{"name" => "foo", "value" => long_value}]
+ fields = [%{"name" => "foo", "value" => long_value}]
assert %{"error" => "Invalid request"} ==
conn
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
|> json_response(403)
- long_name = Enum.map(0..name_limit, fn _ -> "x" end) |> Enum.join()
-
fields = [%{"name" => long_name, "value" => "bar"}]
assert %{"error" => "Invalid request"} ==
@@ -346,7 +368,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
Pleroma.Config.put([:instance, :max_account_fields], 1)
fields = [
- %{"name" => "foo", "value" => "bar"},
+ %{"name" => "foo", "value" => "bar"},
%{"name" => "link", "value" => "cofe.io"}
]
@@ -354,20 +376,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
conn
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
|> json_response(403)
-
- fields = [
- %{"name" => "foo", "value" => ""},
- %{"name" => "", "value" => "bar"}
- ]
-
- account =
- conn
- |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
- |> json_response(200)
-
- assert account["fields"] == [
- %{"name" => "foo", "value" => ""}
- ]
end
end
end
--
cgit v1.2.3
From 2553400a662de7170dd56ee0950a6c1bb1513e45 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Sun, 29 Mar 2020 22:01:49 +0200
Subject: Initial failing test statement against funkwhale channels
---
test/web/mastodon_api/views/account_view_test.exs | 21 +++++++++++++++++++--
1 file changed, 19 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index 0d1c3ecb3..8d00e3c21 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -5,13 +5,19 @@
defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
use Pleroma.DataCase
- import Pleroma.Factory
-
alias Pleroma.User
alias Pleroma.UserRelationship
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.MastodonAPI.AccountView
+ import Pleroma.Factory
+ import Tesla.Mock
+
+ setup do
+ mock(fn env -> apply(HttpRequestMock, :request, [env]) end)
+ :ok
+ end
+
test "Represent a user account" do
source_data = %{
"tag" => [
@@ -164,6 +170,17 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
assert expected == AccountView.render("show.json", %{user: user})
end
+ test "Represent a Funkwhale channel" do
+ {:ok, user} =
+ User.get_or_fetch_by_ap_id(
+ "https://channels.tests.funkwhale.audio/federation/actors/compositions"
+ )
+
+ assert represented = AccountView.render("show.json", %{user: user})
+ assert represented.acct == "compositions@channels.tests.funkwhale.audio"
+ assert represented.url == "https://channels.tests.funkwhale.audio/channels/compositions"
+ end
+
test "Represent a deactivated user for an admin" do
admin = insert(:user, is_admin: true)
deactivated_user = insert(:user, deactivated: true)
--
cgit v1.2.3
From b30fb1f3bbf8fb8e49cc5276225dc09771c79477 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Sun, 29 Mar 2020 22:30:50 +0200
Subject: User: Fix use of source_data in profile_url/1
---
test/web/mastodon_api/views/account_view_test.exs | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index 8d00e3c21..ef3f3eff1 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -178,7 +178,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
assert represented = AccountView.render("show.json", %{user: user})
assert represented.acct == "compositions@channels.tests.funkwhale.audio"
- assert represented.url == "https://channels.tests.funkwhale.audio/channels/compositions"
+ # assert represented.url == "https://channels.tests.funkwhale.audio/channels/compositions"
+ assert represented.url ==
+ "https://channels.tests.funkwhale.audio/federation/actors/compositions"
end
test "Represent a deactivated user for an admin" do
--
cgit v1.2.3
From 185520d1b4d3fdf8ecde7814faec92bbb531ce59 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Mon, 30 Mar 2020 02:01:09 +0200
Subject: Provide known-good user.uri, remove User.profile_url/1
---
test/web/mastodon_api/views/account_view_test.exs | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index ef3f3eff1..8d00e3c21 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -178,9 +178,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
assert represented = AccountView.render("show.json", %{user: user})
assert represented.acct == "compositions@channels.tests.funkwhale.audio"
- # assert represented.url == "https://channels.tests.funkwhale.audio/channels/compositions"
- assert represented.url ==
- "https://channels.tests.funkwhale.audio/federation/actors/compositions"
+ assert represented.url == "https://channels.tests.funkwhale.audio/channels/compositions"
end
test "Represent a deactivated user for an admin" do
--
cgit v1.2.3
From 94ddbe4098e167f9537d168261a6cc76fa17508b Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 1 Apr 2020 09:55:05 +0300
Subject: restrict remote users from indexing
---
test/web/metadata/metadata_test.exs | 25 +++++++++++++++++++++++++
test/web/metadata/restrict_indexing_test.exs | 21 +++++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 test/web/metadata/metadata_test.exs
create mode 100644 test/web/metadata/restrict_indexing_test.exs
(limited to 'test')
diff --git a/test/web/metadata/metadata_test.exs b/test/web/metadata/metadata_test.exs
new file mode 100644
index 000000000..3f8b29e58
--- /dev/null
+++ b/test/web/metadata/metadata_test.exs
@@ -0,0 +1,25 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.MetadataTest do
+ use Pleroma.DataCase, async: true
+
+ import Pleroma.Factory
+
+ describe "restrict indexing remote users" do
+ test "for remote user" do
+ user = insert(:user, local: false)
+
+ assert Pleroma.Web.Metadata.build_tags(%{user: user}) =~
+ ""
+ end
+
+ test "for local user" do
+ user = insert(:user)
+
+ refute Pleroma.Web.Metadata.build_tags(%{user: user}) =~
+ ""
+ end
+ end
+end
diff --git a/test/web/metadata/restrict_indexing_test.exs b/test/web/metadata/restrict_indexing_test.exs
new file mode 100644
index 000000000..aad0bac42
--- /dev/null
+++ b/test/web/metadata/restrict_indexing_test.exs
@@ -0,0 +1,21 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.Metadata.Providers.RestrictIndexingTest do
+ use ExUnit.Case, async: true
+
+ describe "build_tags/1" do
+ test "for remote user" do
+ assert Pleroma.Web.Metadata.Providers.RestrictIndexing.build_tags(%{
+ user: %Pleroma.User{local: false}
+ }) == [{:meta, [name: "robots", content: "noindex, noarchive"], []}]
+ end
+
+ test "for local user" do
+ assert Pleroma.Web.Metadata.Providers.RestrictIndexing.build_tags(%{
+ user: %Pleroma.User{local: true}
+ }) == []
+ end
+ end
+end
--
cgit v1.2.3
From 2f2bd7fe72f474b7177c751a2dc3af716622ba91 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Wed, 1 Apr 2020 19:49:09 +0300
Subject: Ability to control the output of account/pleroma/relationship in
statuses in order to improve the rendering performance. See `[:extensions,
output_relationships_in_statuses_by_default]` setting and
`with_relationships` param.
---
.../controllers/notification_controller_test.exs | 20 +++++++++++++++
.../controllers/status_controller_test.exs | 6 +++--
.../controllers/timeline_controller_test.exs | 29 +++++++++++++++++++---
3 files changed, 50 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs
index 7a0011646..42a311f99 100644
--- a/test/web/mastodon_api/controllers/notification_controller_test.exs
+++ b/test/web/mastodon_api/controllers/notification_controller_test.exs
@@ -12,6 +12,26 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
import Pleroma.Factory
+ test "does NOT render account/pleroma/relationship if this is disabled by default" do
+ clear_config([:extensions, :output_relationships_in_statuses_by_default], false)
+
+ %{user: user, conn: conn} = oauth_access(["read:notifications"])
+ other_user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
+ {:ok, [_notification]} = Notification.create_notifications(activity)
+
+ response =
+ conn
+ |> assign(:user, user)
+ |> get("/api/v1/notifications")
+ |> json_response(200)
+
+ assert Enum.all?(response, fn n ->
+ get_in(n, ["account", "pleroma", "relationship"]) == %{}
+ end)
+ end
+
test "list of notifications" do
%{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user)
diff --git a/test/web/mastodon_api/controllers/status_controller_test.exs b/test/web/mastodon_api/controllers/status_controller_test.exs
index d59974d50..6b126217a 100644
--- a/test/web/mastodon_api/controllers/status_controller_test.exs
+++ b/test/web/mastodon_api/controllers/status_controller_test.exs
@@ -1043,6 +1043,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
end
test "bookmarks" do
+ bookmarks_uri = "/api/v1/bookmarks?with_relationships=true"
+
%{conn: conn} = oauth_access(["write:bookmarks", "read:bookmarks"])
author = insert(:user)
@@ -1064,7 +1066,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
assert json_response(response2, 200)["bookmarked"] == true
- bookmarks = get(conn, "/api/v1/bookmarks")
+ bookmarks = get(conn, bookmarks_uri)
assert [json_response(response2, 200), json_response(response1, 200)] ==
json_response(bookmarks, 200)
@@ -1073,7 +1075,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
assert json_response(response1, 200)["bookmarked"] == false
- bookmarks = get(conn, "/api/v1/bookmarks")
+ bookmarks = get(conn, bookmarks_uri)
assert [json_response(response2, 200)] == json_response(bookmarks, 200)
end
diff --git a/test/web/mastodon_api/controllers/timeline_controller_test.exs b/test/web/mastodon_api/controllers/timeline_controller_test.exs
index 97b1c3e66..06efdc901 100644
--- a/test/web/mastodon_api/controllers/timeline_controller_test.exs
+++ b/test/web/mastodon_api/controllers/timeline_controller_test.exs
@@ -20,7 +20,30 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
describe "home" do
setup do: oauth_access(["read:statuses"])
+ test "does NOT render account/pleroma/relationship if this is disabled by default", %{
+ user: user,
+ conn: conn
+ } do
+ clear_config([:extensions, :output_relationships_in_statuses_by_default], false)
+
+ other_user = insert(:user)
+
+ {:ok, _} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
+
+ response =
+ conn
+ |> assign(:user, user)
+ |> get("/api/v1/timelines/home")
+ |> json_response(200)
+
+ assert Enum.all?(response, fn n ->
+ get_in(n, ["account", "pleroma", "relationship"]) == %{}
+ end)
+ end
+
test "the home timeline", %{user: user, conn: conn} do
+ uri = "/api/v1/timelines/home?with_relationships=true"
+
following = insert(:user, nickname: "followed")
third_user = insert(:user, nickname: "repeated")
@@ -28,13 +51,13 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
{:ok, activity} = CommonAPI.post(third_user, %{"status" => "repeated post"})
{:ok, _, _} = CommonAPI.repeat(activity.id, following)
- ret_conn = get(conn, "/api/v1/timelines/home")
+ ret_conn = get(conn, uri)
assert Enum.empty?(json_response(ret_conn, :ok))
{:ok, _user} = User.follow(user, following)
- ret_conn = get(conn, "/api/v1/timelines/home")
+ ret_conn = get(conn, uri)
assert [
%{
@@ -59,7 +82,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
{:ok, _user} = User.follow(third_user, user)
- ret_conn = get(conn, "/api/v1/timelines/home")
+ ret_conn = get(conn, uri)
assert [
%{
--
cgit v1.2.3
From 2d64500a9dee8bc53c988719bde1c1f4f41575b7 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 1 Apr 2020 20:26:33 +0300
Subject: error improvement for email_invite endpoint
---
test/web/admin_api/admin_api_controller_test.exs | 39 ++++++++++++++++++++++--
1 file changed, 37 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index ea0c92502..32fe69d19 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -625,6 +625,39 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
assert json_response(conn, :forbidden)
end
+
+ test "email with +", %{conn: conn, admin: admin} do
+ recipient_email = "foo+bar@baz.com"
+
+ conn
+ |> put_req_header("content-type", "application/json;charset=utf-8")
+ |> post("/api/pleroma/admin/users/email_invite", %{email: recipient_email})
+ |> json_response(:no_content)
+
+ token_record =
+ Pleroma.UserInviteToken
+ |> Repo.all()
+ |> List.last()
+
+ assert token_record
+ refute token_record.used
+
+ notify_email = Config.get([:instance, :notify_email])
+ instance_name = Config.get([:instance, :name])
+
+ email =
+ Pleroma.Emails.UserEmail.user_invitation_email(
+ admin,
+ token_record,
+ recipient_email
+ )
+
+ Swoosh.TestAssertions.assert_email_sent(
+ from: {instance_name, notify_email},
+ to: recipient_email,
+ html_body: email.html_body
+ )
+ end
end
describe "POST /api/pleroma/admin/users/email_invite, with invalid config" do
@@ -637,7 +670,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
- assert json_response(conn, :internal_server_error)
+ assert json_response(conn, :bad_request) ==
+ "To send invites you need set `invites_enabled` option to true."
end
test "it returns 500 if `registrations_open` is enabled", %{conn: conn} do
@@ -646,7 +680,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
- assert json_response(conn, :internal_server_error)
+ assert json_response(conn, :bad_request) ==
+ "To send invites you need set `registrations_open` option to false."
end
end
--
cgit v1.2.3
From 23219e6fb3163bfac07fb5fb1b2602dcd27e47c2 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 1 Apr 2020 23:00:59 +0400
Subject: Add OpenAPI
---
test/web/api_spec/app_operation_test.exs | 45 ++++++++++++++++++++++
.../controllers/account_controller_test.exs | 4 +-
.../controllers/app_controller_test.exs | 4 +-
3 files changed, 50 insertions(+), 3 deletions(-)
create mode 100644 test/web/api_spec/app_operation_test.exs
(limited to 'test')
diff --git a/test/web/api_spec/app_operation_test.exs b/test/web/api_spec/app_operation_test.exs
new file mode 100644
index 000000000..5b96abb44
--- /dev/null
+++ b/test/web/api_spec/app_operation_test.exs
@@ -0,0 +1,45 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ApiSpec.AppOperationTest do
+ use Pleroma.Web.ConnCase, async: true
+
+ alias Pleroma.Web.ApiSpec
+ alias Pleroma.Web.ApiSpec.Schemas.AppCreateRequest
+ alias Pleroma.Web.ApiSpec.Schemas.AppCreateResponse
+
+ import OpenApiSpex.TestAssertions
+ import Pleroma.Factory
+
+ test "AppCreateRequest example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = AppCreateRequest.schema()
+ assert_schema(schema.example, "AppCreateRequest", api_spec)
+ end
+
+ test "AppCreateResponse example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = AppCreateResponse.schema()
+ assert_schema(schema.example, "AppCreateResponse", api_spec)
+ end
+
+ test "AppController produces a AppCreateResponse", %{conn: conn} do
+ api_spec = ApiSpec.spec()
+ app_attrs = build(:oauth_app)
+
+ json =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post(
+ "/api/v1/apps",
+ Jason.encode!(%{
+ client_name: app_attrs.client_name,
+ redirect_uris: app_attrs.redirect_uris
+ })
+ )
+ |> json_response(200)
+
+ assert_schema(json, "AppCreateResponse", api_spec)
+ end
+end
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index a9fa0ce48..a450a732c 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -794,7 +794,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "Account registration via Application", %{conn: conn} do
conn =
- post(conn, "/api/v1/apps", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/apps", %{
client_name: "client_name",
redirect_uris: "urn:ietf:wg:oauth:2.0:oob",
scopes: "read, write, follow"
diff --git a/test/web/mastodon_api/controllers/app_controller_test.exs b/test/web/mastodon_api/controllers/app_controller_test.exs
index 77d234d67..e7b11d14e 100644
--- a/test/web/mastodon_api/controllers/app_controller_test.exs
+++ b/test/web/mastodon_api/controllers/app_controller_test.exs
@@ -16,8 +16,7 @@ defmodule Pleroma.Web.MastodonAPI.AppControllerTest do
conn =
conn
- |> assign(:user, token.user)
- |> assign(:token, token)
+ |> put_req_header("authorization", "Bearer #{token.token}")
|> get("/api/v1/apps/verify_credentials")
app = Repo.preload(token, :app).app
@@ -37,6 +36,7 @@ defmodule Pleroma.Web.MastodonAPI.AppControllerTest do
conn =
conn
+ |> put_req_header("content-type", "application/json")
|> assign(:user, user)
|> post("/api/v1/apps", %{
client_name: app_attrs.client_name,
--
cgit v1.2.3
From aa78325117c879ecb7ec76383c239078275adbd9 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Thu, 2 Apr 2020 19:23:30 +0300
Subject: [#2323] Fixed a typo causing /accounts/relationships to render
default relationships. Improved the tests.
---
test/web/mastodon_api/views/account_view_test.exs | 3 +++
1 file changed, 3 insertions(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index 8d00e3c21..4435f69ff 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -209,6 +209,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
relationships_opt = UserRelationship.view_relationships_option(user, [other_user])
opts = Map.put(opts, :relationships, relationships_opt)
assert expected_result == AccountView.render("relationship.json", opts)
+
+ assert [expected_result] ==
+ AccountView.render("relationships.json", %{user: user, targets: [other_user]})
end
@blank_response %{
--
cgit v1.2.3
From fc81e5a49c34224e07e85f490a30f92db0835d45 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Mon, 6 Apr 2020 10:20:44 +0300
Subject: Enforcement of OAuth scopes check for authenticated API endpoints,
:skip_plug plug to mark a plug explicitly skipped (disabled).
---
.../controllers/suggestion_controller_test.exs | 26 ----------------------
.../controllers/pleroma_api_controller_test.exs | 2 +-
2 files changed, 1 insertion(+), 27 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/suggestion_controller_test.exs b/test/web/mastodon_api/controllers/suggestion_controller_test.exs
index c697a39f8..8d0e70db8 100644
--- a/test/web/mastodon_api/controllers/suggestion_controller_test.exs
+++ b/test/web/mastodon_api/controllers/suggestion_controller_test.exs
@@ -7,34 +7,8 @@ defmodule Pleroma.Web.MastodonAPI.SuggestionControllerTest do
alias Pleroma.Config
- import Pleroma.Factory
- import Tesla.Mock
-
setup do: oauth_access(["read"])
- setup %{user: user} do
- other_user = insert(:user)
- host = Config.get([Pleroma.Web.Endpoint, :url, :host])
- url500 = "http://test500?#{host}{user.nickname}"
- url200 = "http://test200?#{host}{user.nickname}"
-
- mock(fn
- %{method: :get, url: ^url500} ->
- %Tesla.Env{status: 500, body: "bad request"}
-
- %{method: :get, url: ^url200} ->
- %Tesla.Env{
- status: 200,
- body:
- ~s([{"acct":"yj455","avatar":"https://social.heldscal.la/avatar/201.jpeg","avatar_static":"https://social.heldscal.la/avatar/s/201.jpeg"}, {"acct":"#{
- other_user.ap_id
- }","avatar":"https://social.heldscal.la/avatar/202.jpeg","avatar_static":"https://social.heldscal.la/avatar/s/202.jpeg"}])
- }
- end)
-
- [other_user: other_user]
- end
-
test "returns empty result", %{conn: conn} do
res =
conn
diff --git a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
index 32250f06f..8f0cbe9b2 100644
--- a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
@@ -203,7 +203,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
test "POST /api/v1/pleroma/conversations/read" do
user = insert(:user)
- %{user: other_user, conn: conn} = oauth_access(["write:notifications"])
+ %{user: other_user, conn: conn} = oauth_access(["write:conversations"])
{:ok, _activity} =
CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}", "visibility" => "direct"})
--
cgit v1.2.3
From b59ac37b2c09d5dc80b59bd3a2aea36989bee713 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Mon, 6 Apr 2020 10:45:25 +0300
Subject: tests for emoji mix task
---
test/fixtures/emoji/packs/blank.png.zip | Bin 0 -> 284 bytes
test/fixtures/emoji/packs/default-manifest.json | 10 ++
test/fixtures/emoji/packs/finmoji.json | 3 +
test/fixtures/emoji/packs/manifest.json | 10 ++
test/tasks/emoji_test.exs | 226 ++++++++++++++++++++++++
5 files changed, 249 insertions(+)
create mode 100644 test/fixtures/emoji/packs/blank.png.zip
create mode 100644 test/fixtures/emoji/packs/default-manifest.json
create mode 100644 test/fixtures/emoji/packs/finmoji.json
create mode 100644 test/fixtures/emoji/packs/manifest.json
create mode 100644 test/tasks/emoji_test.exs
(limited to 'test')
diff --git a/test/fixtures/emoji/packs/blank.png.zip b/test/fixtures/emoji/packs/blank.png.zip
new file mode 100644
index 000000000..651daf127
Binary files /dev/null and b/test/fixtures/emoji/packs/blank.png.zip differ
diff --git a/test/fixtures/emoji/packs/default-manifest.json b/test/fixtures/emoji/packs/default-manifest.json
new file mode 100644
index 000000000..c8433808d
--- /dev/null
+++ b/test/fixtures/emoji/packs/default-manifest.json
@@ -0,0 +1,10 @@
+{
+ "finmoji": {
+ "license": "CC BY-NC-ND 4.0",
+ "homepage": "https://finland.fi/emoji/",
+ "description": "Finland is the first country in the world to publish its own set of country themed emojis. The Finland emoji collection contains 56 tongue-in-cheek emotions, which were created to explain some hard-to-describe Finnish emotions, Finnish words and customs.",
+ "src": "https://finland.fi/wp-content/uploads/2017/06/finland-emojis.zip",
+ "src_sha256": "384025A1AC6314473863A11AC7AB38A12C01B851A3F82359B89B4D4211D3291D",
+ "files": "finmoji.json"
+ }
+}
\ No newline at end of file
diff --git a/test/fixtures/emoji/packs/finmoji.json b/test/fixtures/emoji/packs/finmoji.json
new file mode 100644
index 000000000..279770998
--- /dev/null
+++ b/test/fixtures/emoji/packs/finmoji.json
@@ -0,0 +1,3 @@
+{
+ "blank": "blank.png"
+}
\ No newline at end of file
diff --git a/test/fixtures/emoji/packs/manifest.json b/test/fixtures/emoji/packs/manifest.json
new file mode 100644
index 000000000..2d51a459b
--- /dev/null
+++ b/test/fixtures/emoji/packs/manifest.json
@@ -0,0 +1,10 @@
+{
+ "blobs.gg": {
+ "src_sha256": "3a12f3a181678d5b3584a62095411b0d60a335118135910d879920f8ade5a57f",
+ "src": "https://git.pleroma.social/pleroma/emoji-index/raw/master/packs/blobs_gg.zip",
+ "license": "Apache 2.0",
+ "homepage": "https://blobs.gg",
+ "files": "blobs_gg.json",
+ "description": "Blob Emoji from blobs.gg repacked as apng"
+ }
+}
\ No newline at end of file
diff --git a/test/tasks/emoji_test.exs b/test/tasks/emoji_test.exs
new file mode 100644
index 000000000..f2930652a
--- /dev/null
+++ b/test/tasks/emoji_test.exs
@@ -0,0 +1,226 @@
+defmodule Mix.Tasks.Pleroma.EmojiTest do
+ use ExUnit.Case, async: true
+
+ import ExUnit.CaptureIO
+ import Tesla.Mock
+
+ alias Mix.Tasks.Pleroma.Emoji
+
+ describe "ls-packs" do
+ test "with default manifest as url" do
+ mock(fn
+ %{
+ method: :get,
+ url: "https://git.pleroma.social/pleroma/emoji-index/raw/master/index.json"
+ } ->
+ %Tesla.Env{
+ status: 200,
+ body: File.read!("test/fixtures/emoji/packs/default-manifest.json")
+ }
+ end)
+
+ capture_io(fn -> Emoji.run(["ls-packs"]) end) =~
+ "https://finland.fi/wp-content/uploads/2017/06/finland-emojis.zip"
+ end
+
+ test "with passed manifest as file" do
+ capture_io(fn ->
+ Emoji.run(["ls-packs", "-m", "test/fixtures/emoji/packs/manifest.json"])
+ end) =~ "https://git.pleroma.social/pleroma/emoji-index/raw/master/packs/blobs_gg.zip"
+ end
+ end
+
+ describe "get-packs" do
+ test "download pack from default manifest" do
+ mock(fn
+ %{
+ method: :get,
+ url: "https://git.pleroma.social/pleroma/emoji-index/raw/master/index.json"
+ } ->
+ %Tesla.Env{
+ status: 200,
+ body: File.read!("test/fixtures/emoji/packs/default-manifest.json")
+ }
+
+ %{
+ method: :get,
+ url: "https://finland.fi/wp-content/uploads/2017/06/finland-emojis.zip"
+ } ->
+ %Tesla.Env{
+ status: 200,
+ body: File.read!("test/fixtures/emoji/packs/blank.png.zip")
+ }
+
+ %{
+ method: :get,
+ url: "https://git.pleroma.social/pleroma/emoji-index/raw/master/finmoji.json"
+ } ->
+ %Tesla.Env{
+ status: 200,
+ body: File.read!("test/fixtures/emoji/packs/finmoji.json")
+ }
+ end)
+
+ assert capture_io(fn -> Emoji.run(["get-packs", "finmoji"]) end) =~ "Writing pack.json for"
+
+ emoji_path =
+ Path.join(
+ Pleroma.Config.get!([:instance, :static_dir]),
+ "emoji"
+ )
+
+ assert File.exists?(Path.join([emoji_path, "finmoji", "pack.json"]))
+ on_exit(fn -> File.rm_rf!("test/instance_static/emoji/finmoji") end)
+ end
+
+ test "pack not found" do
+ mock(fn
+ %{
+ method: :get,
+ url: "https://git.pleroma.social/pleroma/emoji-index/raw/master/index.json"
+ } ->
+ %Tesla.Env{
+ status: 200,
+ body: File.read!("test/fixtures/emoji/packs/default-manifest.json")
+ }
+ end)
+
+ assert capture_io(fn -> Emoji.run(["get-packs", "not_found"]) end) =~
+ "No pack named \"not_found\" found"
+ end
+
+ test "raise on bad sha256" do
+ mock(fn
+ %{
+ method: :get,
+ url: "https://git.pleroma.social/pleroma/emoji-index/raw/master/packs/blobs_gg.zip"
+ } ->
+ %Tesla.Env{
+ status: 200,
+ body: File.read!("test/fixtures/emoji/packs/blank.png.zip")
+ }
+ end)
+
+ assert_raise RuntimeError, ~r/^Bad SHA256 for blobs.gg/, fn ->
+ capture_io(fn ->
+ Emoji.run(["get-packs", "blobs.gg", "-m", "test/fixtures/emoji/packs/manifest.json"])
+ end)
+ end
+ end
+ end
+
+ describe "gen-pack" do
+ setup do
+ url = "https://finland.fi/wp-content/uploads/2017/06/finland-emojis.zip"
+
+ mock(fn %{
+ method: :get,
+ url: ^url
+ } ->
+ %Tesla.Env{status: 200, body: File.read!("test/fixtures/emoji/packs/blank.png.zip")}
+ end)
+
+ {:ok, url: url}
+ end
+
+ test "with default extensions", %{url: url} do
+ name = "pack1"
+ pack_json = "#{name}.json"
+ files_json = "#{name}_file.json"
+ refute File.exists?(pack_json)
+ refute File.exists?(files_json)
+
+ captured =
+ capture_io(fn ->
+ Emoji.run([
+ "gen-pack",
+ url,
+ "--name",
+ name,
+ "--license",
+ "license",
+ "--homepage",
+ "homepage",
+ "--description",
+ "description",
+ "--files",
+ files_json,
+ "--extensions",
+ ".png .gif"
+ ])
+ end)
+
+ assert captured =~ "#{pack_json} has been created with the pack1 pack"
+ assert captured =~ "Using .png .gif extensions"
+
+ assert File.exists?(pack_json)
+ assert File.exists?(files_json)
+
+ on_exit(fn ->
+ File.rm_rf!(pack_json)
+ File.rm_rf!(files_json)
+ end)
+ end
+
+ test "with custom extensions and update existing files", %{url: url} do
+ name = "pack2"
+ pack_json = "#{name}.json"
+ files_json = "#{name}_file.json"
+ refute File.exists?(pack_json)
+ refute File.exists?(files_json)
+
+ captured =
+ capture_io(fn ->
+ Emoji.run([
+ "gen-pack",
+ url,
+ "--name",
+ name,
+ "--license",
+ "license",
+ "--homepage",
+ "homepage",
+ "--description",
+ "description",
+ "--files",
+ files_json,
+ "--extensions",
+ " .png .gif .jpeg "
+ ])
+ end)
+
+ assert captured =~ "#{pack_json} has been created with the pack2 pack"
+ assert captured =~ "Using .png .gif .jpeg extensions"
+
+ assert File.exists?(pack_json)
+ assert File.exists?(files_json)
+
+ captured =
+ capture_io(fn ->
+ Emoji.run([
+ "gen-pack",
+ url,
+ "--name",
+ name,
+ "--license",
+ "license",
+ "--homepage",
+ "homepage",
+ "--description",
+ "description",
+ "--files",
+ files_json,
+ "--extensions",
+ " .png .gif .jpeg "
+ ])
+ end)
+
+ assert captured =~ "#{pack_json} has been updated with the pack2 pack"
+
+ on_exit(fn ->
+ File.rm_rf!(pack_json)
+ File.rm_rf!(files_json)
+ end)
+ end
+ end
+end
--
cgit v1.2.3
From a43e05591639132ce121d2e14258944a53004438 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Mon, 6 Apr 2020 14:27:20 +0300
Subject: using another fn for file deletion
---
test/tasks/emoji_test.exs | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/tasks/emoji_test.exs b/test/tasks/emoji_test.exs
index f2930652a..f5de3ef0e 100644
--- a/test/tasks/emoji_test.exs
+++ b/test/tasks/emoji_test.exs
@@ -157,8 +157,8 @@ defmodule Mix.Tasks.Pleroma.EmojiTest do
assert File.exists?(files_json)
on_exit(fn ->
- File.rm_rf!(pack_json)
- File.rm_rf!(files_json)
+ File.rm!(pack_json)
+ File.rm!(files_json)
end)
end
@@ -218,8 +218,8 @@ defmodule Mix.Tasks.Pleroma.EmojiTest do
assert captured =~ "#{pack_json} has been updated with the pack2 pack"
on_exit(fn ->
- File.rm_rf!(pack_json)
- File.rm_rf!(files_json)
+ File.rm!(pack_json)
+ File.rm!(files_json)
end)
end
end
--
cgit v1.2.3
From 06471940e0cb917bb362cbcb9d872ab1336a04cf Mon Sep 17 00:00:00 2001
From: kPherox
Date: Tue, 7 Apr 2020 08:44:53 +0000
Subject: Apply suggestion to
test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
---
.../controllers/account_controller/update_credentials_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
index 8687d7995..d78fbc5a1 100644
--- a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
@@ -298,7 +298,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
]
end
- test "update fields by urlencoded", %{conn: conn} do
+ test "update fields via x-www-form-urlencoded", %{conn: conn} do
fields =
[
"fields_attributes[1][name]=link",
--
cgit v1.2.3
From f35c28bf070014dfba4b988bfc47fbf93baef81f Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Wed, 8 Apr 2020 21:26:22 +0300
Subject: [#1559] Added / fixed tests for follow / follow_request
notifications.
---
test/notification_test.exs | 80 ++++++++++++++++++++++++++++++++++++++++------
1 file changed, 70 insertions(+), 10 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 837a9dacd..0877aaaaf 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -11,8 +11,10 @@ defmodule Pleroma.NotificationTest do
alias Pleroma.Notification
alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
+ alias Pleroma.FollowingRelationship
alias Pleroma.Web.ActivityPub.Transmogrifier
alias Pleroma.Web.CommonAPI
+ alias Pleroma.Web.MastodonAPI.NotificationView
alias Pleroma.Web.Push
alias Pleroma.Web.Streamer
@@ -272,16 +274,6 @@ defmodule Pleroma.NotificationTest do
refute Notification.create_notification(activity, author)
end
- test "it doesn't create a notification for follow-unfollow-follow chains" do
- user = insert(:user)
- followed_user = insert(:user)
- {:ok, _, _, activity} = CommonAPI.follow(user, followed_user)
- Notification.create_notification(activity, followed_user)
- CommonAPI.unfollow(user, followed_user)
- {:ok, _, _, activity_dupe} = CommonAPI.follow(user, followed_user)
- refute Notification.create_notification(activity_dupe, followed_user)
- end
-
test "it doesn't create duplicate notifications for follow+subscribed users" do
user = insert(:user)
subscriber = insert(:user)
@@ -304,6 +296,74 @@ defmodule Pleroma.NotificationTest do
end
end
+ describe "follow / follow_request notifications" do
+ test "it creates `follow` notification for approved Follow activity" do
+ user = insert(:user)
+ followed_user = insert(:user, locked: false)
+
+ {:ok, _, _, _activity} = CommonAPI.follow(user, followed_user)
+ assert FollowingRelationship.following?(user, followed_user)
+ assert [notification] = Notification.for_user(followed_user)
+
+ assert %{type: "follow"} =
+ NotificationView.render("show.json", %{
+ notification: notification,
+ for: followed_user
+ })
+ end
+
+ test "if `follow_request` notifications are enabled, " <>
+ "it creates `follow_request` notification for pending Follow activity" do
+ clear_config([:notifications, :enable_follow_request_notifications], true)
+ user = insert(:user)
+ followed_user = insert(:user, locked: true)
+
+ {:ok, _, _, _activity} = CommonAPI.follow(user, followed_user)
+ refute FollowingRelationship.following?(user, followed_user)
+ assert [notification] = Notification.for_user(followed_user)
+
+ render_opts = %{notification: notification, for: followed_user}
+ assert %{type: "follow_request"} = NotificationView.render("show.json", render_opts)
+
+ # After request is accepted, the same notification is rendered with type "follow":
+ assert {:ok, _} = CommonAPI.accept_follow_request(user, followed_user)
+
+ notification_id = notification.id
+ assert [%{id: ^notification_id}] = Notification.for_user(followed_user)
+ assert %{type: "follow"} = NotificationView.render("show.json", render_opts)
+ end
+
+ test "if `follow_request` notifications are disabled, " <>
+ "it does NOT create `follow*` notification for pending Follow activity" do
+ clear_config([:notifications, :enable_follow_request_notifications], false)
+ user = insert(:user)
+ followed_user = insert(:user, locked: true)
+
+ {:ok, _, _, _activity} = CommonAPI.follow(user, followed_user)
+ refute FollowingRelationship.following?(user, followed_user)
+ assert [] = Notification.for_user(followed_user)
+
+ # After request is accepted, no new notifications are generated:
+ assert {:ok, _} = CommonAPI.accept_follow_request(user, followed_user)
+ assert [] = Notification.for_user(followed_user)
+ end
+
+ test "it doesn't create a notification for follow-unfollow-follow chains" do
+ user = insert(:user)
+ followed_user = insert(:user, locked: false)
+
+ {:ok, _, _, _activity} = CommonAPI.follow(user, followed_user)
+ assert FollowingRelationship.following?(user, followed_user)
+ assert [notification] = Notification.for_user(followed_user)
+
+ CommonAPI.unfollow(user, followed_user)
+ {:ok, _, _, _activity_dupe} = CommonAPI.follow(user, followed_user)
+
+ notification_id = notification.id
+ assert [%{id: ^notification_id}] = Notification.for_user(followed_user)
+ end
+ end
+
describe "get notification" do
test "it gets a notification that belongs to the user" do
user = insert(:user)
--
cgit v1.2.3
From 3965772b261e78669441a5bf3a597f1a69f78a7f Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Wed, 8 Apr 2020 21:33:37 +0300
Subject: [#1559] Minor change (analysis).
---
test/notification_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 0877aaaaf..a7f53e319 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -8,10 +8,10 @@ defmodule Pleroma.NotificationTest do
import Pleroma.Factory
import Mock
+ alias Pleroma.FollowingRelationship
alias Pleroma.Notification
alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
- alias Pleroma.FollowingRelationship
alias Pleroma.Web.ActivityPub.Transmogrifier
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.MastodonAPI.NotificationView
--
cgit v1.2.3
From d067eaa7b3bb76e7fc5ae019d6e00510b657171d Mon Sep 17 00:00:00 2001
From: rinpatch
Date: Wed, 8 Apr 2020 22:58:31 +0300
Subject: formatter.ex: Use Phoenix.HTML for mention/hashtag generation
Unlike concatenating strings, this makes sure everything is escaped.
Tests had to be changed because Phoenix.HTML runs attributes through
Enum.sort before generation for whatever reason.
---
test/formatter_test.exs | 24 +++++++++-------------
test/user_test.exs | 2 +-
test/web/common_api/common_api_utils_test.exs | 6 +++---
.../account_controller/update_credentials_test.exs | 4 ++--
.../controllers/notification_controller_test.exs | 4 ++--
test/web/twitter_api/twitter_api_test.exs | 2 +-
6 files changed, 19 insertions(+), 23 deletions(-)
(limited to 'test')
diff --git a/test/formatter_test.exs b/test/formatter_test.exs
index cf8441cf6..93fd8eab7 100644
--- a/test/formatter_test.exs
+++ b/test/formatter_test.exs
@@ -150,13 +150,13 @@ defmodule Pleroma.FormatterTest do
assert length(mentions) == 3
expected_text =
- ~s(@gsimg According to @gsimg According to @archa_eme_, that is @daggsy. Also hello @archa_eme_, that is @daggsy. Also hello @archaeme)
+ }" href="#{archaeme_remote.ap_id}" rel="ugc">@archaeme)
assert expected_text == text
end
@@ -171,7 +171,7 @@ defmodule Pleroma.FormatterTest do
assert length(mentions) == 1
expected_text =
- ~s(@mike test)
@@ -187,7 +187,7 @@ defmodule Pleroma.FormatterTest do
assert length(mentions) == 1
expected_text =
- ~s(@o hi)
+ ~s(@o hi)
assert expected_text == text
end
@@ -209,17 +209,13 @@ defmodule Pleroma.FormatterTest do
assert mentions == [{"@#{user.nickname}", user}, {"@#{other_user.nickname}", other_user}]
assert expected_text ==
- ~s(@#{user.nickname} @#{user.nickname} @#{
- other_user.nickname
- } hey dudes i hate @#{other_user.nickname} hey dudes i hate @#{
- third_user.nickname
- })
+ }" href="#{third_user.ap_id}" rel="ugc">@#{third_user.nickname})
end
test "given the 'safe_mention' option, it will still work without any mention" do
diff --git a/test/user_test.exs b/test/user_test.exs
index 0479f294d..d39787f35 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -1404,7 +1404,7 @@ defmodule Pleroma.UserTest do
bio = "A.k.a. @nick@domain.com"
expected_text =
- ~s(A.k.a. @nick@domain.com)
diff --git a/test/web/common_api/common_api_utils_test.exs b/test/web/common_api/common_api_utils_test.exs
index d383d1714..98cf02d49 100644
--- a/test/web/common_api/common_api_utils_test.exs
+++ b/test/web/common_api/common_api_utils_test.exs
@@ -159,11 +159,11 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
{output, _, _} = Utils.format_input(text, "text/markdown")
assert output ==
- ~s(hello world
another @user__test and @user__test and @user__test google.com paragraph
)
+ }" href="http://foo.com/user__test" rel="ugc">@user__test google.com paragraph
)
end
end
diff --git a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
index d78fbc5a1..2d256f63c 100644
--- a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
@@ -82,9 +82,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
assert user_data = json_response(conn, 200)
assert user_data["note"] ==
- ~s(I drink #cofe with #cofe with @#{user2.nickname}
suya..)
+ }" href="#{user2.ap_id}" rel="ugc">@#{user2.nickname}
suya..)
end
test "updates the user's locking status", %{conn: conn} do
diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs
index 344eabb4a..6f1fab069 100644
--- a/test/web/mastodon_api/controllers/notification_controller_test.exs
+++ b/test/web/mastodon_api/controllers/notification_controller_test.exs
@@ -26,7 +26,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
|> get("/api/v1/notifications")
expected_response =
- "hi @#{user.nickname}"
@@ -45,7 +45,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
conn = get(conn, "/api/v1/notifications/#{notification.id}")
expected_response =
- "hi @#{user.nickname}"
diff --git a/test/web/twitter_api/twitter_api_test.exs b/test/web/twitter_api/twitter_api_test.exs
index 92f9aa0f5..f6e13b661 100644
--- a/test/web/twitter_api/twitter_api_test.exs
+++ b/test/web/twitter_api/twitter_api_test.exs
@@ -109,7 +109,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
{:ok, user2} = TwitterAPI.register_user(data2)
expected_text =
- ~s(@john test)
--
cgit v1.2.3
From 365c34a7a96a9cbd5acb30eb6eedf195eeaff131 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Thu, 9 Apr 2020 10:17:44 +0000
Subject: Apply suggestion to test/web/admin_api/admin_api_controller_test.exs
---
test/web/admin_api/admin_api_controller_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 32fe69d19..afd894269 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -671,7 +671,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
assert json_response(conn, :bad_request) ==
- "To send invites you need set `invites_enabled` option to true."
+ "To send invites you need to set the `invites_enabled` option to true."
end
test "it returns 500 if `registrations_open` is enabled", %{conn: conn} do
--
cgit v1.2.3
From 9795ff5b016e74c0e7b94ac2ea28023208d1f8ee Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Thu, 9 Apr 2020 10:17:50 +0000
Subject: Apply suggestion to test/web/admin_api/admin_api_controller_test.exs
---
test/web/admin_api/admin_api_controller_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index afd894269..e8d11b88c 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -681,7 +681,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
assert json_response(conn, :bad_request) ==
- "To send invites you need set `registrations_open` option to false."
+ "To send invites you need to set the `registrations_open` option to false."
end
end
--
cgit v1.2.3
From d545b883eb3c5b79b89a49ccaf9256c31b401145 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 9 Apr 2020 17:08:43 +0400
Subject: Add `/api/v1/notifications/:id/dismiss` endpoint
---
.../controllers/notification_controller_test.exs | 18 +++++++++++++++++-
1 file changed, 17 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs
index 6f1fab069..1557937d8 100644
--- a/test/web/mastodon_api/controllers/notification_controller_test.exs
+++ b/test/web/mastodon_api/controllers/notification_controller_test.exs
@@ -53,7 +53,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
assert response == expected_response
end
- test "dismissing a single notification" do
+ test "dismissing a single notification (deprecated endpoint)" do
%{user: user, conn: conn} = oauth_access(["write:notifications"])
other_user = insert(:user)
@@ -69,6 +69,22 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
assert %{} = json_response(conn, 200)
end
+ test "dismissing a single notification" do
+ %{user: user, conn: conn} = oauth_access(["write:notifications"])
+ other_user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
+
+ {:ok, [notification]} = Notification.create_notifications(activity)
+
+ conn =
+ conn
+ |> assign(:user, user)
+ |> post("/api/v1/notifications/#{notification.id}/dismiss")
+
+ assert %{} = json_response(conn, 200)
+ end
+
test "clearing all notifications" do
%{user: user, conn: conn} = oauth_access(["write:notifications", "read:notifications"])
other_user = insert(:user)
--
cgit v1.2.3
From 19eedb3d0424abb235eec1a51457ed0bf3a0e95d Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Wed, 1 Apr 2020 06:58:48 +0200
Subject: User: Move public_key from source_data to own field
---
test/signature_test.exs | 13 ++++---------
1 file changed, 4 insertions(+), 9 deletions(-)
(limited to 'test')
diff --git a/test/signature_test.exs b/test/signature_test.exs
index 04736d8b9..d5a2a62c4 100644
--- a/test/signature_test.exs
+++ b/test/signature_test.exs
@@ -19,12 +19,7 @@ defmodule Pleroma.SignatureTest do
@private_key "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEA48qb4v6kqigZutO9Ot0wkp27GIF2LiVaADgxQORZozZR63jH\nTaoOrS3Xhngbgc8SSOhfXET3omzeCLqaLNfXnZ8OXmuhJfJSU6mPUvmZ9QdT332j\nfN/g3iWGhYMf/M9ftCKh96nvFVO/tMruzS9xx7tkrfJjehdxh/3LlJMMImPtwcD7\nkFXwyt1qZTAU6Si4oQAJxRDQXHp1ttLl3Ob829VM7IKkrVmY8TD+JSlV0jtVJPj6\n1J19ytKTx/7UaucYvb9HIiBpkuiy5n/irDqKLVf5QEdZoNCdojOZlKJmTLqHhzKP\n3E9TxsUjhrf4/EqegNc/j982RvOxeu4i40zMQwIDAQABAoIBAQDH5DXjfh21i7b4\ncXJuw0cqget617CDUhemdakTDs9yH+rHPZd3mbGDWuT0hVVuFe4vuGpmJ8c+61X0\nRvugOlBlavxK8xvYlsqTzAmPgKUPljyNtEzQ+gz0I+3mH2jkin2rL3D+SksZZgKm\nfiYMPIQWB2WUF04gB46DDb2mRVuymGHyBOQjIx3WC0KW2mzfoFUFRlZEF+Nt8Ilw\nT+g/u0aZ1IWoszbsVFOEdghgZET0HEarum0B2Je/ozcPYtwmU10iBANGMKdLqaP/\nj954BPunrUf6gmlnLZKIKklJj0advx0NA+cL79+zeVB3zexRYSA5o9q0WPhiuTwR\n/aedWHnBAoGBAP0sDWBAM1Y4TRAf8ZI9PcztwLyHPzfEIqzbObJJnx1icUMt7BWi\n+/RMOnhrlPGE1kMhOqSxvXYN3u+eSmWTqai2sSH5Hdw2EqnrISSTnwNUPINX7fHH\njEkgmXQ6ixE48SuBZnb4w1EjdB/BA6/sjL+FNhggOc87tizLTkMXmMtTAoGBAOZV\n+wPuAMBDBXmbmxCuDIjoVmgSlgeRunB1SA8RCPAFAiUo3+/zEgzW2Oz8kgI+xVwM\n33XkLKrWG1Orhpp6Hm57MjIc5MG+zF4/YRDpE/KNG9qU1tiz0UD5hOpIU9pP4bR/\ngxgPxZzvbk4h5BfHWLpjlk8UUpgk6uxqfti48c1RAoGBALBOKDZ6HwYRCSGMjUcg\n3NPEUi84JD8qmFc2B7Tv7h2he2ykIz9iFAGpwCIyETQsJKX1Ewi0OlNnD3RhEEAy\nl7jFGQ+mkzPSeCbadmcpYlgIJmf1KN/x7fDTAepeBpCEzfZVE80QKbxsaybd3Dp8\nCfwpwWUFtBxr4c7J+gNhAGe/AoGAPn8ZyqkrPv9wXtyfqFjxQbx4pWhVmNwrkBPi\nZ2Qh3q4dNOPwTvTO8vjghvzIyR8rAZzkjOJKVFgftgYWUZfM5gE7T2mTkBYq8W+U\n8LetF+S9qAM2gDnaDx0kuUTCq7t87DKk6URuQ/SbI0wCzYjjRD99KxvChVGPBHKo\n1DjqMuECgYEAgJGNm7/lJCS2wk81whfy/ttKGsEIkyhPFYQmdGzSYC5aDc2gp1R3\nxtOkYEvdjfaLfDGEa4UX8CHHF+w3t9u8hBtcdhMH6GYb9iv6z0VBTt4A/11HUR49\n3Z7TQ18Iyh3jAUCzFV9IJlLIExq5Y7P4B3ojWFBN607sDCt8BMPbDYs=\n-----END RSA PRIVATE KEY-----"
- @public_key %{
- "id" => "https://mastodon.social/users/lambadalambda#main-key",
- "owner" => "https://mastodon.social/users/lambadalambda",
- "publicKeyPem" =>
- "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw0P/Tq4gb4G/QVuMGbJo\nC/AfMNcv+m7NfrlOwkVzcU47jgESuYI4UtJayissCdBycHUnfVUd9qol+eznSODz\nCJhfJloqEIC+aSnuEPGA0POtWad6DU0E6/Ho5zQn5WAWUwbRQqowbrsm/GHo2+3v\neR5jGenwA6sYhINg/c3QQbksyV0uJ20Umyx88w8+TJuv53twOfmyDWuYNoQ3y5cc\nHKOZcLHxYOhvwg3PFaGfFHMFiNmF40dTXt9K96r7sbzc44iLD+VphbMPJEjkMuf8\nPGEFOBzy8pm3wJZw2v32RNW2VESwMYyqDzwHXGSq1a73cS7hEnc79gXlELsK04L9\nQQIDAQAB\n-----END PUBLIC KEY-----\n"
- }
+ @public_key "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw0P/Tq4gb4G/QVuMGbJo\nC/AfMNcv+m7NfrlOwkVzcU47jgESuYI4UtJayissCdBycHUnfVUd9qol+eznSODz\nCJhfJloqEIC+aSnuEPGA0POtWad6DU0E6/Ho5zQn5WAWUwbRQqowbrsm/GHo2+3v\neR5jGenwA6sYhINg/c3QQbksyV0uJ20Umyx88w8+TJuv53twOfmyDWuYNoQ3y5cc\nHKOZcLHxYOhvwg3PFaGfFHMFiNmF40dTXt9K96r7sbzc44iLD+VphbMPJEjkMuf8\nPGEFOBzy8pm3wJZw2v32RNW2VESwMYyqDzwHXGSq1a73cS7hEnc79gXlELsK04L9\nQQIDAQAB\n-----END PUBLIC KEY-----\n"
@rsa_public_key {
:RSAPublicKey,
@@ -42,7 +37,7 @@ defmodule Pleroma.SignatureTest do
test "it returns key" do
expected_result = {:ok, @rsa_public_key}
- user = insert(:user, source_data: %{"publicKey" => @public_key})
+ user = insert(:user, public_key: @public_key)
assert Signature.fetch_public_key(make_fake_conn(user.ap_id)) == expected_result
end
@@ -53,8 +48,8 @@ defmodule Pleroma.SignatureTest do
end) =~ "[error] Could not decode user"
end
- test "it returns error if public key is empty" do
- user = insert(:user, source_data: %{"publicKey" => %{}})
+ test "it returns error if public key is nil" do
+ user = insert(:user, public_key: nil)
assert Signature.fetch_public_key(make_fake_conn(user.ap_id)) == {:error, :error}
end
--
cgit v1.2.3
From 369c03834c5f2638080ff515055723e6c1c716bf Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Wed, 1 Apr 2020 07:15:38 +0200
Subject: formatter: Use user.uri instead of user.source_data.uri
---
test/formatter_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/formatter_test.exs b/test/formatter_test.exs
index 93fd8eab7..bef5a2c28 100644
--- a/test/formatter_test.exs
+++ b/test/formatter_test.exs
@@ -140,7 +140,7 @@ defmodule Pleroma.FormatterTest do
archaeme =
insert(:user,
nickname: "archa_eme_",
- source_data: %{"url" => "https://archeme/@archa_eme_"}
+ uri: "https://archeme/@archa_eme_"
)
archaeme_remote = insert(:user, %{nickname: "archaeme@archae.me"})
--
cgit v1.2.3
From 62656ab259cec1a8585abecf45096b283fa4c60a Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Wed, 1 Apr 2020 07:47:07 +0200
Subject: User: Move inbox & shared_inbox to own fields
---
test/web/activity_pub/publisher_test.exs | 52 +++++++++++---------------------
test/web/federator_test.exs | 4 +--
2 files changed, 19 insertions(+), 37 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/publisher_test.exs b/test/web/activity_pub/publisher_test.exs
index 801da03c1..c2bc38d52 100644
--- a/test/web/activity_pub/publisher_test.exs
+++ b/test/web/activity_pub/publisher_test.exs
@@ -48,10 +48,7 @@ defmodule Pleroma.Web.ActivityPub.PublisherTest do
describe "determine_inbox/2" do
test "it returns sharedInbox for messages involving as:Public in to" do
- user =
- insert(:user, %{
- source_data: %{"endpoints" => %{"sharedInbox" => "http://example.com/inbox"}}
- })
+ user = insert(:user, %{shared_inbox: "http://example.com/inbox"})
activity = %Activity{
data: %{"to" => [@as_public], "cc" => [user.follower_address]}
@@ -61,10 +58,7 @@ defmodule Pleroma.Web.ActivityPub.PublisherTest do
end
test "it returns sharedInbox for messages involving as:Public in cc" do
- user =
- insert(:user, %{
- source_data: %{"endpoints" => %{"sharedInbox" => "http://example.com/inbox"}}
- })
+ user = insert(:user, %{shared_inbox: "http://example.com/inbox"})
activity = %Activity{
data: %{"cc" => [@as_public], "to" => [user.follower_address]}
@@ -74,11 +68,7 @@ defmodule Pleroma.Web.ActivityPub.PublisherTest do
end
test "it returns sharedInbox for messages involving multiple recipients in to" do
- user =
- insert(:user, %{
- source_data: %{"endpoints" => %{"sharedInbox" => "http://example.com/inbox"}}
- })
-
+ user = insert(:user, %{shared_inbox: "http://example.com/inbox"})
user_two = insert(:user)
user_three = insert(:user)
@@ -90,11 +80,7 @@ defmodule Pleroma.Web.ActivityPub.PublisherTest do
end
test "it returns sharedInbox for messages involving multiple recipients in cc" do
- user =
- insert(:user, %{
- source_data: %{"endpoints" => %{"sharedInbox" => "http://example.com/inbox"}}
- })
-
+ user = insert(:user, %{shared_inbox: "http://example.com/inbox"})
user_two = insert(:user)
user_three = insert(:user)
@@ -107,12 +93,10 @@ defmodule Pleroma.Web.ActivityPub.PublisherTest do
test "it returns sharedInbox for messages involving multiple recipients in total" do
user =
- insert(:user,
- source_data: %{
- "inbox" => "http://example.com/personal-inbox",
- "endpoints" => %{"sharedInbox" => "http://example.com/inbox"}
- }
- )
+ insert(:user, %{
+ shared_inbox: "http://example.com/inbox",
+ inbox: "http://example.com/personal-inbox"
+ })
user_two = insert(:user)
@@ -125,12 +109,10 @@ defmodule Pleroma.Web.ActivityPub.PublisherTest do
test "it returns inbox for messages involving single recipients in total" do
user =
- insert(:user,
- source_data: %{
- "inbox" => "http://example.com/personal-inbox",
- "endpoints" => %{"sharedInbox" => "http://example.com/inbox"}
- }
- )
+ insert(:user, %{
+ shared_inbox: "http://example.com/inbox",
+ inbox: "http://example.com/personal-inbox"
+ })
activity = %Activity{
data: %{"to" => [user.ap_id], "cc" => []}
@@ -258,11 +240,11 @@ defmodule Pleroma.Web.ActivityPub.PublisherTest do
[:passthrough],
[] do
follower =
- insert(:user,
+ insert(:user, %{
local: false,
- source_data: %{"inbox" => "https://domain.com/users/nick1/inbox"},
+ inbox: "https://domain.com/users/nick1/inbox",
ap_enabled: true
- )
+ })
actor = insert(:user, follower_address: follower.ap_id)
user = insert(:user)
@@ -295,14 +277,14 @@ defmodule Pleroma.Web.ActivityPub.PublisherTest do
fetcher =
insert(:user,
local: false,
- source_data: %{"inbox" => "https://domain.com/users/nick1/inbox"},
+ inbox: "https://domain.com/users/nick1/inbox",
ap_enabled: true
)
another_fetcher =
insert(:user,
local: false,
- source_data: %{"inbox" => "https://domain2.com/users/nick1/inbox"},
+ inbox: "https://domain2.com/users/nick1/inbox",
ap_enabled: true
)
diff --git a/test/web/federator_test.exs b/test/web/federator_test.exs
index da844c24c..59e53bb03 100644
--- a/test/web/federator_test.exs
+++ b/test/web/federator_test.exs
@@ -78,7 +78,7 @@ defmodule Pleroma.Web.FederatorTest do
local: false,
nickname: "nick1@domain.com",
ap_id: "https://domain.com/users/nick1",
- source_data: %{"inbox" => inbox1},
+ inbox: inbox1,
ap_enabled: true
})
@@ -86,7 +86,7 @@ defmodule Pleroma.Web.FederatorTest do
local: false,
nickname: "nick2@domain2.com",
ap_id: "https://domain2.com/users/nick2",
- source_data: %{"inbox" => inbox2},
+ inbox: inbox2,
ap_enabled: true
})
--
cgit v1.2.3
From 9172d719ccbf84d55236007d329fc880db69fe42 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Fri, 3 Apr 2020 13:03:32 +0200
Subject: profile emojis in User.emoji instead of source_data
---
test/emoji/formatter_test.exs | 24 ++++++-----------------
test/web/activity_pub/transmogrifier_test.exs | 14 +++++++++++++
test/web/activity_pub/views/user_view_test.exs | 2 +-
test/web/common_api/common_api_test.exs | 12 ------------
test/web/common_api/common_api_utils_test.exs | 23 ----------------------
test/web/mastodon_api/views/account_view_test.exs | 16 ++-------------
6 files changed, 23 insertions(+), 68 deletions(-)
(limited to 'test')
diff --git a/test/emoji/formatter_test.exs b/test/emoji/formatter_test.exs
index 3bfee9420..12af6cd8b 100644
--- a/test/emoji/formatter_test.exs
+++ b/test/emoji/formatter_test.exs
@@ -3,7 +3,6 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Emoji.FormatterTest do
- alias Pleroma.Emoji
alias Pleroma.Emoji.Formatter
use Pleroma.DataCase
@@ -32,30 +31,19 @@ defmodule Pleroma.Emoji.FormatterTest do
end
end
- describe "get_emoji" do
+ describe "get_emoji_map" do
test "it returns the emoji used in the text" do
- text = "I love :firefox:"
-
- assert Formatter.get_emoji(text) == [
- {"firefox",
- %Emoji{
- code: "firefox",
- file: "/emoji/Firefox.gif",
- tags: ["Gif", "Fun"],
- safe_code: "firefox",
- safe_file: "/emoji/Firefox.gif"
- }}
- ]
+ assert Formatter.get_emoji_map("I love :firefox:") == %{
+ "firefox" => "http://localhost:4001/emoji/Firefox.gif"
+ }
end
test "it returns a nice empty result when no emojis are present" do
- text = "I love moominamma"
- assert Formatter.get_emoji(text) == []
+ assert Formatter.get_emoji_map("I love moominamma") == %{}
end
test "it doesn't die when text is absent" do
- text = nil
- assert Formatter.get_emoji(text) == []
+ assert Formatter.get_emoji_map(nil) == %{}
end
end
end
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 6dfd823f7..d7f11d1d7 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -2182,4 +2182,18 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
Transmogrifier.set_replies(object.data)["replies"]
end
end
+
+ test "take_emoji_tags/1" do
+ user = insert(:user, %{emoji: %{"firefox" => "https://example.org/firefox.png"}})
+
+ assert Transmogrifier.take_emoji_tags(user) == [
+ %{
+ "icon" => %{"type" => "Image", "url" => "https://example.org/firefox.png"},
+ "id" => "https://example.org/firefox.png",
+ "name" => ":firefox:",
+ "type" => "Emoji",
+ "updated" => "1970-01-01T00:00:00Z"
+ }
+ ]
+ end
end
diff --git a/test/web/activity_pub/views/user_view_test.exs b/test/web/activity_pub/views/user_view_test.exs
index ecb2dc386..20578161b 100644
--- a/test/web/activity_pub/views/user_view_test.exs
+++ b/test/web/activity_pub/views/user_view_test.exs
@@ -38,7 +38,7 @@ defmodule Pleroma.Web.ActivityPub.UserViewTest do
end
test "Renders with emoji tags" do
- user = insert(:user, emoji: [%{"bib" => "/test"}])
+ user = insert(:user, emoji: %{"bib" => "/test"})
assert %{
"tag" => [
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index f46ad0272..5e78c5758 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -97,18 +97,6 @@ defmodule Pleroma.Web.CommonAPITest do
assert Object.normalize(activity).data["emoji"]["firefox"]
end
- test "it adds emoji when updating profiles" do
- user = insert(:user, %{name: ":firefox:"})
-
- {:ok, activity} = CommonAPI.update(user)
- user = User.get_cached_by_ap_id(user.ap_id)
- [firefox] = user.source_data["tag"]
-
- assert firefox["name"] == ":firefox:"
-
- assert Pleroma.Constants.as_public() in activity.recipients
- end
-
describe "posting" do
test "it supports explicit addressing" do
user = insert(:user)
diff --git a/test/web/common_api/common_api_utils_test.exs b/test/web/common_api/common_api_utils_test.exs
index 98cf02d49..b21445fe9 100644
--- a/test/web/common_api/common_api_utils_test.exs
+++ b/test/web/common_api/common_api_utils_test.exs
@@ -7,7 +7,6 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
alias Pleroma.Object
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.CommonAPI.Utils
- alias Pleroma.Web.Endpoint
use Pleroma.DataCase
import ExUnit.CaptureLog
@@ -42,28 +41,6 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
end
end
- test "parses emoji from name and bio" do
- {:ok, user} = UserBuilder.insert(%{name: ":blank:", bio: ":firefox:"})
-
- expected = [
- %{
- "type" => "Emoji",
- "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}/emoji/Firefox.gif"},
- "name" => ":firefox:"
- },
- %{
- "type" => "Emoji",
- "icon" => %{
- "type" => "Image",
- "url" => "#{Endpoint.url()}/emoji/blank.png"
- },
- "name" => ":blank:"
- }
- ]
-
- assert expected == Utils.emoji_from_profile(user)
- end
-
describe "format_input/3" do
test "works for bare text/plain" do
text = "hello world!"
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index 4435f69ff..85fa4f6a2 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -19,16 +19,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
end
test "Represent a user account" do
- source_data = %{
- "tag" => [
- %{
- "type" => "Emoji",
- "icon" => %{"url" => "/file.png"},
- "name" => ":karjalanpiirakka:"
- }
- ]
- }
-
background_image = %{
"url" => [%{"href" => "https://example.com/images/asuka_hospital.png"}]
}
@@ -37,13 +27,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
insert(:user, %{
follower_count: 3,
note_count: 5,
- source_data: source_data,
background: background_image,
nickname: "shp@shitposter.club",
name: ":karjalanpiirakka: shp",
bio:
"valid html. a
b
c
d
f",
- inserted_at: ~N[2017-08-15 15:47:06.597036]
+ inserted_at: ~N[2017-08-15 15:47:06.597036],
+ emoji: %{"karjalanpiirakka" => "/file.png"}
})
expected = %{
@@ -117,7 +107,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
insert(:user, %{
follower_count: 3,
note_count: 5,
- source_data: %{},
actor_type: "Service",
nickname: "shp@shitposter.club",
inserted_at: ~N[2017-08-15 15:47:06.597036]
@@ -311,7 +300,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
insert(:user, %{
follower_count: 0,
note_count: 5,
- source_data: %{},
actor_type: "Service",
nickname: "shp@shitposter.club",
inserted_at: ~N[2017-08-15 15:47:06.597036]
--
cgit v1.2.3
From 3420dec494203b46d37ddc17f7e1235dc908a5b3 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Mon, 6 Apr 2020 10:44:48 +0200
Subject: Remove User.fields/1
---
test/web/activity_pub/transmogrifier_test.exs | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index d7f11d1d7..8ddc75669 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -746,7 +746,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
user = User.get_cached_by_ap_id(activity.actor)
- assert User.fields(user) == [
+ assert user.fields == [
%{"name" => "foo", "value" => "bar"},
%{"name" => "foo1", "value" => "bar1"}
]
@@ -767,7 +767,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
user = User.get_cached_by_ap_id(user.ap_id)
- assert User.fields(user) == [
+ assert user.fields == [
%{"name" => "foo", "value" => "updated"},
%{"name" => "foo1", "value" => "updated"}
]
@@ -785,7 +785,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
user = User.get_cached_by_ap_id(user.ap_id)
- assert User.fields(user) == [
+ assert user.fields == [
%{"name" => "foo", "value" => "updated"},
%{"name" => "foo1", "value" => "updated"}
]
@@ -796,7 +796,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
user = User.get_cached_by_ap_id(user.ap_id)
- assert User.fields(user) == []
+ assert user.fields == []
end
test "it works for incoming update activities which lock the account" do
--
cgit v1.2.3
From e89078ac2a27bb0a833c982dbb5eef63ddea3cc0 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Mon, 6 Apr 2020 10:59:35 +0200
Subject: User: remove source_data
---
test/user_test.exs | 2 +-
test/web/activity_pub/activity_pub_test.exs | 1 -
2 files changed, 1 insertion(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/user_test.exs b/test/user_test.exs
index d39787f35..d35005353 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -581,7 +581,7 @@ defmodule Pleroma.UserTest do
{:ok, user} = User.get_or_fetch_by_ap_id("http://mastodon.example.org/users/admin")
- assert user.source_data["endpoints"]
+ assert user.inbox
refute user.last_refreshed_at == orig_user.last_refreshed_at
end
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 17e7b97de..6410df49b 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -180,7 +180,6 @@ 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.source_data
assert user.ap_enabled
assert user.follower_address == "http://mastodon.example.org/users/admin/followers"
end
--
cgit v1.2.3
From 88b16fdfb7b40877aecae5d45f6f3a1c54362f13 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Sat, 11 Apr 2020 16:01:09 +0300
Subject: [#1364] Disabled notifications on activities from blocked domains.
---
test/notification_test.exs | 15 +++++++++++++++
1 file changed, 15 insertions(+)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 837a9dacd..caa941934 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -609,6 +609,21 @@ defmodule Pleroma.NotificationTest do
assert [other_user] == disabled_receivers
refute other_user in enabled_receivers
end
+
+ test "it returns domain-blocking recipient in disabled recipients list" do
+ blocked_domain = "blocked.domain"
+ user = insert(:user, %{ap_id: "https://#{blocked_domain}/@actor"})
+ other_user = insert(:user)
+
+ {:ok, other_user} = User.block_domain(other_user, blocked_domain)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"})
+
+ {enabled_receivers, disabled_receivers} = Notification.get_notified_from_activity(activity)
+
+ assert [] == enabled_receivers
+ assert [other_user] == disabled_receivers
+ end
end
describe "notification lifecycle" do
--
cgit v1.2.3
From c077ad0b3305e74f5b8d1b9bf38d4f480d76c1a6 Mon Sep 17 00:00:00 2001
From: rinpatch
Date: Sat, 11 Apr 2020 21:44:52 +0300
Subject: Remove User.upgrade_changeset in favor of remote_user_creation
The two changesets had the same purpose, yet some changes were updated
in one, but not the other (`uri`, for example).
Also makes `Transmogrifier.upgrade_user_from_ap_id` be called from
`ActivityPub.make_user_from_ap_id` only when the user is actually
not AP enabled yet.
I did not bother rewriting tests that used `User.insert_or_update`
to use the changeset instead because they seemed to just test the implementation,
rather than behavior.
---
test/user_test.exs | 64 +++-----------------------
test/web/activity_pub/views/user_view_test.exs | 2 +-
2 files changed, 7 insertions(+), 59 deletions(-)
(limited to 'test')
diff --git a/test/user_test.exs b/test/user_test.exs
index d39787f35..5c24955c2 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -609,7 +609,7 @@ defmodule Pleroma.UserTest do
) <> "/followers"
end
- describe "remote user creation changeset" do
+ describe "remote user changeset" do
@valid_remote %{
bio: "hello",
name: "Someone",
@@ -621,28 +621,28 @@ defmodule Pleroma.UserTest do
setup do: clear_config([:instance, :user_name_length])
test "it confirms validity" do
- cs = User.remote_user_creation(@valid_remote)
+ cs = User.remote_user_changeset(@valid_remote)
assert cs.valid?
end
test "it sets the follower_adress" do
- cs = User.remote_user_creation(@valid_remote)
+ cs = User.remote_user_changeset(@valid_remote)
# remote users get a fake local follower address
assert cs.changes.follower_address ==
User.ap_followers(%User{nickname: @valid_remote[:nickname]})
end
test "it enforces the fqn format for nicknames" do
- cs = User.remote_user_creation(%{@valid_remote | nickname: "bla"})
+ cs = User.remote_user_changeset(%{@valid_remote | nickname: "bla"})
assert Ecto.Changeset.get_field(cs, :local) == false
assert cs.changes.avatar
refute cs.valid?
end
test "it has required fields" do
- [:name, :ap_id]
+ [:ap_id]
|> Enum.each(fn field ->
- cs = User.remote_user_creation(Map.delete(@valid_remote, field))
+ cs = User.remote_user_changeset(Map.delete(@valid_remote, field))
refute cs.valid?
end)
end
@@ -1198,58 +1198,6 @@ defmodule Pleroma.UserTest do
assert {:ok, _key} = User.get_public_key_for_ap_id("http://mastodon.example.org/users/admin")
end
- describe "insert or update a user from given data" do
- test "with normal data" do
- user = insert(:user, %{nickname: "nick@name.de"})
- data = %{ap_id: user.ap_id <> "xxx", name: user.name, nickname: user.nickname}
-
- assert {:ok, %User{}} = User.insert_or_update_user(data)
- end
-
- test "with overly long fields" do
- current_max_length = Pleroma.Config.get([:instance, :account_field_value_length], 255)
- user = insert(:user, nickname: "nickname@supergood.domain")
-
- data = %{
- ap_id: user.ap_id,
- name: user.name,
- nickname: user.nickname,
- fields: [
- %{"name" => "myfield", "value" => String.duplicate("h", current_max_length + 1)}
- ]
- }
-
- assert {:ok, %User{}} = User.insert_or_update_user(data)
- end
-
- test "with an overly long bio" do
- current_max_length = Pleroma.Config.get([:instance, :user_bio_length], 5000)
- user = insert(:user, nickname: "nickname@supergood.domain")
-
- data = %{
- ap_id: user.ap_id,
- name: user.name,
- nickname: user.nickname,
- bio: String.duplicate("h", current_max_length + 1)
- }
-
- assert {:ok, %User{}} = User.insert_or_update_user(data)
- end
-
- test "with an overly long display name" do
- current_max_length = Pleroma.Config.get([:instance, :user_name_length], 100)
- user = insert(:user, nickname: "nickname@supergood.domain")
-
- data = %{
- ap_id: user.ap_id,
- name: String.duplicate("h", current_max_length + 1),
- nickname: user.nickname
- }
-
- assert {:ok, %User{}} = User.insert_or_update_user(data)
- end
- end
-
describe "per-user rich-text filtering" do
test "html_filter_policy returns default policies, when rich-text is enabled" do
user = insert(:user)
diff --git a/test/web/activity_pub/views/user_view_test.exs b/test/web/activity_pub/views/user_view_test.exs
index ecb2dc386..514fd97b8 100644
--- a/test/web/activity_pub/views/user_view_test.exs
+++ b/test/web/activity_pub/views/user_view_test.exs
@@ -29,7 +29,7 @@ defmodule Pleroma.Web.ActivityPub.UserViewTest do
{:ok, user} =
insert(:user)
- |> User.upgrade_changeset(%{fields: fields})
+ |> User.update_changeset(%{fields: fields})
|> User.update_and_set_cache()
assert %{
--
cgit v1.2.3
From c556efb761a3e7fc2beb4540d6f58dbfe8e4abfe Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Sun, 12 Apr 2020 21:53:03 +0300
Subject: [#1364] Enabled notifications on followed domain-blocked users'
activities.
---
test/notification_test.exs | 35 ++++++++++++++++++++++++++++++++---
1 file changed, 32 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index caa941934..4e5559bb1 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -610,7 +610,7 @@ defmodule Pleroma.NotificationTest do
refute other_user in enabled_receivers
end
- test "it returns domain-blocking recipient in disabled recipients list" do
+ test "it returns non-following domain-blocking recipient in disabled recipients list" do
blocked_domain = "blocked.domain"
user = insert(:user, %{ap_id: "https://#{blocked_domain}/@actor"})
other_user = insert(:user)
@@ -624,6 +624,22 @@ defmodule Pleroma.NotificationTest do
assert [] == enabled_receivers
assert [other_user] == disabled_receivers
end
+
+ test "it returns following domain-blocking recipient in enabled recipients list" do
+ blocked_domain = "blocked.domain"
+ user = insert(:user, %{ap_id: "https://#{blocked_domain}/@actor"})
+ other_user = insert(:user)
+
+ {:ok, other_user} = User.block_domain(other_user, blocked_domain)
+ {:ok, other_user} = User.follow(other_user, user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"})
+
+ {enabled_receivers, disabled_receivers} = Notification.get_notified_from_activity(activity)
+
+ assert [other_user] == enabled_receivers
+ assert [] == disabled_receivers
+ end
end
describe "notification lifecycle" do
@@ -886,7 +902,7 @@ defmodule Pleroma.NotificationTest do
assert Notification.for_user(user) == []
end
- test "it doesn't return notifications for blocked domain" do
+ test "it doesn't return notifications for domain-blocked non-followed user" do
user = insert(:user)
blocked = insert(:user, ap_id: "http://some-domain.com")
{:ok, user} = User.block_domain(user, "some-domain.com")
@@ -896,6 +912,18 @@ defmodule Pleroma.NotificationTest do
assert Notification.for_user(user) == []
end
+ test "it returns notifications for domain-blocked but followed user" do
+ user = insert(:user)
+ blocked = insert(:user, ap_id: "http://some-domain.com")
+
+ {:ok, user} = User.block_domain(user, "some-domain.com")
+ {:ok, _} = User.follow(user, blocked)
+
+ {:ok, _activity} = CommonAPI.post(blocked, %{"status" => "hey @#{user.nickname}"})
+
+ assert length(Notification.for_user(user)) == 1
+ end
+
test "it doesn't return notifications for muted thread" do
user = insert(:user)
another_user = insert(:user)
@@ -926,7 +954,8 @@ defmodule Pleroma.NotificationTest do
assert Enum.empty?(Notification.for_user(user, %{with_muted: true}))
end
- test "it doesn't return notifications from a domain-blocked user when with_muted is set" do
+ test "when with_muted is set, " <>
+ "it doesn't return notifications from a domain-blocked non-followed user" do
user = insert(:user)
blocked = insert(:user, ap_id: "http://some-domain.com")
{:ok, user} = User.block_domain(user, "some-domain.com")
--
cgit v1.2.3
From 9a3c74b244bce6097a8c6da99692bfc9973e1ec8 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Sun, 12 Apr 2020 20:26:35 -0500
Subject: Always accept deletions through SimplePolicy
---
test/web/activity_pub/mrf/simple_policy_test.exs | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/mrf/simple_policy_test.exs b/test/web/activity_pub/mrf/simple_policy_test.exs
index 91c24c2d9..eaa595706 100644
--- a/test/web/activity_pub/mrf/simple_policy_test.exs
+++ b/test/web/activity_pub/mrf/simple_policy_test.exs
@@ -258,6 +258,14 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do
assert SimplePolicy.filter(remote_user) == {:reject, nil}
end
+
+ test "always accept deletions" do
+ Config.put([:mrf_simple, :reject], ["remote.instance"])
+
+ deletion_message = build_remote_deletion_message()
+
+ assert SimplePolicy.filter(deletion_message) == {:ok, deletion_message}
+ end
end
describe "when :accept" do
@@ -308,6 +316,14 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do
assert SimplePolicy.filter(remote_user) == {:ok, remote_user}
end
+
+ test "always accept deletions" do
+ Config.put([:mrf_simple, :accept], ["non.matching.remote"])
+
+ deletion_message = build_remote_deletion_message()
+
+ assert SimplePolicy.filter(deletion_message) == {:ok, deletion_message}
+ end
end
describe "when :avatar_removal" do
@@ -408,4 +424,11 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do
"type" => "Person"
}
end
+
+ defp build_remote_deletion_message do
+ %{
+ "type" => "Delete",
+ "actor" => "https://remote.instance/users/bob"
+ }
+ end
end
--
cgit v1.2.3
From c5c09fc61b7b6e591e9de23028e5caea8f26b996 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Mon, 13 Apr 2020 06:53:45 +0300
Subject: fix mediaType of object
---
test/fixtures/tesla_mock/bittube-video.json | 1 +
test/fixtures/tesla_mock/hanimated.json | 1 +
test/support/http_request_mock.ex | 16 ++++++++++++++++
test/web/activity_pub/transmogrifier_test.exs | 9 +++++++++
4 files changed, 27 insertions(+)
create mode 100644 test/fixtures/tesla_mock/bittube-video.json
create mode 100644 test/fixtures/tesla_mock/hanimated.json
(limited to 'test')
diff --git a/test/fixtures/tesla_mock/bittube-video.json b/test/fixtures/tesla_mock/bittube-video.json
new file mode 100644
index 000000000..be839862f
--- /dev/null
+++ b/test/fixtures/tesla_mock/bittube-video.json
@@ -0,0 +1 @@
+{"type":"Video","id":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b","name":"Implications of 5G Rollout Simply Explained","duration":"PT428S","uuid":"2aad7dfb-5c75-4ee6-a9ed-08436af0558b","tag":[{"type":"Hashtag","name":"5g"},{"type":"Hashtag","name":"big brother"},{"type":"Hashtag","name":"facial recognition"},{"type":"Hashtag","name":"smart device"}],"category":{"identifier":"15","name":"Science & Technology"},"language":{"identifier":"en","name":"English"},"views":5,"sensitive":false,"waitTranscoding":true,"state":1,"commentsEnabled":true,"downloadEnabled":true,"published":"2020-04-12T11:55:44.805Z","originallyPublishedAt":null,"updated":"2020-04-13T02:01:24.279Z","mediaType":"text/markdown","content":null,"support":null,"subtitleLanguage":[],"icon":{"type":"Image","url":"https://bittube.video/static/thumbnails/2aad7dfb-5c75-4ee6-a9ed-08436af0558b.jpg","mediaType":"image/jpeg","width":223,"height":122},"url":[{"type":"Link","mediaType":"text/html","href":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b"},{"type":"Link","mediaType":"video/mp4","href":"https://bittube.video/static/webseed/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-240.mp4","height":240,"size":17158094,"fps":30},{"type":"Link","mediaType":"application/x-bittorrent","href":"https://bittube.video/static/torrents/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-240.torrent","height":240},{"type":"Link","mediaType":"application/x-bittorrent;x-scheme-handler/magnet","href":"magnet:?xs=https%3A%2F%2Fbittube.video%2Fstatic%2Ftorrents%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-240.torrent&xt=urn:btih:16c8f60d788a29e7ff195de44b4a1558b41dc6c3&dn=Implications+of+5G+Rollout+Simply+Explained&tr=wss%3A%2F%2Fbittube.video%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fbittube.video%2Ftracker%2Fannounce&ws=https%3A%2F%2Fbittube.video%2Fstatic%2Fwebseed%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-240.mp4","height":240},{"type":"Link","mediaType":"video/mp4","href":"https://bittube.video/static/webseed/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-0.mp4","height":0,"size":5215186,"fps":0},{"type":"Link","mediaType":"application/x-bittorrent","href":"https://bittube.video/static/torrents/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-0.torrent","height":0},{"type":"Link","mediaType":"application/x-bittorrent;x-scheme-handler/magnet","href":"magnet:?xs=https%3A%2F%2Fbittube.video%2Fstatic%2Ftorrents%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-0.torrent&xt=urn:btih:8a043b09291f2947423ce96d1cd0e977662d6de8&dn=Implications+of+5G+Rollout+Simply+Explained&tr=wss%3A%2F%2Fbittube.video%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fbittube.video%2Ftracker%2Fannounce&ws=https%3A%2F%2Fbittube.video%2Fstatic%2Fwebseed%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-0.mp4","height":0},{"type":"Link","mediaType":"video/mp4","href":"https://bittube.video/static/webseed/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-360.mp4","height":360,"size":22813140,"fps":30},{"type":"Link","mediaType":"application/x-bittorrent","href":"https://bittube.video/static/torrents/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-360.torrent","height":360},{"type":"Link","mediaType":"application/x-bittorrent;x-scheme-handler/magnet","href":"magnet:?xs=https%3A%2F%2Fbittube.video%2Fstatic%2Ftorrents%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-360.torrent&xt=urn:btih:d121f7493998d4204b3d33d00da7fea1c9a42484&dn=Implications+of+5G+Rollout+Simply+Explained&tr=wss%3A%2F%2Fbittube.video%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fbittube.video%2Ftracker%2Fannounce&ws=https%3A%2F%2Fbittube.video%2Fstatic%2Fwebseed%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-360.mp4","height":360}],"likes":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b/likes","dislikes":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b/dislikes","shares":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b/announces","comments":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b/comments","attributedTo":[{"type":"Person","id":"https://bittube.video/accounts/hanimated.moh"},{"type":"Group","id":"https://bittube.video/video-channels/hanimated.moh_channel"}],"to":["https://www.w3.org/ns/activitystreams#Public"],"cc":["https://bittube.video/accounts/hanimated.moh/followers"],"@context":["https://www.w3.org/ns/activitystreams","https://w3id.org/security/v1",{"RsaSignature2017":"https://w3id.org/security#RsaSignature2017","pt":"https://joinpeertube.org/ns#","sc":"http://schema.org#","Hashtag":"as:Hashtag","uuid":"sc:identifier","category":"sc:category","licence":"sc:license","subtitleLanguage":"sc:subtitleLanguage","sensitive":"as:sensitive","language":"sc:inLanguage","expires":"sc:expires","CacheFile":"pt:CacheFile","Infohash":"pt:Infohash","originallyPublishedAt":"sc:datePublished","views":{"@type":"sc:Number","@id":"pt:views"},"state":{"@type":"sc:Number","@id":"pt:state"},"size":{"@type":"sc:Number","@id":"pt:size"},"fps":{"@type":"sc:Number","@id":"pt:fps"},"startTimestamp":{"@type":"sc:Number","@id":"pt:startTimestamp"},"stopTimestamp":{"@type":"sc:Number","@id":"pt:stopTimestamp"},"position":{"@type":"sc:Number","@id":"pt:position"},"commentsEnabled":{"@type":"sc:Boolean","@id":"pt:commentsEnabled"},"downloadEnabled":{"@type":"sc:Boolean","@id":"pt:downloadEnabled"},"waitTranscoding":{"@type":"sc:Boolean","@id":"pt:waitTranscoding"},"support":{"@type":"sc:Text","@id":"pt:support"}},{"likes":{"@id":"as:likes","@type":"@id"},"dislikes":{"@id":"as:dislikes","@type":"@id"},"playlists":{"@id":"pt:playlists","@type":"@id"},"shares":{"@id":"as:shares","@type":"@id"},"comments":{"@id":"as:comments","@type":"@id"}}]}
diff --git a/test/fixtures/tesla_mock/hanimated.json b/test/fixtures/tesla_mock/hanimated.json
new file mode 100644
index 000000000..564deebd9
--- /dev/null
+++ b/test/fixtures/tesla_mock/hanimated.json
@@ -0,0 +1 @@
+{"type":"Person","id":"https://bittube.video/accounts/hanimated.moh","following":"https://bittube.video/accounts/hanimated.moh/following","followers":"https://bittube.video/accounts/hanimated.moh/followers","playlists":"https://bittube.video/accounts/hanimated.moh/playlists","inbox":"https://bittube.video/accounts/hanimated.moh/inbox","outbox":"https://bittube.video/accounts/hanimated.moh/outbox","preferredUsername":"hanimated.moh","url":"https://bittube.video/accounts/hanimated.moh","name":"Nosat","endpoints":{"sharedInbox":"https://bittube.video/inbox"},"publicKey":{"id":"https://bittube.video/accounts/hanimated.moh#main-key","owner":"https://bittube.video/accounts/hanimated.moh","publicKeyPem":"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwuoQT+4uyAboQcf/okCM\nFqUS/LuqFc2888OSKZFAz00Op/dyOB/pkr1+QLxbl8ZGiUWhmnmhNwmmd3tbhSsC\nvLv9Mz/YaWQPYLfRS/s/7iIxdniC4lo/YgicOrzcvetHmk1feOg5vb5/yc+bgUSm\nOk+L4azqXP9GmZyofzvufT65bUmzQRFXP19eL55YZWvZDaC81QAfRXsqtCqbehtF\nQNOjGhnl6a7Kfe8KprRDPV/3WvvFjftnNO2qenIIOFLLeznkQ0ELP6lyb9pvv/1C\n2/GRh2BwmgVlCTw1kTxLSdj80BFX5P8AudSiIx079lVkhamEhzsNLkMpQFqWAAlg\nrQIDAQAB\n-----END PUBLIC KEY-----"},"icon":{"type":"Image","mediaType":"image/jpeg","url":"https://bittube.video/lazy-static/avatars/84b8acc3-e48b-4642-a9f4-360a4499579b.jpg"},"@context":["https://www.w3.org/ns/activitystreams","https://w3id.org/security/v1",{"RsaSignature2017":"https://w3id.org/security#RsaSignature2017","pt":"https://joinpeertube.org/ns#","sc":"http://schema.org#","Hashtag":"as:Hashtag","uuid":"sc:identifier","category":"sc:category","licence":"sc:license","subtitleLanguage":"sc:subtitleLanguage","sensitive":"as:sensitive","language":"sc:inLanguage","expires":"sc:expires","CacheFile":"pt:CacheFile","Infohash":"pt:Infohash","originallyPublishedAt":"sc:datePublished","views":{"@type":"sc:Number","@id":"pt:views"},"state":{"@type":"sc:Number","@id":"pt:state"},"size":{"@type":"sc:Number","@id":"pt:size"},"fps":{"@type":"sc:Number","@id":"pt:fps"},"startTimestamp":{"@type":"sc:Number","@id":"pt:startTimestamp"},"stopTimestamp":{"@type":"sc:Number","@id":"pt:stopTimestamp"},"position":{"@type":"sc:Number","@id":"pt:position"},"commentsEnabled":{"@type":"sc:Boolean","@id":"pt:commentsEnabled"},"downloadEnabled":{"@type":"sc:Boolean","@id":"pt:downloadEnabled"},"waitTranscoding":{"@type":"sc:Boolean","@id":"pt:waitTranscoding"},"support":{"@type":"sc:Text","@id":"pt:support"}},{"likes":{"@id":"as:likes","@type":"@id"},"dislikes":{"@id":"as:dislikes","@type":"@id"},"playlists":{"@id":"pt:playlists","@type":"@id"},"shares":{"@id":"as:shares","@type":"@id"},"comments":{"@id":"as:comments","@type":"@id"}}],"summary":null}
diff --git a/test/support/http_request_mock.ex b/test/support/http_request_mock.ex
index 20cb2b3d1..54dde0432 100644
--- a/test/support/http_request_mock.ex
+++ b/test/support/http_request_mock.ex
@@ -308,6 +308,22 @@ defmodule HttpRequestMock do
}}
end
+ def get("https://bittube.video/accounts/hanimated.moh", _, _, _) do
+ {:ok,
+ %Tesla.Env{
+ status: 200,
+ body: File.read!("test/fixtures/tesla_mock/hanimated.json")
+ }}
+ end
+
+ def get("https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b", _, _, _) do
+ {:ok,
+ %Tesla.Env{
+ status: 200,
+ body: File.read!("test/fixtures/tesla_mock/bittube-video.json")
+ }}
+ end
+
def get("https://mobilizon.org/events/252d5816-00a3-4a89-a66f-15bf65c33e39", _, _, [
{"accept", "application/activity+json"}
]) do
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 2332029e5..de9663fa9 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -1221,6 +1221,15 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
:error = Transmogrifier.handle_incoming(data)
end
+ test "it remaps mediaType of object" do
+ {:ok, object} =
+ Fetcher.fetch_object_from_id(
+ "https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b"
+ )
+
+ assert object.data["mediaType"] == "text/html"
+ end
+
test "it remaps video URLs as attachments if necessary" do
{:ok, object} =
Fetcher.fetch_object_from_id(
--
cgit v1.2.3
From a050f3e015a6c5c8d38d535692d4da7a6b1e9c60 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Fri, 10 Apr 2020 14:42:52 +0300
Subject: fix for logger configuration through admin-fe
---
test/web/admin_api/admin_api_controller_test.exs | 17 +++++++----------
1 file changed, 7 insertions(+), 10 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index f02f6ae7a..60ec895f5 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -2273,13 +2273,17 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
value: :erlang.term_to_binary([])
)
+ Pleroma.Config.TransferTask.load_and_update_env([], false)
+
+ assert Application.get_env(:logger, :backends) == []
+
conn =
post(conn, "/api/pleroma/admin/config", %{
configs: [
%{
group: config.group,
key: config.key,
- value: [":console", %{"tuple" => ["ExSyslogger", ":ex_syslogger"]}]
+ value: [":console"]
}
]
})
@@ -2290,8 +2294,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
"group" => ":logger",
"key" => ":backends",
"value" => [
- ":console",
- %{"tuple" => ["ExSyslogger", ":ex_syslogger"]}
+ ":console"
],
"db" => [":backends"]
}
@@ -2299,14 +2302,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
}
assert Application.get_env(:logger, :backends) == [
- :console,
- {ExSyslogger, :ex_syslogger}
+ :console
]
-
- capture_log(fn ->
- require Logger
- Logger.warn("Ooops...")
- end) =~ "Ooops..."
end
test "saving full setting if value is not keyword", %{conn: conn} do
--
cgit v1.2.3
From b08ded6c2f5ee29c6efc8c67cfc2ce0a679f0c77 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Fri, 3 Apr 2020 22:45:08 +0400
Subject: Add spec for AccountController.create
---
test/web/api_spec/account_operation_test.exs | 48 +++++
.../controllers/account_controller_test.exs | 30 ++-
test/web/twitter_api/twitter_api_test.exs | 222 ++++++++++-----------
3 files changed, 182 insertions(+), 118 deletions(-)
create mode 100644 test/web/api_spec/account_operation_test.exs
(limited to 'test')
diff --git a/test/web/api_spec/account_operation_test.exs b/test/web/api_spec/account_operation_test.exs
new file mode 100644
index 000000000..4f8d04698
--- /dev/null
+++ b/test/web/api_spec/account_operation_test.exs
@@ -0,0 +1,48 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ApiSpec.AccountOperationTest do
+ use Pleroma.Web.ConnCase, async: true
+
+ alias Pleroma.Web.ApiSpec
+ alias Pleroma.Web.ApiSpec.Schemas.AccountCreateRequest
+ alias Pleroma.Web.ApiSpec.Schemas.AccountCreateResponse
+
+ import OpenApiSpex.TestAssertions
+ import Pleroma.Factory
+
+ test "AccountCreateRequest example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = AccountCreateRequest.schema()
+ assert_schema(schema.example, "AccountCreateRequest", api_spec)
+ end
+
+ test "AccountCreateResponse example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = AccountCreateResponse.schema()
+ assert_schema(schema.example, "AccountCreateResponse", api_spec)
+ end
+
+ test "AccountController produces a AccountCreateResponse", %{conn: conn} do
+ api_spec = ApiSpec.spec()
+ app_token = insert(:oauth_token, user: nil)
+
+ json =
+ conn
+ |> put_req_header("authorization", "Bearer " <> app_token.token)
+ |> put_req_header("content-type", "application/json")
+ |> post(
+ "/api/v1/accounts",
+ %{
+ username: "foo",
+ email: "bar@example.org",
+ password: "qwerty",
+ agreement: true
+ }
+ )
+ |> json_response(200)
+
+ assert_schema(json, "AccountCreateResponse", api_spec)
+ end
+end
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index a450a732c..6fe46af3c 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -830,6 +830,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
conn =
build_conn()
+ |> put_req_header("content-type", "multipart/form-data")
|> put_req_header("authorization", "Bearer " <> token)
|> post("/api/v1/accounts", %{
username: "lain",
@@ -858,11 +859,12 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
_user = insert(:user, email: "lain@example.org")
app_token = insert(:oauth_token, user: nil)
- conn =
+ res =
conn
|> put_req_header("authorization", "Bearer " <> app_token.token)
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/accounts", valid_params)
- res = post(conn, "/api/v1/accounts", valid_params)
assert json_response(res, 400) == %{"error" => "{\"email\":[\"has already been taken\"]}"}
end
@@ -872,7 +874,10 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
} do
app_token = insert(:oauth_token, user: nil)
- conn = put_req_header(conn, "authorization", "Bearer " <> app_token.token)
+ conn =
+ conn
+ |> put_req_header("authorization", "Bearer " <> app_token.token)
+ |> put_req_header("content-type", "application/json")
res = post(conn, "/api/v1/accounts", valid_params)
assert json_response(res, 200)
@@ -897,7 +902,11 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
Pleroma.Config.put([:instance, :account_activation_required], true)
app_token = insert(:oauth_token, user: nil)
- conn = put_req_header(conn, "authorization", "Bearer " <> app_token.token)
+
+ conn =
+ conn
+ |> put_req_header("authorization", "Bearer " <> app_token.token)
+ |> put_req_header("content-type", "application/json")
res =
conn
@@ -920,6 +929,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
res =
conn
+ |> put_req_header("content-type", "application/json")
|> Map.put(:remote_ip, {127, 0, 0, 7})
|> post("/api/v1/accounts", Map.delete(valid_params, :email))
@@ -932,6 +942,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
res =
conn
+ |> put_req_header("content-type", "application/json")
|> Map.put(:remote_ip, {127, 0, 0, 8})
|> post("/api/v1/accounts", Map.put(valid_params, :email, ""))
@@ -939,9 +950,12 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
end
test "returns forbidden if token is invalid", %{conn: conn, valid_params: valid_params} do
- conn = put_req_header(conn, "authorization", "Bearer " <> "invalid-token")
+ res =
+ conn
+ |> put_req_header("authorization", "Bearer " <> "invalid-token")
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/v1/accounts", valid_params)
- res = post(conn, "/api/v1/accounts", valid_params)
assert json_response(res, 403) == %{"error" => "Invalid credentials"}
end
end
@@ -956,10 +970,12 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
conn
|> put_req_header("authorization", "Bearer " <> app_token.token)
|> Map.put(:remote_ip, {15, 15, 15, 15})
+ |> put_req_header("content-type", "multipart/form-data")
for i <- 1..2 do
conn =
- post(conn, "/api/v1/accounts", %{
+ conn
+ |> post("/api/v1/accounts", %{
username: "#{i}lain",
email: "#{i}lain@example.org",
password: "PlzDontHackLain",
diff --git a/test/web/twitter_api/twitter_api_test.exs b/test/web/twitter_api/twitter_api_test.exs
index f6e13b661..7926a0757 100644
--- a/test/web/twitter_api/twitter_api_test.exs
+++ b/test/web/twitter_api/twitter_api_test.exs
@@ -18,11 +18,11 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
test "it registers a new user and returns the user." do
data = %{
- "nickname" => "lain",
- "email" => "lain@wired.jp",
- "fullname" => "lain iwakura",
- "password" => "bear",
- "confirm" => "bear"
+ :nickname => "lain",
+ :email => "lain@wired.jp",
+ :fullname => "lain iwakura",
+ :password => "bear",
+ :confirm => "bear"
}
{:ok, user} = TwitterAPI.register_user(data)
@@ -35,12 +35,12 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
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"
+ :nickname => "lain",
+ :email => "lain@wired.jp",
+ :fullname => "lain iwakura",
+ :bio => "",
+ :password => "bear",
+ :confirm => "bear"
}
{:ok, user} = TwitterAPI.register_user(data)
@@ -60,12 +60,12 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
end
data = %{
- "nickname" => "lain",
- "email" => "lain@wired.jp",
- "fullname" => "lain iwakura",
- "bio" => "",
- "password" => "bear",
- "confirm" => "bear"
+ :nickname => "lain",
+ :email => "lain@wired.jp",
+ :fullname => "lain iwakura",
+ :bio => "",
+ :password => "bear",
+ :confirm => "bear"
}
{:ok, user} = TwitterAPI.register_user(data)
@@ -87,23 +87,23 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
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"
+ :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"
+ :nickname => "lain",
+ :email => "lain@wired.jp",
+ :fullname => "lain iwakura",
+ :bio => "@john test",
+ :password => "bear",
+ :confirm => "bear"
}
{:ok, user2} = TwitterAPI.register_user(data2)
@@ -123,13 +123,13 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
{:ok, invite} = UserInviteToken.create_invite()
data = %{
- "nickname" => "vinny",
- "email" => "pasta@pizza.vs",
- "fullname" => "Vinny Vinesauce",
- "bio" => "streamer",
- "password" => "hiptofbees",
- "confirm" => "hiptofbees",
- "token" => invite.token
+ :nickname => "vinny",
+ :email => "pasta@pizza.vs",
+ :fullname => "Vinny Vinesauce",
+ :bio => "streamer",
+ :password => "hiptofbees",
+ :confirm => "hiptofbees",
+ :token => invite.token
}
{:ok, user} = TwitterAPI.register_user(data)
@@ -145,13 +145,13 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
test "returns error on invalid token" do
data = %{
- "nickname" => "GrimReaper",
- "email" => "death@reapers.afterlife",
- "fullname" => "Reaper Grim",
- "bio" => "Your time has come",
- "password" => "scythe",
- "confirm" => "scythe",
- "token" => "DudeLetMeInImAFairy"
+ :nickname => "GrimReaper",
+ :email => "death@reapers.afterlife",
+ :fullname => "Reaper Grim",
+ :bio => "Your time has come",
+ :password => "scythe",
+ :confirm => "scythe",
+ :token => "DudeLetMeInImAFairy"
}
{:error, msg} = TwitterAPI.register_user(data)
@@ -165,13 +165,13 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
UserInviteToken.update_invite!(invite, used: true)
data = %{
- "nickname" => "GrimReaper",
- "email" => "death@reapers.afterlife",
- "fullname" => "Reaper Grim",
- "bio" => "Your time has come",
- "password" => "scythe",
- "confirm" => "scythe",
- "token" => invite.token
+ :nickname => "GrimReaper",
+ :email => "death@reapers.afterlife",
+ :fullname => "Reaper Grim",
+ :bio => "Your time has come",
+ :password => "scythe",
+ :confirm => "scythe",
+ :token => invite.token
}
{:error, msg} = TwitterAPI.register_user(data)
@@ -186,16 +186,16 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
setup do
data = %{
- "nickname" => "vinny",
- "email" => "pasta@pizza.vs",
- "fullname" => "Vinny Vinesauce",
- "bio" => "streamer",
- "password" => "hiptofbees",
- "confirm" => "hiptofbees"
+ :nickname => "vinny",
+ :email => "pasta@pizza.vs",
+ :fullname => "Vinny Vinesauce",
+ :bio => "streamer",
+ :password => "hiptofbees",
+ :confirm => "hiptofbees"
}
check_fn = fn invite ->
- data = Map.put(data, "token", invite.token)
+ data = Map.put(data, :token, invite.token)
{:ok, user} = TwitterAPI.register_user(data)
fetched_user = User.get_cached_by_nickname("vinny")
@@ -250,13 +250,13 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
UserInviteToken.update_invite!(invite, uses: 99)
data = %{
- "nickname" => "vinny",
- "email" => "pasta@pizza.vs",
- "fullname" => "Vinny Vinesauce",
- "bio" => "streamer",
- "password" => "hiptofbees",
- "confirm" => "hiptofbees",
- "token" => invite.token
+ :nickname => "vinny",
+ :email => "pasta@pizza.vs",
+ :fullname => "Vinny Vinesauce",
+ :bio => "streamer",
+ :password => "hiptofbees",
+ :confirm => "hiptofbees",
+ :token => invite.token
}
{:ok, user} = TwitterAPI.register_user(data)
@@ -269,13 +269,13 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
AccountView.render("show.json", %{user: fetched_user})
data = %{
- "nickname" => "GrimReaper",
- "email" => "death@reapers.afterlife",
- "fullname" => "Reaper Grim",
- "bio" => "Your time has come",
- "password" => "scythe",
- "confirm" => "scythe",
- "token" => invite.token
+ :nickname => "GrimReaper",
+ :email => "death@reapers.afterlife",
+ :fullname => "Reaper Grim",
+ :bio => "Your time has come",
+ :password => "scythe",
+ :confirm => "scythe",
+ :token => invite.token
}
{:error, msg} = TwitterAPI.register_user(data)
@@ -292,13 +292,13 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
{:ok, invite} = UserInviteToken.create_invite(%{expires_at: Date.utc_today(), max_use: 100})
data = %{
- "nickname" => "vinny",
- "email" => "pasta@pizza.vs",
- "fullname" => "Vinny Vinesauce",
- "bio" => "streamer",
- "password" => "hiptofbees",
- "confirm" => "hiptofbees",
- "token" => invite.token
+ :nickname => "vinny",
+ :email => "pasta@pizza.vs",
+ :fullname => "Vinny Vinesauce",
+ :bio => "streamer",
+ :password => "hiptofbees",
+ :confirm => "hiptofbees",
+ :token => invite.token
}
{:ok, user} = TwitterAPI.register_user(data)
@@ -317,13 +317,13 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
UserInviteToken.update_invite!(invite, uses: 99)
data = %{
- "nickname" => "vinny",
- "email" => "pasta@pizza.vs",
- "fullname" => "Vinny Vinesauce",
- "bio" => "streamer",
- "password" => "hiptofbees",
- "confirm" => "hiptofbees",
- "token" => invite.token
+ :nickname => "vinny",
+ :email => "pasta@pizza.vs",
+ :fullname => "Vinny Vinesauce",
+ :bio => "streamer",
+ :password => "hiptofbees",
+ :confirm => "hiptofbees",
+ :token => invite.token
}
{:ok, user} = TwitterAPI.register_user(data)
@@ -335,13 +335,13 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
AccountView.render("show.json", %{user: fetched_user})
data = %{
- "nickname" => "GrimReaper",
- "email" => "death@reapers.afterlife",
- "fullname" => "Reaper Grim",
- "bio" => "Your time has come",
- "password" => "scythe",
- "confirm" => "scythe",
- "token" => invite.token
+ :nickname => "GrimReaper",
+ :email => "death@reapers.afterlife",
+ :fullname => "Reaper Grim",
+ :bio => "Your time has come",
+ :password => "scythe",
+ :confirm => "scythe",
+ :token => invite.token
}
{:error, msg} = TwitterAPI.register_user(data)
@@ -355,13 +355,13 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
UserInviteToken.create_invite(%{expires_at: Date.add(Date.utc_today(), -1), max_use: 100})
data = %{
- "nickname" => "GrimReaper",
- "email" => "death@reapers.afterlife",
- "fullname" => "Reaper Grim",
- "bio" => "Your time has come",
- "password" => "scythe",
- "confirm" => "scythe",
- "token" => invite.token
+ :nickname => "GrimReaper",
+ :email => "death@reapers.afterlife",
+ :fullname => "Reaper Grim",
+ :bio => "Your time has come",
+ :password => "scythe",
+ :confirm => "scythe",
+ :token => invite.token
}
{:error, msg} = TwitterAPI.register_user(data)
@@ -377,13 +377,13 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
UserInviteToken.update_invite!(invite, uses: 100)
data = %{
- "nickname" => "GrimReaper",
- "email" => "death@reapers.afterlife",
- "fullname" => "Reaper Grim",
- "bio" => "Your time has come",
- "password" => "scythe",
- "confirm" => "scythe",
- "token" => invite.token
+ :nickname => "GrimReaper",
+ :email => "death@reapers.afterlife",
+ :fullname => "Reaper Grim",
+ :bio => "Your time has come",
+ :password => "scythe",
+ :confirm => "scythe",
+ :token => invite.token
}
{:error, msg} = TwitterAPI.register_user(data)
@@ -395,11 +395,11 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
test "it returns the error on registration problems" do
data = %{
- "nickname" => "lain",
- "email" => "lain@wired.jp",
- "fullname" => "lain iwakura",
- "bio" => "close the world.",
- "password" => "bear"
+ :nickname => "lain",
+ :email => "lain@wired.jp",
+ :fullname => "lain iwakura",
+ :bio => "close the world.",
+ :password => "bear"
}
{:error, error_object} = TwitterAPI.register_user(data)
--
cgit v1.2.3
From f80116125f928de36c93627bbdf5f6578396f53b Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 6 Apr 2020 00:15:37 +0400
Subject: Add spec for AccountController.verify_credentials
---
test/web/api_spec/account_operation_test.exs | 7 +++++++
1 file changed, 7 insertions(+)
(limited to 'test')
diff --git a/test/web/api_spec/account_operation_test.exs b/test/web/api_spec/account_operation_test.exs
index 4f8d04698..37501b8cc 100644
--- a/test/web/api_spec/account_operation_test.exs
+++ b/test/web/api_spec/account_operation_test.exs
@@ -6,12 +6,19 @@ defmodule Pleroma.Web.ApiSpec.AccountOperationTest do
use Pleroma.Web.ConnCase, async: true
alias Pleroma.Web.ApiSpec
+ alias Pleroma.Web.ApiSpec.Schemas.Account
alias Pleroma.Web.ApiSpec.Schemas.AccountCreateRequest
alias Pleroma.Web.ApiSpec.Schemas.AccountCreateResponse
import OpenApiSpex.TestAssertions
import Pleroma.Factory
+ test "Account example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = Account.schema()
+ assert_schema(schema.example, "Account", api_spec)
+ end
+
test "AccountCreateRequest example matches schema" do
api_spec = ApiSpec.spec()
schema = AccountCreateRequest.schema()
--
cgit v1.2.3
From 260cbddc943e53a85762e56852de65d2b900cc04 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 7 Apr 2020 14:53:12 +0400
Subject: Add spec for AccountController.update_credentials
---
test/support/conn_case.ex | 5 ++++
test/web/api_spec/account_operation_test.exs | 32 ++++++++++++++++++++++
.../account_controller/update_credentials_test.exs | 2 ++
3 files changed, 39 insertions(+)
(limited to 'test')
diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex
index 064874201..36ce372c2 100644
--- a/test/support/conn_case.ex
+++ b/test/support/conn_case.ex
@@ -51,6 +51,11 @@ defmodule Pleroma.Web.ConnCase do
%{user: user, token: token, conn: conn}
end
+ defp request_content_type(%{conn: conn}) do
+ conn = put_req_header(conn, "content-type", "multipart/form-data")
+ [conn: conn]
+ end
+
defp ensure_federating_or_authenticated(conn, url, user) do
initial_setting = Config.get([:instance, :federating])
on_exit(fn -> Config.put([:instance, :federating], initial_setting) end)
diff --git a/test/web/api_spec/account_operation_test.exs b/test/web/api_spec/account_operation_test.exs
index 37501b8cc..a54059074 100644
--- a/test/web/api_spec/account_operation_test.exs
+++ b/test/web/api_spec/account_operation_test.exs
@@ -9,6 +9,7 @@ defmodule Pleroma.Web.ApiSpec.AccountOperationTest do
alias Pleroma.Web.ApiSpec.Schemas.Account
alias Pleroma.Web.ApiSpec.Schemas.AccountCreateRequest
alias Pleroma.Web.ApiSpec.Schemas.AccountCreateResponse
+ alias Pleroma.Web.ApiSpec.Schemas.AccountUpdateCredentialsRequest
import OpenApiSpex.TestAssertions
import Pleroma.Factory
@@ -31,6 +32,12 @@ defmodule Pleroma.Web.ApiSpec.AccountOperationTest do
assert_schema(schema.example, "AccountCreateResponse", api_spec)
end
+ test "AccountUpdateCredentialsRequest example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = AccountUpdateCredentialsRequest.schema()
+ assert_schema(schema.example, "AccountUpdateCredentialsRequest", api_spec)
+ end
+
test "AccountController produces a AccountCreateResponse", %{conn: conn} do
api_spec = ApiSpec.spec()
app_token = insert(:oauth_token, user: nil)
@@ -52,4 +59,29 @@ defmodule Pleroma.Web.ApiSpec.AccountOperationTest do
assert_schema(json, "AccountCreateResponse", api_spec)
end
+
+ test "AccountUpdateCredentialsRequest produces an Account", %{conn: conn} do
+ api_spec = ApiSpec.spec()
+ token = insert(:oauth_token, scopes: ["read", "write"])
+
+ json =
+ conn
+ |> put_req_header("authorization", "Bearer " <> token.token)
+ |> put_req_header("content-type", "application/json")
+ |> patch(
+ "/api/v1/accounts/update_credentials",
+ %{
+ hide_followers_count: "true",
+ hide_follows_count: "true",
+ skip_thread_containment: "true",
+ hide_follows: "true",
+ pleroma_settings_store: %{"pleroma-fe" => %{"key" => "val"}},
+ note: "foobar",
+ fields_attributes: [%{name: "foo", value: "bar"}]
+ }
+ )
+ |> json_response(200)
+
+ assert_schema(json, "Account", api_spec)
+ end
end
diff --git a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
index 2d256f63c..0e890a980 100644
--- a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
@@ -14,6 +14,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
describe "updating credentials" do
setup do: oauth_access(["write:accounts"])
+ setup :request_content_type
test "sets user settings in a generic way", %{conn: conn} do
res_conn =
@@ -237,6 +238,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
for token <- [token1, token2] do
conn =
build_conn()
+ |> put_req_header("content-type", "multipart/form-data")
|> put_req_header("authorization", "Bearer #{token.token}")
|> patch("/api/v1/accounts/update_credentials", %{})
--
cgit v1.2.3
From ab400b2ddb205271b0a2680c45db18844f59a27d Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 7 Apr 2020 16:18:23 +0400
Subject: Add specs for ActorType and VisibilityScope
---
.../controllers/account_controller/update_credentials_test.exs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
index 0e890a980..a3356c12f 100644
--- a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
@@ -106,10 +106,10 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
end
test "updates the user's default scope", %{conn: conn} do
- conn = patch(conn, "/api/v1/accounts/update_credentials", %{default_scope: "cofe"})
+ conn = patch(conn, "/api/v1/accounts/update_credentials", %{default_scope: "unlisted"})
assert user_data = json_response(conn, 200)
- assert user_data["source"]["privacy"] == "cofe"
+ assert user_data["source"]["privacy"] == "unlisted"
end
test "updates the user's hide_followers status", %{conn: conn} do
--
cgit v1.2.3
From d7d6a83233f24b80005b4f49a8697535620e4b83 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 7 Apr 2020 18:29:05 +0400
Subject: Add spec for AccountController.relationships
---
test/web/api_spec/account_operation_test.exs | 24 ++++++++++++++++++++++
.../controllers/account_controller_test.exs | 14 ++++++++-----
2 files changed, 33 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/web/api_spec/account_operation_test.exs b/test/web/api_spec/account_operation_test.exs
index a54059074..58a38d8af 100644
--- a/test/web/api_spec/account_operation_test.exs
+++ b/test/web/api_spec/account_operation_test.exs
@@ -9,6 +9,7 @@ defmodule Pleroma.Web.ApiSpec.AccountOperationTest do
alias Pleroma.Web.ApiSpec.Schemas.Account
alias Pleroma.Web.ApiSpec.Schemas.AccountCreateRequest
alias Pleroma.Web.ApiSpec.Schemas.AccountCreateResponse
+ alias Pleroma.Web.ApiSpec.Schemas.AccountRelationshipsResponse
alias Pleroma.Web.ApiSpec.Schemas.AccountUpdateCredentialsRequest
import OpenApiSpex.TestAssertions
@@ -84,4 +85,27 @@ defmodule Pleroma.Web.ApiSpec.AccountOperationTest do
assert_schema(json, "Account", api_spec)
end
+
+ test "AccountRelationshipsResponse example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = AccountRelationshipsResponse.schema()
+ assert_schema(schema.example, "AccountRelationshipsResponse", api_spec)
+ end
+
+ test "/api/v1/accounts/relationships produces AccountRelationshipsResponse", %{
+ conn: conn
+ } do
+ token = insert(:oauth_token, scopes: ["read", "write"])
+ other_user = insert(:user)
+ {:ok, _user} = Pleroma.User.follow(token.user, other_user)
+ api_spec = ApiSpec.spec()
+
+ assert [relationship] =
+ conn
+ |> put_req_header("authorization", "Bearer " <> token.token)
+ |> get("/api/v1/accounts/relationships?id=#{other_user.id}")
+ |> json_response(:ok)
+
+ assert_schema([relationship], "AccountRelationshipsResponse", api_spec)
+ end
end
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 6fe46af3c..060a7c1cd 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -1062,14 +1062,18 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
setup do: oauth_access(["read:follows"])
test "returns the relationships for the current user", %{user: user, conn: conn} do
- other_user = insert(:user)
+ %{id: other_user_id} = other_user = insert(:user)
{:ok, _user} = User.follow(user, other_user)
- conn = get(conn, "/api/v1/accounts/relationships", %{"id" => [other_user.id]})
-
- assert [relationship] = json_response(conn, 200)
+ assert [%{"id" => ^other_user_id}] =
+ conn
+ |> get("/api/v1/accounts/relationships?id=#{other_user.id}")
+ |> json_response(200)
- assert to_string(other_user.id) == relationship["id"]
+ assert [%{"id" => ^other_user_id}] =
+ conn
+ |> get("/api/v1/accounts/relationships?id[]=#{other_user.id}")
+ |> json_response(200)
end
test "returns an empty list on a bad request", %{conn: conn} do
--
cgit v1.2.3
From 278b3fa0ad0ca58a9e5549e98d24944bbe0bf766 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 7 Apr 2020 18:53:12 +0400
Subject: Add spec for AccountController.show
---
test/web/api_spec/account_operation_test.exs | 16 +++++++++++++++-
1 file changed, 15 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/api_spec/account_operation_test.exs b/test/web/api_spec/account_operation_test.exs
index 58a38d8af..6cc08ee0e 100644
--- a/test/web/api_spec/account_operation_test.exs
+++ b/test/web/api_spec/account_operation_test.exs
@@ -3,7 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ApiSpec.AccountOperationTest do
- use Pleroma.Web.ConnCase, async: true
+ use Pleroma.Web.ConnCase
alias Pleroma.Web.ApiSpec
alias Pleroma.Web.ApiSpec.Schemas.Account
@@ -108,4 +108,18 @@ defmodule Pleroma.Web.ApiSpec.AccountOperationTest do
assert_schema([relationship], "AccountRelationshipsResponse", api_spec)
end
+
+ test "/api/v1/accounts/:id produces Account", %{
+ conn: conn
+ } do
+ user = insert(:user)
+ api_spec = ApiSpec.spec()
+
+ assert resp =
+ conn
+ |> get("/api/v1/accounts/#{user.id}")
+ |> json_response(:ok)
+
+ assert_schema(resp, "Account", api_spec)
+ end
end
--
cgit v1.2.3
From 03124c96cc192ef8c4893738a0cee552c6984da6 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 8 Apr 2020 22:33:25 +0400
Subject: Add spec for AccountController.statuses
---
test/web/api_spec/account_operation_test.exs | 16 ++++++
.../controllers/account_controller_test.exs | 60 ++++++++++++++--------
2 files changed, 56 insertions(+), 20 deletions(-)
(limited to 'test')
diff --git a/test/web/api_spec/account_operation_test.exs b/test/web/api_spec/account_operation_test.exs
index 6cc08ee0e..892ade71c 100644
--- a/test/web/api_spec/account_operation_test.exs
+++ b/test/web/api_spec/account_operation_test.exs
@@ -122,4 +122,20 @@ defmodule Pleroma.Web.ApiSpec.AccountOperationTest do
assert_schema(resp, "Account", api_spec)
end
+
+ test "/api/v1/accounts/:id/statuses produces StatusesResponse", %{
+ conn: conn
+ } do
+ user = insert(:user)
+ Pleroma.Web.CommonAPI.post(user, %{"status" => "foobar"})
+
+ api_spec = ApiSpec.spec()
+
+ assert resp =
+ conn
+ |> get("/api/v1/accounts/#{user.id}/statuses")
+ |> json_response(:ok)
+
+ assert_schema(resp, "StatusesResponse", api_spec)
+ end
end
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 060a7c1cd..969256fa4 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -10,9 +10,11 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.InternalFetchActor
+ alias Pleroma.Web.ApiSpec
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.OAuth.Token
+ import OpenApiSpex.TestAssertions
import Pleroma.Factory
describe "account fetching" do
@@ -245,22 +247,23 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
{:ok, activity} = CommonAPI.post(user_two, %{"status" => "User one sux0rz"})
{:ok, repeat, _} = CommonAPI.repeat(activity.id, user_three)
- resp = get(conn, "/api/v1/accounts/#{user_two.id}/statuses")
-
- assert [%{"id" => id}] = json_response(resp, 200)
+ assert resp = get(conn, "/api/v1/accounts/#{user_two.id}/statuses") |> json_response(200)
+ assert [%{"id" => id}] = resp
+ assert_schema(resp, "StatusesResponse", ApiSpec.spec())
assert id == activity.id
# Even a blocked user will deliver the full user timeline, there would be
# no point in looking at a blocked users timeline otherwise
- resp = get(conn, "/api/v1/accounts/#{user_two.id}/statuses")
-
- assert [%{"id" => id}] = json_response(resp, 200)
+ assert resp = get(conn, "/api/v1/accounts/#{user_two.id}/statuses") |> json_response(200)
+ assert [%{"id" => id}] = resp
assert id == activity.id
+ assert_schema(resp, "StatusesResponse", ApiSpec.spec())
# Third user's timeline includes the repeat when viewed by unauthenticated user
- resp = get(build_conn(), "/api/v1/accounts/#{user_three.id}/statuses")
- assert [%{"id" => id}] = json_response(resp, 200)
+ resp = get(build_conn(), "/api/v1/accounts/#{user_three.id}/statuses") |> json_response(200)
+ assert [%{"id" => id}] = resp
assert id == repeat.id
+ assert_schema(resp, "StatusesResponse", ApiSpec.spec())
# When viewing a third user's timeline, the blocked users' statuses will NOT be shown
resp = get(conn, "/api/v1/accounts/#{user_three.id}/statuses")
@@ -286,30 +289,34 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
{:ok, private_activity} =
CommonAPI.post(user_one, %{"status" => "private", "visibility" => "private"})
- resp = get(conn, "/api/v1/accounts/#{user_one.id}/statuses")
-
- assert [%{"id" => id}] = json_response(resp, 200)
+ resp = get(conn, "/api/v1/accounts/#{user_one.id}/statuses") |> json_response(200)
+ assert [%{"id" => id}] = resp
assert id == to_string(activity.id)
+ assert_schema(resp, "StatusesResponse", ApiSpec.spec())
resp =
conn
|> assign(:user, user_two)
|> assign(:token, insert(:oauth_token, user: user_two, scopes: ["read:statuses"]))
|> get("/api/v1/accounts/#{user_one.id}/statuses")
+ |> json_response(200)
- assert [%{"id" => id_one}, %{"id" => id_two}] = json_response(resp, 200)
+ assert [%{"id" => id_one}, %{"id" => id_two}] = resp
assert id_one == to_string(direct_activity.id)
assert id_two == to_string(activity.id)
+ assert_schema(resp, "StatusesResponse", ApiSpec.spec())
resp =
conn
|> assign(:user, user_three)
|> assign(:token, insert(:oauth_token, user: user_three, scopes: ["read:statuses"]))
|> get("/api/v1/accounts/#{user_one.id}/statuses")
+ |> json_response(200)
- assert [%{"id" => id_one}, %{"id" => id_two}] = json_response(resp, 200)
+ assert [%{"id" => id_one}, %{"id" => id_two}] = resp
assert id_one == to_string(private_activity.id)
assert id_two == to_string(activity.id)
+ assert_schema(resp, "StatusesResponse", ApiSpec.spec())
end
test "unimplemented pinned statuses feature", %{conn: conn} do
@@ -335,40 +342,45 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
{:ok, image_post} = CommonAPI.post(user, %{"status" => "cofe", "media_ids" => [media_id]})
- conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"only_media" => "true"})
+ conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?only_media=true")
assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(image_post.id)
+ assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
- conn = get(build_conn(), "/api/v1/accounts/#{user.id}/statuses", %{"only_media" => "1"})
+ conn = get(build_conn(), "/api/v1/accounts/#{user.id}/statuses?only_media=1")
assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(image_post.id)
+ assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
end
test "gets a user's statuses without reblogs", %{user: user, conn: conn} do
{:ok, post} = CommonAPI.post(user, %{"status" => "HI!!!"})
{:ok, _, _} = CommonAPI.repeat(post.id, user)
- conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"exclude_reblogs" => "true"})
+ conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?exclude_reblogs=true")
assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(post.id)
+ assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
- conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"exclude_reblogs" => "1"})
+ conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?exclude_reblogs=1")
assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(post.id)
+ assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
end
test "filters user's statuses by a hashtag", %{user: user, conn: conn} do
{:ok, post} = CommonAPI.post(user, %{"status" => "#hashtag"})
{:ok, _post} = CommonAPI.post(user, %{"status" => "hashtag"})
- conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"tagged" => "hashtag"})
+ conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?tagged=hashtag")
assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(post.id)
+ assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
end
test "the user views their own timelines and excludes direct messages", %{
@@ -378,11 +390,11 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
{:ok, public_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "public"})
{:ok, _direct_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
- conn =
- get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"exclude_visibilities" => ["direct"]})
+ conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?exclude_visibilities[]=direct")
assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(public_activity.id)
+ assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
end
end
@@ -420,9 +432,11 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses")
assert length(json_response(res_conn, 200)) == 1
+ assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses")
assert length(json_response(res_conn, 200)) == 1
+ assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
end
end
@@ -441,6 +455,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses")
assert length(json_response(res_conn, 200)) == 1
+ assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
end
test "if user is authenticated", %{local: local, remote: remote} do
@@ -448,9 +463,11 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses")
assert length(json_response(res_conn, 200)) == 1
+ assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses")
assert length(json_response(res_conn, 200)) == 1
+ assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
end
end
@@ -463,6 +480,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses")
assert length(json_response(res_conn, 200)) == 1
+ assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses")
@@ -476,9 +494,11 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses")
assert length(json_response(res_conn, 200)) == 1
+ assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses")
assert length(json_response(res_conn, 200)) == 1
+ assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
end
end
--
cgit v1.2.3
From bd6e2b300f82e66afb121c2339c3cbbfb0b1a446 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 8 Apr 2020 23:16:20 +0400
Subject: Add spec for AccountController.followers
---
test/web/mastodon_api/controllers/account_controller_test.exs | 4 ++++
1 file changed, 4 insertions(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 969256fa4..79b3adc69 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -513,6 +513,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(user.id)
+ assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
end
test "getting followers, hide_followers", %{user: user, conn: conn} do
@@ -536,6 +537,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> get("/api/v1/accounts/#{other_user.id}/followers")
refute [] == json_response(conn, 200)
+ assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
end
test "getting followers, pagination", %{user: user, conn: conn} do
@@ -551,6 +553,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert [%{"id" => id3}, %{"id" => id2}] = json_response(res_conn, 200)
assert id3 == follower3.id
assert id2 == follower2.id
+ assert_schema(json_response(res_conn, 200), "AccountsResponse", ApiSpec.spec())
res_conn = get(conn, "/api/v1/accounts/#{user.id}/followers?max_id=#{follower3.id}")
@@ -566,6 +569,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert [link_header] = get_resp_header(res_conn, "link")
assert link_header =~ ~r/min_id=#{follower2.id}/
assert link_header =~ ~r/max_id=#{follower2.id}/
+ assert_schema(json_response(res_conn, 200), "AccountsResponse", ApiSpec.spec())
end
end
--
cgit v1.2.3
From e105cc12b67e44eb4e19293b850731f300999a4f Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 8 Apr 2020 23:38:07 +0400
Subject: Add spec for AccountController.following
---
test/web/mastodon_api/controllers/account_controller_test.exs | 5 +++++
1 file changed, 5 insertions(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 79b3adc69..341c9b015 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -584,6 +584,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(other_user.id)
+ assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
end
test "getting following, hide_follows, other user requesting" do
@@ -598,6 +599,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> get("/api/v1/accounts/#{user.id}/following")
assert [] == json_response(conn, 200)
+ assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
end
test "getting following, hide_follows, same user requesting" do
@@ -627,12 +629,14 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert [%{"id" => id3}, %{"id" => id2}] = json_response(res_conn, 200)
assert id3 == following3.id
assert id2 == following2.id
+ assert_schema(json_response(res_conn, 200), "AccountsResponse", ApiSpec.spec())
res_conn = get(conn, "/api/v1/accounts/#{user.id}/following?max_id=#{following3.id}")
assert [%{"id" => id2}, %{"id" => id1}] = json_response(res_conn, 200)
assert id2 == following2.id
assert id1 == following1.id
+ assert_schema(json_response(res_conn, 200), "AccountsResponse", ApiSpec.spec())
res_conn =
get(conn, "/api/v1/accounts/#{user.id}/following?limit=1&max_id=#{following3.id}")
@@ -643,6 +647,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert [link_header] = get_resp_header(res_conn, "link")
assert link_header =~ ~r/min_id=#{following2.id}/
assert link_header =~ ~r/max_id=#{following2.id}/
+ assert_schema(json_response(res_conn, 200), "AccountsResponse", ApiSpec.spec())
end
end
--
cgit v1.2.3
From 1b680a98ae15035215fa8489f825af72532340c4 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 8 Apr 2020 23:51:46 +0400
Subject: Add spec for AccountController.lists
---
test/web/mastodon_api/controllers/account_controller_test.exs | 1 +
1 file changed, 1 insertion(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 341c9b015..706eea5d9 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -1051,6 +1051,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> json_response(200)
assert res == [%{"id" => to_string(list.id), "title" => "Test List"}]
+ assert_schema(res, "ListsResponse", ApiSpec.spec())
end
end
--
cgit v1.2.3
From 854780c72bc90a55d7005a05861d45771c5aeadf Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 9 Apr 2020 15:25:24 +0400
Subject: Add spec for AccountController.follow
---
test/web/mastodon_api/controllers/account_controller_test.exs | 1 +
1 file changed, 1 insertion(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 706eea5d9..7a3d58600 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -669,6 +669,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert %{"id" => id} = json_response(conn, 200)
assert id == to_string(other_user.id)
+ assert_schema(json_response(conn, 200), "AccountRelationship", ApiSpec.spec())
end
test "cancelling follow request", %{conn: conn} do
--
cgit v1.2.3
From aa958a6dda7cdcf12e9cd9232e7c6be421610317 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 9 Apr 2020 17:57:21 +0400
Subject: Add spec for AccountController.unfollow
---
.../mastodon_api/controllers/account_controller_test.exs | 16 ++++++++++++----
1 file changed, 12 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 7a3d58600..d56e7fb4a 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -660,10 +660,12 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/follow")
assert %{"id" => _id, "following" => true} = json_response(ret_conn, 200)
+ assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/unfollow")
assert %{"id" => _id, "following" => false} = json_response(ret_conn, 200)
+ assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
conn = post(conn, "/api/v1/follows", %{"uri" => other_user.nickname})
@@ -675,11 +677,15 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "cancelling follow request", %{conn: conn} do
%{id: other_user_id} = insert(:user, %{locked: true})
- assert %{"id" => ^other_user_id, "following" => false, "requested" => true} =
- conn |> post("/api/v1/accounts/#{other_user_id}/follow") |> json_response(:ok)
+ resp = conn |> post("/api/v1/accounts/#{other_user_id}/follow") |> json_response(:ok)
- assert %{"id" => ^other_user_id, "following" => false, "requested" => false} =
- conn |> post("/api/v1/accounts/#{other_user_id}/unfollow") |> json_response(:ok)
+ assert %{"id" => ^other_user_id, "following" => false, "requested" => true} = resp
+ assert_schema(resp, "AccountRelationship", ApiSpec.spec())
+
+ resp = conn |> post("/api/v1/accounts/#{other_user_id}/unfollow") |> json_response(:ok)
+
+ assert %{"id" => ^other_user_id, "following" => false, "requested" => false} = resp
+ assert_schema(resp, "AccountRelationship", ApiSpec.spec())
end
test "following without reblogs" do
@@ -690,6 +696,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
ret_conn = post(conn, "/api/v1/accounts/#{followed.id}/follow?reblogs=false")
assert %{"showing_reblogs" => false} = json_response(ret_conn, 200)
+ assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "hey"})
{:ok, reblog, _} = CommonAPI.repeat(activity.id, followed)
@@ -701,6 +708,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
ret_conn = post(conn, "/api/v1/accounts/#{followed.id}/follow?reblogs=true")
assert %{"showing_reblogs" => true} = json_response(ret_conn, 200)
+ assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
conn = get(conn, "/api/v1/timelines/home")
--
cgit v1.2.3
From e4195d4a684908d58482f9c865375a080e7b78bc Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 9 Apr 2020 18:28:14 +0400
Subject: Add specs for AccountController.mute and AccountController.unmute
---
.../mastodon_api/controllers/account_controller_test.exs | 13 +++++++++++--
1 file changed, 11 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index d56e7fb4a..91d4685cb 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -751,32 +751,41 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "with notifications", %{conn: conn} do
other_user = insert(:user)
- ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/mute")
+ ret_conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/accounts/#{other_user.id}/mute")
response = json_response(ret_conn, 200)
assert %{"id" => _id, "muting" => true, "muting_notifications" => true} = response
+ assert_schema(response, "AccountRelationship", ApiSpec.spec())
conn = post(conn, "/api/v1/accounts/#{other_user.id}/unmute")
response = json_response(conn, 200)
assert %{"id" => _id, "muting" => false, "muting_notifications" => false} = response
+ assert_schema(response, "AccountRelationship", ApiSpec.spec())
end
test "without notifications", %{conn: conn} do
other_user = insert(:user)
ret_conn =
- post(conn, "/api/v1/accounts/#{other_user.id}/mute", %{"notifications" => "false"})
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/v1/accounts/#{other_user.id}/mute", %{"notifications" => "false"})
response = json_response(ret_conn, 200)
assert %{"id" => _id, "muting" => true, "muting_notifications" => false} = response
+ assert_schema(response, "AccountRelationship", ApiSpec.spec())
conn = post(conn, "/api/v1/accounts/#{other_user.id}/unmute")
response = json_response(conn, 200)
assert %{"id" => _id, "muting" => false, "muting_notifications" => false} = response
+ assert_schema(response, "AccountRelationship", ApiSpec.spec())
end
end
--
cgit v1.2.3
From 68a979b8243b9a5b685df2c13388a93b9ede1900 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 9 Apr 2020 18:41:18 +0400
Subject: Add specs for AccountController.block and AccountController.unblock
---
test/web/mastodon_api/controllers/account_controller_test.exs | 2 ++
1 file changed, 2 insertions(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 91d4685cb..f71b54ade 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -819,10 +819,12 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/block")
assert %{"id" => _id, "blocking" => true} = json_response(ret_conn, 200)
+ assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
conn = post(conn, "/api/v1/accounts/#{other_user.id}/unblock")
assert %{"id" => _id, "blocking" => false} = json_response(conn, 200)
+ assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
end
describe "create account by app" do
--
cgit v1.2.3
From ab185d3ea47deb38128dc501acdf27c47c542de2 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 9 Apr 2020 20:12:09 +0400
Subject: Add spec for AccountController.follows
---
.../controllers/account_controller_test.exs | 20 ++++++++++++++++----
1 file changed, 16 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index f71b54ade..fa2091c5e 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -667,11 +667,14 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert %{"id" => _id, "following" => false} = json_response(ret_conn, 200)
assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
- conn = post(conn, "/api/v1/follows", %{"uri" => other_user.nickname})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/follows", %{"uri" => other_user.nickname})
assert %{"id" => id} = json_response(conn, 200)
assert id == to_string(other_user.id)
- assert_schema(json_response(conn, 200), "AccountRelationship", ApiSpec.spec())
+ assert_schema(json_response(conn, 200), "Account", ApiSpec.spec())
end
test "cancelling follow request", %{conn: conn} do
@@ -728,7 +731,12 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
# self follow via uri
user = User.get_cached_by_id(user.id)
- conn_res = post(conn, "/api/v1/follows", %{"uri" => user.nickname})
+
+ conn_res =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/v1/follows", %{"uri" => user.nickname})
+
assert %{"error" => "Record not found"} = json_response(conn_res, 404)
# follow non existing user
@@ -736,7 +744,11 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert %{"error" => "Record not found"} = json_response(conn_res, 404)
# follow non existing user via uri
- conn_res = post(conn, "/api/v1/follows", %{"uri" => "doesntexist"})
+ conn_res =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/v1/follows", %{"uri" => "doesntexist"})
+
assert %{"error" => "Record not found"} = json_response(conn_res, 404)
# unfollow non existing user
--
cgit v1.2.3
From 7e0b42d99f3eb9520bc29cc29c06512c55183482 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 9 Apr 2020 20:34:21 +0400
Subject: Add specs for AccountController.mutes, AccountController.blocks,
AccountController.mutes, AccountController.endorsements
---
test/web/mastodon_api/controllers/account_controller_test.exs | 2 ++
1 file changed, 2 insertions(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index fa2091c5e..86136f7e4 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -1155,6 +1155,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
other_user_id = to_string(other_user.id)
assert [%{"id" => ^other_user_id}] = json_response(conn, 200)
+ assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
end
test "getting a list of blocks" do
@@ -1170,5 +1171,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
other_user_id = to_string(other_user.id)
assert [%{"id" => ^other_user_id}] = json_response(conn, 200)
+ assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
end
end
--
cgit v1.2.3
From c28aaf9d82a781508eba886bd455767a110d1b7c Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 13 Apr 2020 21:21:04 +0400
Subject: Add OpenAPI spec for CustomEmojiController
---
.../controllers/custom_emoji_controller_test.exs | 27 ++++++++++++++++++----
1 file changed, 23 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs b/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs
index 6567a0667..0b2ffa470 100644
--- a/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs
+++ b/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs
@@ -4,13 +4,18 @@
defmodule Pleroma.Web.MastodonAPI.CustomEmojiControllerTest do
use Pleroma.Web.ConnCase, async: true
+ alias Pleroma.Web.ApiSpec
+ alias Pleroma.Web.ApiSpec.Schemas.CustomEmoji
+ alias Pleroma.Web.ApiSpec.Schemas.CustomEmojisResponse
+ import OpenApiSpex.TestAssertions
test "with tags", %{conn: conn} do
- [emoji | _body] =
- conn
- |> get("/api/v1/custom_emojis")
- |> json_response(200)
+ assert resp =
+ conn
+ |> get("/api/v1/custom_emojis")
+ |> json_response(200)
+ assert [emoji | _body] = resp
assert Map.has_key?(emoji, "shortcode")
assert Map.has_key?(emoji, "static_url")
assert Map.has_key?(emoji, "tags")
@@ -18,5 +23,19 @@ defmodule Pleroma.Web.MastodonAPI.CustomEmojiControllerTest do
assert Map.has_key?(emoji, "category")
assert Map.has_key?(emoji, "url")
assert Map.has_key?(emoji, "visible_in_picker")
+ assert_schema(resp, "CustomEmojisResponse", ApiSpec.spec())
+ assert_schema(emoji, "CustomEmoji", ApiSpec.spec())
+ end
+
+ test "CustomEmoji example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = CustomEmoji.schema()
+ assert_schema(schema.example, "CustomEmoji", api_spec)
+ end
+
+ test "CustomEmojisResponse example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = CustomEmojisResponse.schema()
+ assert_schema(schema.example, "CustomEmojisResponse", api_spec)
end
end
--
cgit v1.2.3
From 4dca712e90a81a1a754608eb4f8e22dae99eb755 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 13 Apr 2020 22:44:52 +0400
Subject: Add OpenAPI spec for DomainBlockController
---
.../controllers/domain_block_controller_test.exs | 20 ++++++++++++++++++--
1 file changed, 18 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/domain_block_controller_test.exs b/test/web/mastodon_api/controllers/domain_block_controller_test.exs
index 8d24b3b88..d66190c90 100644
--- a/test/web/mastodon_api/controllers/domain_block_controller_test.exs
+++ b/test/web/mastodon_api/controllers/domain_block_controller_test.exs
@@ -6,20 +6,29 @@ defmodule Pleroma.Web.MastodonAPI.DomainBlockControllerTest do
use Pleroma.Web.ConnCase
alias Pleroma.User
+ alias Pleroma.Web.ApiSpec
+ alias Pleroma.Web.ApiSpec.Schemas.DomainBlocksResponse
import Pleroma.Factory
+ import OpenApiSpex.TestAssertions
test "blocking / unblocking a domain" do
%{user: user, conn: conn} = oauth_access(["write:blocks"])
other_user = insert(:user, %{ap_id: "https://dogwhistle.zone/@pundit"})
- ret_conn = post(conn, "/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"})
+ ret_conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"})
assert %{} = json_response(ret_conn, 200)
user = User.get_cached_by_ap_id(user.ap_id)
assert User.blocks?(user, other_user)
- ret_conn = delete(conn, "/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"})
+ ret_conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> delete("/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"})
assert %{} = json_response(ret_conn, 200)
user = User.get_cached_by_ap_id(user.ap_id)
@@ -41,5 +50,12 @@ defmodule Pleroma.Web.MastodonAPI.DomainBlockControllerTest do
assert "bad.site" in domain_blocks
assert "even.worse.site" in domain_blocks
+ assert_schema(domain_blocks, "DomainBlocksResponse", ApiSpec.spec())
+ end
+
+ test "DomainBlocksResponse example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = DomainBlocksResponse.schema()
+ assert_schema(schema.example, "DomainBlocksResponse", api_spec)
end
end
--
cgit v1.2.3
From 4576520461e2e3a1c78133aaf31cb742a2a1a689 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 14 Apr 2020 16:32:22 +0000
Subject: Revert "Merge branch 'issue/1276' into 'develop'"
This reverts merge request !1877
---
test/marker_test.exs | 29 +---------------------
test/notification_test.exs | 13 ----------
.../controllers/marker_controller_test.exs | 10 +++-----
test/web/mastodon_api/views/marker_view_test.exs | 8 +++---
4 files changed, 7 insertions(+), 53 deletions(-)
(limited to 'test')
diff --git a/test/marker_test.exs b/test/marker_test.exs
index 5b6d0b4a4..c80ae16b6 100644
--- a/test/marker_test.exs
+++ b/test/marker_test.exs
@@ -8,39 +8,12 @@ defmodule Pleroma.MarkerTest do
import Pleroma.Factory
- describe "multi_set_unread_count/3" do
- test "returns multi" do
- user = insert(:user)
-
- assert %Ecto.Multi{
- operations: [marker: {:run, _}, counters: {:run, _}]
- } =
- Marker.multi_set_last_read_id(
- Ecto.Multi.new(),
- user,
- "notifications"
- )
- end
-
- test "return empty multi" do
- user = insert(:user)
- multi = Ecto.Multi.new()
- assert Marker.multi_set_last_read_id(multi, user, "home") == multi
- end
- end
-
describe "get_markers/2" do
test "returns user markers" do
user = insert(:user)
marker = insert(:marker, user: user)
- insert(:notification, user: user)
- insert(:notification, user: user)
insert(:marker, timeline: "home", user: user)
-
- assert Marker.get_markers(
- user,
- ["notifications"]
- ) == [%Marker{refresh_record(marker) | unread_count: 2}]
+ assert Marker.get_markers(user, ["notifications"]) == [refresh_record(marker)]
end
end
diff --git a/test/notification_test.exs b/test/notification_test.exs
index f78a47af6..837a9dacd 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -45,9 +45,6 @@ defmodule Pleroma.NotificationTest do
assert notified_ids == [other_user.id, third_user.id]
assert notification.activity_id == activity.id
assert other_notification.activity_id == activity.id
-
- assert [%Pleroma.Marker{unread_count: 2}] =
- Pleroma.Marker.get_markers(other_user, ["notifications"])
end
test "it creates a notification for subscribed users" do
@@ -413,16 +410,6 @@ defmodule Pleroma.NotificationTest do
assert n1.seen == true
assert n2.seen == true
assert n3.seen == false
-
- assert %Pleroma.Marker{} =
- m =
- Pleroma.Repo.get_by(
- Pleroma.Marker,
- user_id: other_user.id,
- timeline: "notifications"
- )
-
- assert m.last_read_id == to_string(n2.id)
end
end
diff --git a/test/web/mastodon_api/controllers/marker_controller_test.exs b/test/web/mastodon_api/controllers/marker_controller_test.exs
index 7280abd10..919f295bd 100644
--- a/test/web/mastodon_api/controllers/marker_controller_test.exs
+++ b/test/web/mastodon_api/controllers/marker_controller_test.exs
@@ -11,7 +11,6 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
test "gets markers with correct scopes", %{conn: conn} do
user = insert(:user)
token = insert(:oauth_token, user: user, scopes: ["read:statuses"])
- insert_list(7, :notification, user: user)
{:ok, %{"notifications" => marker}} =
Pleroma.Marker.upsert(
@@ -30,8 +29,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"notifications" => %{
"last_read_id" => "69420",
"updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
- "version" => 0,
- "pleroma" => %{"unread_count" => 7}
+ "version" => 0
}
}
end
@@ -72,8 +70,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"notifications" => %{
"last_read_id" => "69420",
"updated_at" => _,
- "version" => 0,
- "pleroma" => %{"unread_count" => 0}
+ "version" => 0
}
} = response
end
@@ -102,8 +99,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"notifications" => %{
"last_read_id" => "69888",
"updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
- "version" => 0,
- "pleroma" => %{"unread_count" => 0}
+ "version" => 0
}
}
end
diff --git a/test/web/mastodon_api/views/marker_view_test.exs b/test/web/mastodon_api/views/marker_view_test.exs
index 48a0a6d33..893cf8857 100644
--- a/test/web/mastodon_api/views/marker_view_test.exs
+++ b/test/web/mastodon_api/views/marker_view_test.exs
@@ -8,21 +8,19 @@ defmodule Pleroma.Web.MastodonAPI.MarkerViewTest do
import Pleroma.Factory
test "returns markers" do
- marker1 = insert(:marker, timeline: "notifications", last_read_id: "17", unread_count: 5)
+ marker1 = insert(:marker, timeline: "notifications", last_read_id: "17")
marker2 = insert(:marker, timeline: "home", last_read_id: "42")
assert MarkerView.render("markers.json", %{markers: [marker1, marker2]}) == %{
"home" => %{
last_read_id: "42",
updated_at: NaiveDateTime.to_iso8601(marker2.updated_at),
- version: 0,
- pleroma: %{unread_count: 0}
+ version: 0
},
"notifications" => %{
last_read_id: "17",
updated_at: NaiveDateTime.to_iso8601(marker1.updated_at),
- version: 0,
- pleroma: %{unread_count: 5}
+ version: 0
}
}
end
--
cgit v1.2.3
From 22bde21c4f1a84a1fbe733070e8926366a3c01dc Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 15 Apr 2020 15:27:34 +0300
Subject: remote_ip plug adds remote_ip_found flag
---
test/plugs/rate_limiter_test.exs | 31 ++++++++++++++++++++-----------
1 file changed, 20 insertions(+), 11 deletions(-)
(limited to 'test')
diff --git a/test/plugs/rate_limiter_test.exs b/test/plugs/rate_limiter_test.exs
index 0ce9f3a0a..4d3d694f4 100644
--- a/test/plugs/rate_limiter_test.exs
+++ b/test/plugs/rate_limiter_test.exs
@@ -5,8 +5,10 @@
defmodule Pleroma.Plugs.RateLimiterTest do
use Pleroma.Web.ConnCase
+ alias Phoenix.ConnTest
alias Pleroma.Config
alias Pleroma.Plugs.RateLimiter
+ alias Plug.Conn
import Pleroma.Factory
import Pleroma.Tests.Helpers, only: [clear_config: 1, clear_config: 2]
@@ -36,8 +38,15 @@ defmodule Pleroma.Plugs.RateLimiterTest do
end
test "it is disabled if it remote ip plug is enabled but no remote ip is found" do
- Config.put([Pleroma.Web.Endpoint, :http, :ip], {127, 0, 0, 1})
- assert RateLimiter.disabled?(Plug.Conn.assign(build_conn(), :remote_ip_found, false))
+ assert RateLimiter.disabled?(Conn.assign(build_conn(), :remote_ip_found, false))
+ end
+
+ test "it is enabled if remote ip found" do
+ refute RateLimiter.disabled?(Conn.assign(build_conn(), :remote_ip_found, true))
+ end
+
+ test "it is enabled if remote_ip_found flag doesn't exist" do
+ refute RateLimiter.disabled?(build_conn())
end
test "it restricts based on config values" do
@@ -58,7 +67,7 @@ defmodule Pleroma.Plugs.RateLimiterTest do
end
conn = RateLimiter.call(conn, plug_opts)
- assert %{"error" => "Throttled"} = Phoenix.ConnTest.json_response(conn, :too_many_requests)
+ assert %{"error" => "Throttled"} = ConnTest.json_response(conn, :too_many_requests)
assert conn.halted
Process.sleep(50)
@@ -68,7 +77,7 @@ defmodule Pleroma.Plugs.RateLimiterTest do
conn = RateLimiter.call(conn, plug_opts)
assert {1, 4} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts)
- refute conn.status == Plug.Conn.Status.code(:too_many_requests)
+ refute conn.status == Conn.Status.code(:too_many_requests)
refute conn.resp_body
refute conn.halted
end
@@ -98,7 +107,7 @@ defmodule Pleroma.Plugs.RateLimiterTest do
plug_opts = RateLimiter.init(name: limiter_name, params: ["id"])
conn = build_conn(:get, "/?id=1")
- conn = Plug.Conn.fetch_query_params(conn)
+ conn = Conn.fetch_query_params(conn)
conn_2 = build_conn(:get, "/?id=2")
RateLimiter.call(conn, plug_opts)
@@ -119,7 +128,7 @@ defmodule Pleroma.Plugs.RateLimiterTest do
id = "100"
conn = build_conn(:get, "/?id=#{id}")
- conn = Plug.Conn.fetch_query_params(conn)
+ conn = Conn.fetch_query_params(conn)
conn_2 = build_conn(:get, "/?id=#{101}")
RateLimiter.call(conn, plug_opts)
@@ -147,13 +156,13 @@ defmodule Pleroma.Plugs.RateLimiterTest do
conn = RateLimiter.call(conn, plug_opts)
- assert %{"error" => "Throttled"} = Phoenix.ConnTest.json_response(conn, :too_many_requests)
+ assert %{"error" => "Throttled"} = ConnTest.json_response(conn, :too_many_requests)
assert conn.halted
conn_2 = RateLimiter.call(conn_2, plug_opts)
assert {1, 4} = RateLimiter.inspect_bucket(conn_2, limiter_name, plug_opts)
- refute conn_2.status == Plug.Conn.Status.code(:too_many_requests)
+ refute conn_2.status == Conn.Status.code(:too_many_requests)
refute conn_2.resp_body
refute conn_2.halted
end
@@ -187,7 +196,7 @@ defmodule Pleroma.Plugs.RateLimiterTest do
conn = RateLimiter.call(conn, plug_opts)
- assert %{"error" => "Throttled"} = Phoenix.ConnTest.json_response(conn, :too_many_requests)
+ assert %{"error" => "Throttled"} = ConnTest.json_response(conn, :too_many_requests)
assert conn.halted
end
@@ -210,12 +219,12 @@ defmodule Pleroma.Plugs.RateLimiterTest do
end
conn = RateLimiter.call(conn, plug_opts)
- assert %{"error" => "Throttled"} = Phoenix.ConnTest.json_response(conn, :too_many_requests)
+ assert %{"error" => "Throttled"} = ConnTest.json_response(conn, :too_many_requests)
assert conn.halted
conn_2 = RateLimiter.call(conn_2, plug_opts)
assert {1, 4} = RateLimiter.inspect_bucket(conn_2, limiter_name, plug_opts)
- refute conn_2.status == Plug.Conn.Status.code(:too_many_requests)
+ refute conn_2.status == Conn.Status.code(:too_many_requests)
refute conn_2.resp_body
refute conn_2.halted
end
--
cgit v1.2.3
From bde1189c349dc114aca2e9310dda840a1007825f Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Wed, 15 Apr 2020 21:19:16 +0300
Subject: [#2349] Made :skip_plug/2 prevent plug from being executed even if
explicitly called. Refactoring. Tests.
---
test/plugs/oauth_scopes_plug_test.exs | 13 ++++++++
test/web/auth/oauth_test_controller_test.exs | 49 ++++++++++++++++++++++++++++
2 files changed, 62 insertions(+)
create mode 100644 test/web/auth/oauth_test_controller_test.exs
(limited to 'test')
diff --git a/test/plugs/oauth_scopes_plug_test.exs b/test/plugs/oauth_scopes_plug_test.exs
index e79ecf263..abab7abb0 100644
--- a/test/plugs/oauth_scopes_plug_test.exs
+++ b/test/plugs/oauth_scopes_plug_test.exs
@@ -7,6 +7,7 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do
alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Plugs.OAuthScopesPlug
+ alias Pleroma.Plugs.PlugHelper
alias Pleroma.Repo
import Mock
@@ -16,6 +17,18 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do
:ok
end
+ test "is not performed if marked as skipped", %{conn: conn} do
+ with_mock OAuthScopesPlug, [:passthrough], perform: &passthrough([&1, &2]) do
+ conn =
+ conn
+ |> PlugHelper.append_to_skipped_plugs(OAuthScopesPlug)
+ |> OAuthScopesPlug.call(%{scopes: ["random_scope"]})
+
+ refute called(OAuthScopesPlug.perform(:_, :_))
+ refute conn.halted
+ end
+ end
+
test "if `token.scopes` fulfills specified 'any of' conditions, " <>
"proceeds with no op",
%{conn: conn} do
diff --git a/test/web/auth/oauth_test_controller_test.exs b/test/web/auth/oauth_test_controller_test.exs
new file mode 100644
index 000000000..a2f6009ac
--- /dev/null
+++ b/test/web/auth/oauth_test_controller_test.exs
@@ -0,0 +1,49 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Tests.OAuthTestControllerTest do
+ use Pleroma.Web.ConnCase
+
+ import Pleroma.Factory
+
+ setup %{conn: conn} do
+ user = insert(:user)
+ conn = assign(conn, :user, user)
+ %{conn: conn, user: user}
+ end
+
+ test "missed_oauth", %{conn: conn} do
+ res =
+ conn
+ |> get("/test/authenticated_api/missed_oauth")
+ |> json_response(403)
+
+ assert res ==
+ %{
+ "error" =>
+ "Security violation: OAuth scopes check was neither handled nor explicitly skipped."
+ }
+ end
+
+ test "skipped_oauth", %{conn: conn} do
+ conn
+ |> assign(:token, nil)
+ |> get("/test/authenticated_api/skipped_oauth")
+ |> json_response(200)
+ end
+
+ test "performed_oauth", %{user: user} do
+ %{conn: good_token_conn} = oauth_access(["read"], user: user)
+
+ good_token_conn
+ |> get("/test/authenticated_api/performed_oauth")
+ |> json_response(200)
+
+ %{conn: bad_token_conn} = oauth_access(["follow"], user: user)
+
+ bad_token_conn
+ |> get("/test/authenticated_api/performed_oauth")
+ |> json_response(403)
+ end
+end
--
cgit v1.2.3
From 4b3b1fec4e57bd07ac75700bf34cd188ce43b545 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Wed, 15 Apr 2020 21:19:43 +0300
Subject: added an endpoint for getting unread notification count
---
test/marker_test.exs | 29 +++++++++++++++++++++-
test/notification_test.exs | 13 ++++++++++
.../controllers/marker_controller_test.exs | 10 +++++---
test/web/mastodon_api/views/marker_view_test.exs | 8 +++---
4 files changed, 53 insertions(+), 7 deletions(-)
(limited to 'test')
diff --git a/test/marker_test.exs b/test/marker_test.exs
index c80ae16b6..5b6d0b4a4 100644
--- a/test/marker_test.exs
+++ b/test/marker_test.exs
@@ -8,12 +8,39 @@ defmodule Pleroma.MarkerTest do
import Pleroma.Factory
+ describe "multi_set_unread_count/3" do
+ test "returns multi" do
+ user = insert(:user)
+
+ assert %Ecto.Multi{
+ operations: [marker: {:run, _}, counters: {:run, _}]
+ } =
+ Marker.multi_set_last_read_id(
+ Ecto.Multi.new(),
+ user,
+ "notifications"
+ )
+ end
+
+ test "return empty multi" do
+ user = insert(:user)
+ multi = Ecto.Multi.new()
+ assert Marker.multi_set_last_read_id(multi, user, "home") == multi
+ end
+ end
+
describe "get_markers/2" do
test "returns user markers" do
user = insert(:user)
marker = insert(:marker, user: user)
+ insert(:notification, user: user)
+ insert(:notification, user: user)
insert(:marker, timeline: "home", user: user)
- assert Marker.get_markers(user, ["notifications"]) == [refresh_record(marker)]
+
+ assert Marker.get_markers(
+ user,
+ ["notifications"]
+ ) == [%Marker{refresh_record(marker) | unread_count: 2}]
end
end
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 837a9dacd..f78a47af6 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -45,6 +45,9 @@ defmodule Pleroma.NotificationTest do
assert notified_ids == [other_user.id, third_user.id]
assert notification.activity_id == activity.id
assert other_notification.activity_id == activity.id
+
+ assert [%Pleroma.Marker{unread_count: 2}] =
+ Pleroma.Marker.get_markers(other_user, ["notifications"])
end
test "it creates a notification for subscribed users" do
@@ -410,6 +413,16 @@ defmodule Pleroma.NotificationTest do
assert n1.seen == true
assert n2.seen == true
assert n3.seen == false
+
+ assert %Pleroma.Marker{} =
+ m =
+ Pleroma.Repo.get_by(
+ Pleroma.Marker,
+ user_id: other_user.id,
+ timeline: "notifications"
+ )
+
+ assert m.last_read_id == to_string(n2.id)
end
end
diff --git a/test/web/mastodon_api/controllers/marker_controller_test.exs b/test/web/mastodon_api/controllers/marker_controller_test.exs
index 919f295bd..7280abd10 100644
--- a/test/web/mastodon_api/controllers/marker_controller_test.exs
+++ b/test/web/mastodon_api/controllers/marker_controller_test.exs
@@ -11,6 +11,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
test "gets markers with correct scopes", %{conn: conn} do
user = insert(:user)
token = insert(:oauth_token, user: user, scopes: ["read:statuses"])
+ insert_list(7, :notification, user: user)
{:ok, %{"notifications" => marker}} =
Pleroma.Marker.upsert(
@@ -29,7 +30,8 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"notifications" => %{
"last_read_id" => "69420",
"updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
- "version" => 0
+ "version" => 0,
+ "pleroma" => %{"unread_count" => 7}
}
}
end
@@ -70,7 +72,8 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"notifications" => %{
"last_read_id" => "69420",
"updated_at" => _,
- "version" => 0
+ "version" => 0,
+ "pleroma" => %{"unread_count" => 0}
}
} = response
end
@@ -99,7 +102,8 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"notifications" => %{
"last_read_id" => "69888",
"updated_at" => NaiveDateTime.to_iso8601(marker.updated_at),
- "version" => 0
+ "version" => 0,
+ "pleroma" => %{"unread_count" => 0}
}
}
end
diff --git a/test/web/mastodon_api/views/marker_view_test.exs b/test/web/mastodon_api/views/marker_view_test.exs
index 893cf8857..48a0a6d33 100644
--- a/test/web/mastodon_api/views/marker_view_test.exs
+++ b/test/web/mastodon_api/views/marker_view_test.exs
@@ -8,19 +8,21 @@ defmodule Pleroma.Web.MastodonAPI.MarkerViewTest do
import Pleroma.Factory
test "returns markers" do
- marker1 = insert(:marker, timeline: "notifications", last_read_id: "17")
+ marker1 = insert(:marker, timeline: "notifications", last_read_id: "17", unread_count: 5)
marker2 = insert(:marker, timeline: "home", last_read_id: "42")
assert MarkerView.render("markers.json", %{markers: [marker1, marker2]}) == %{
"home" => %{
last_read_id: "42",
updated_at: NaiveDateTime.to_iso8601(marker2.updated_at),
- version: 0
+ version: 0,
+ pleroma: %{unread_count: 0}
},
"notifications" => %{
last_read_id: "17",
updated_at: NaiveDateTime.to_iso8601(marker1.updated_at),
- version: 0
+ version: 0,
+ pleroma: %{unread_count: 5}
}
}
end
--
cgit v1.2.3
From cf4ebba77471f188ce7da45df0b9ea76dbe31916 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 15 Apr 2020 22:59:25 +0400
Subject: Cleanup SubscriptionController
---
.../controllers/subscription_controller_test.exs | 13 +++++++-----
.../views/push_subscription_view_test.exs | 23 ----------------------
.../mastodon_api/views/subscription_view_test.exs | 23 ++++++++++++++++++++++
3 files changed, 31 insertions(+), 28 deletions(-)
delete mode 100644 test/web/mastodon_api/views/push_subscription_view_test.exs
create mode 100644 test/web/mastodon_api/views/subscription_view_test.exs
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/subscription_controller_test.exs b/test/web/mastodon_api/controllers/subscription_controller_test.exs
index 987158a74..5682498c0 100644
--- a/test/web/mastodon_api/controllers/subscription_controller_test.exs
+++ b/test/web/mastodon_api/controllers/subscription_controller_test.exs
@@ -35,7 +35,10 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
quote do
vapid_details = Application.get_env(:web_push_encryption, :vapid_details, [])
Application.put_env(:web_push_encryption, :vapid_details, [])
- assert "Something went wrong" == unquote(yield)
+
+ assert %{"error" => "Web push subscription is disabled on this Pleroma instance"} ==
+ unquote(yield)
+
Application.put_env(:web_push_encryption, :vapid_details, vapid_details)
end
end
@@ -45,7 +48,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
assert_error_when_disable_push do
conn
|> post("/api/v1/push/subscription", %{})
- |> json_response(500)
+ |> json_response(403)
end
end
@@ -74,7 +77,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
assert_error_when_disable_push do
conn
|> get("/api/v1/push/subscription", %{})
- |> json_response(500)
+ |> json_response(403)
end
end
@@ -127,7 +130,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
assert_error_when_disable_push do
conn
|> put("/api/v1/push/subscription", %{data: %{"alerts" => %{"mention" => false}}})
- |> json_response(500)
+ |> json_response(403)
end
end
@@ -155,7 +158,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
assert_error_when_disable_push do
conn
|> delete("/api/v1/push/subscription", %{})
- |> json_response(500)
+ |> json_response(403)
end
end
diff --git a/test/web/mastodon_api/views/push_subscription_view_test.exs b/test/web/mastodon_api/views/push_subscription_view_test.exs
deleted file mode 100644
index 10c6082a5..000000000
--- a/test/web/mastodon_api/views/push_subscription_view_test.exs
+++ /dev/null
@@ -1,23 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Web.MastodonAPI.PushSubscriptionViewTest do
- use Pleroma.DataCase
- import Pleroma.Factory
- alias Pleroma.Web.MastodonAPI.PushSubscriptionView, as: View
- alias Pleroma.Web.Push
-
- test "Represent a subscription" do
- subscription = insert(:push_subscription, data: %{"alerts" => %{"mention" => true}})
-
- expected = %{
- alerts: %{"mention" => true},
- endpoint: subscription.endpoint,
- id: to_string(subscription.id),
- server_key: Keyword.get(Push.vapid_config(), :public_key)
- }
-
- assert expected == View.render("push_subscription.json", %{subscription: subscription})
- end
-end
diff --git a/test/web/mastodon_api/views/subscription_view_test.exs b/test/web/mastodon_api/views/subscription_view_test.exs
new file mode 100644
index 000000000..981524c0e
--- /dev/null
+++ b/test/web/mastodon_api/views/subscription_view_test.exs
@@ -0,0 +1,23 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.MastodonAPI.SubscriptionViewTest do
+ use Pleroma.DataCase
+ import Pleroma.Factory
+ alias Pleroma.Web.MastodonAPI.SubscriptionView, as: View
+ alias Pleroma.Web.Push
+
+ test "Represent a subscription" do
+ subscription = insert(:push_subscription, data: %{"alerts" => %{"mention" => true}})
+
+ expected = %{
+ alerts: %{"mention" => true},
+ endpoint: subscription.endpoint,
+ id: to_string(subscription.id),
+ server_key: Keyword.get(Push.vapid_config(), :public_key)
+ }
+
+ assert expected == View.render("show.json", %{subscription: subscription})
+ end
+end
--
cgit v1.2.3
From 72ef6cc4f2f601e26ba84c16ad2c91bd72867629 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Mon, 13 Apr 2020 14:07:23 +0300
Subject: added need_reboot endpoint to admin api
---
test/web/admin_api/admin_api_controller_test.exs | 18 ++++++++++++++++--
1 file changed, 16 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 60ec895f5..158966365 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -2110,7 +2110,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
|> get("/api/pleroma/admin/config")
|> json_response(200)
- refute Map.has_key?(configs, "need_reboot")
+ assert configs["need_reboot"] == false
end
test "update setting which need reboot, don't change reboot flag until reboot", %{conn: conn} do
@@ -2166,7 +2166,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
|> get("/api/pleroma/admin/config")
|> json_response(200)
- refute Map.has_key?(configs, "need_reboot")
+ assert configs["need_reboot"] == false
end
test "saving config with nested merge", %{conn: conn} do
@@ -2861,6 +2861,20 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
end
+ test "need_reboot flag", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/admin/need_reboot")
+ |> json_response(200) == %{"need_reboot" => false}
+
+ Restarter.Pleroma.need_reboot()
+
+ assert conn
+ |> get("/api/pleroma/admin/need_reboot")
+ |> json_response(200) == %{"need_reboot" => true}
+
+ on_exit(fn -> Restarter.Pleroma.refresh() end)
+ end
+
describe "GET /api/pleroma/admin/statuses" do
test "returns all public and unlisted statuses", %{conn: conn, admin: admin} do
blocked = insert(:user)
--
cgit v1.2.3
From 4d330d9df13b7ff5d24fdd8b4eec1e111fa51297 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Thu, 16 Apr 2020 18:05:36 +0300
Subject: fix for use of published from different entities
---
test/web/feed/tag_controller_test.exs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/feed/tag_controller_test.exs b/test/web/feed/tag_controller_test.exs
index e863df86b..d95aac108 100644
--- a/test/web/feed/tag_controller_test.exs
+++ b/test/web/feed/tag_controller_test.exs
@@ -150,8 +150,8 @@ defmodule Pleroma.Web.Feed.TagControllerTest do
obj2 = Object.normalize(activity2)
assert xpath(xml, ~x"//channel/item/description/text()"sl) == [
- HtmlEntities.decode(FeedView.activity_content(obj2)),
- HtmlEntities.decode(FeedView.activity_content(obj1))
+ HtmlEntities.decode(FeedView.activity_content(obj2.data)),
+ HtmlEntities.decode(FeedView.activity_content(obj1.data))
]
response =
--
cgit v1.2.3
From 304ea09f4c9902a1f96f30541e6c5d253527dd47 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Fri, 17 Apr 2020 08:42:48 +0300
Subject: fix for logger configuration
---
test/config/transfer_task_test.exs | 32 ++++++++++++--------------------
1 file changed, 12 insertions(+), 20 deletions(-)
(limited to 'test')
diff --git a/test/config/transfer_task_test.exs b/test/config/transfer_task_test.exs
index 0265a6156..00db0b686 100644
--- a/test/config/transfer_task_test.exs
+++ b/test/config/transfer_task_test.exs
@@ -16,6 +16,7 @@ defmodule Pleroma.Config.TransferTaskTest do
refute Application.get_env(:pleroma, :test_key)
refute Application.get_env(:idna, :test_key)
refute Application.get_env(:quack, :test_key)
+ initial = Application.get_env(:logger, :level)
ConfigDB.create(%{
group: ":pleroma",
@@ -35,16 +36,20 @@ defmodule Pleroma.Config.TransferTaskTest do
value: [:test_value1, :test_value2]
})
+ ConfigDB.create(%{group: ":logger", key: ":level", value: :debug})
+
TransferTask.start_link([])
assert Application.get_env(:pleroma, :test_key) == [live: 2, com: 3]
assert Application.get_env(:idna, :test_key) == [live: 15, com: 35]
assert Application.get_env(:quack, :test_key) == [:test_value1, :test_value2]
+ assert Application.get_env(:logger, :level) == :debug
on_exit(fn ->
Application.delete_env(:pleroma, :test_key)
Application.delete_env(:idna, :test_key)
Application.delete_env(:quack, :test_key)
+ Application.put_env(:logger, :level, initial)
end)
end
@@ -78,8 +83,8 @@ defmodule Pleroma.Config.TransferTaskTest do
end
test "transfer config values with full subkey update" do
- emoji = Application.get_env(:pleroma, :emoji)
- assets = Application.get_env(:pleroma, :assets)
+ clear_config(:emoji)
+ clear_config(:assets)
ConfigDB.create(%{
group: ":pleroma",
@@ -99,11 +104,6 @@ defmodule Pleroma.Config.TransferTaskTest do
assert emoji_env[:groups] == [a: 1, b: 2]
assets_env = Application.get_env(:pleroma, :assets)
assert assets_env[:mascots] == [a: 1, b: 2]
-
- on_exit(fn ->
- Application.put_env(:pleroma, :emoji, emoji)
- Application.put_env(:pleroma, :assets, assets)
- end)
end
describe "pleroma restart" do
@@ -112,8 +112,7 @@ defmodule Pleroma.Config.TransferTaskTest do
end
test "don't restart if no reboot time settings were changed" do
- emoji = Application.get_env(:pleroma, :emoji)
- on_exit(fn -> Application.put_env(:pleroma, :emoji, emoji) end)
+ clear_config(:emoji)
ConfigDB.create(%{
group: ":pleroma",
@@ -128,8 +127,7 @@ defmodule Pleroma.Config.TransferTaskTest do
end
test "on reboot time key" do
- chat = Application.get_env(:pleroma, :chat)
- on_exit(fn -> Application.put_env(:pleroma, :chat, chat) end)
+ clear_config(:chat)
ConfigDB.create(%{
group: ":pleroma",
@@ -141,8 +139,7 @@ defmodule Pleroma.Config.TransferTaskTest do
end
test "on reboot time subkey" do
- captcha = Application.get_env(:pleroma, Pleroma.Captcha)
- on_exit(fn -> Application.put_env(:pleroma, Pleroma.Captcha, captcha) end)
+ clear_config(Pleroma.Captcha)
ConfigDB.create(%{
group: ":pleroma",
@@ -154,13 +151,8 @@ defmodule Pleroma.Config.TransferTaskTest do
end
test "don't restart pleroma on reboot time key and subkey if there is false flag" do
- chat = Application.get_env(:pleroma, :chat)
- captcha = Application.get_env(:pleroma, Pleroma.Captcha)
-
- on_exit(fn ->
- Application.put_env(:pleroma, :chat, chat)
- Application.put_env(:pleroma, Pleroma.Captcha, captcha)
- end)
+ clear_config(:chat)
+ clear_config(Pleroma.Captcha)
ConfigDB.create(%{
group: ":pleroma",
--
cgit v1.2.3
From 6cda360fea8a42168b5835ef903cf3bf89c8151a Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Thu, 16 Apr 2020 10:36:37 +0300
Subject: don't restart postgrex
---
test/config/transfer_task_test.exs | 9 +++++++++
test/fixtures/config/temp.secret.exs | 2 ++
test/tasks/config_test.exs | 3 ++-
3 files changed, 13 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/config/transfer_task_test.exs b/test/config/transfer_task_test.exs
index 00db0b686..473899d1d 100644
--- a/test/config/transfer_task_test.exs
+++ b/test/config/transfer_task_test.exs
@@ -16,6 +16,7 @@ defmodule Pleroma.Config.TransferTaskTest do
refute Application.get_env(:pleroma, :test_key)
refute Application.get_env(:idna, :test_key)
refute Application.get_env(:quack, :test_key)
+ refute Application.get_env(:postgrex, :test_key)
initial = Application.get_env(:logger, :level)
ConfigDB.create(%{
@@ -36,6 +37,12 @@ defmodule Pleroma.Config.TransferTaskTest do
value: [:test_value1, :test_value2]
})
+ ConfigDB.create(%{
+ group: ":postgrex",
+ key: ":test_key",
+ value: :value
+ })
+
ConfigDB.create(%{group: ":logger", key: ":level", value: :debug})
TransferTask.start_link([])
@@ -44,11 +51,13 @@ defmodule Pleroma.Config.TransferTaskTest do
assert Application.get_env(:idna, :test_key) == [live: 15, com: 35]
assert Application.get_env(:quack, :test_key) == [:test_value1, :test_value2]
assert Application.get_env(:logger, :level) == :debug
+ assert Application.get_env(:postgrex, :test_key) == :value
on_exit(fn ->
Application.delete_env(:pleroma, :test_key)
Application.delete_env(:idna, :test_key)
Application.delete_env(:quack, :test_key)
+ Application.delete_env(:postgrex, :test_key)
Application.put_env(:logger, :level, initial)
end)
end
diff --git a/test/fixtures/config/temp.secret.exs b/test/fixtures/config/temp.secret.exs
index f4686c101..dc950ca30 100644
--- a/test/fixtures/config/temp.secret.exs
+++ b/test/fixtures/config/temp.secret.exs
@@ -7,3 +7,5 @@ config :pleroma, :second_setting, key: "value2", key2: ["Activity"]
config :quack, level: :info
config :pleroma, Pleroma.Repo, pool: Ecto.Adapters.SQL.Sandbox
+
+config :postgrex, :json_library, Poison
diff --git a/test/tasks/config_test.exs b/test/tasks/config_test.exs
index 3dee4f082..04bc947a9 100644
--- a/test/tasks/config_test.exs
+++ b/test/tasks/config_test.exs
@@ -38,7 +38,7 @@ defmodule Mix.Tasks.Pleroma.ConfigTest do
on_exit(fn -> Application.put_env(:quack, :level, initial) end)
end
- test "settings are migrated to db" do
+ test "filtered settings are migrated to db" do
assert Repo.all(ConfigDB) == []
Mix.Tasks.Pleroma.Config.migrate_to_db("test/fixtures/config/temp.secret.exs")
@@ -47,6 +47,7 @@ defmodule Mix.Tasks.Pleroma.ConfigTest do
config2 = ConfigDB.get_by_params(%{group: ":pleroma", key: ":second_setting"})
config3 = ConfigDB.get_by_params(%{group: ":quack", key: ":level"})
refute ConfigDB.get_by_params(%{group: ":pleroma", key: "Pleroma.Repo"})
+ refute ConfigDB.get_by_params(%{group: ":postgrex", key: ":json_library"})
assert ConfigDB.from_binary(config1.value) == [key: "value", key2: [Repo]]
assert ConfigDB.from_binary(config2.value) == [key: "value2", key2: ["Activity"]]
--
cgit v1.2.3
From 26d9c83316fe5d8a3bf1f8fadae727788a92a725 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 17 Apr 2020 15:50:15 +0200
Subject: SideEffects: Test for notification creation.
---
test/web/activity_pub/side_effects_test.exs | 12 ++++++++++--
1 file changed, 10 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index b67bd14b3..0b6b55156 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -5,7 +5,9 @@
defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
use Pleroma.DataCase
+ alias Pleroma.Notification
alias Pleroma.Object
+ alias Pleroma.Repo
alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.SideEffects
@@ -15,13 +17,14 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
describe "like objects" do
setup do
+ poster = insert(:user)
user = insert(:user)
- {:ok, post} = CommonAPI.post(user, %{"status" => "hey"})
+ {:ok, post} = CommonAPI.post(poster, %{"status" => "hey"})
{:ok, like_data, _meta} = Builder.like(user, post.object)
{:ok, like, _meta} = ActivityPub.persist(like_data, local: true)
- %{like: like, user: user}
+ %{like: like, user: user, poster: poster}
end
test "add the like to the original object", %{like: like, user: user} do
@@ -30,5 +33,10 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
assert object.data["like_count"] == 1
assert user.ap_id in object.data["likes"]
end
+
+ test "creates a notification", %{like: like, poster: poster} do
+ {:ok, like, _} = SideEffects.handle(like)
+ assert Repo.get_by(Notification, user_id: poster.id, activity_id: like.id)
+ end
end
end
--
cgit v1.2.3
From 163341857a726e8d74b6ddcd1230579e4c36a1b5 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Fri, 17 Apr 2020 19:27:22 +0400
Subject: Improve OpenAPI errors
---
test/web/mastodon_api/controllers/account_controller_test.exs | 11 ++++++++++-
1 file changed, 10 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 86136f7e4..133d7f642 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -952,7 +952,16 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> post("/api/v1/accounts", Map.delete(valid_params, attr))
|> json_response(400)
- assert res == %{"error" => "Missing parameters"}
+ assert res == %{
+ "error" => "Missing field: #{attr}.",
+ "errors" => [
+ %{
+ "message" => "Missing field: #{attr}",
+ "source" => %{"pointer" => "/#{attr}"},
+ "title" => "Invalid value"
+ }
+ ]
+ }
end)
end
--
cgit v1.2.3
From 66f55106bda23e0cfb01cb63f7397f4383518963 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Fri, 17 Apr 2020 21:21:10 +0300
Subject: [#1682] Fixed Basic Auth permissions issue by disabling OAuth scopes
checks when password is provided. Refactored plugs skipping functionality.
---
test/plugs/authentication_plug_test.exs | 7 +++-
test/plugs/legacy_authentication_plug_test.exs | 6 +++-
test/plugs/oauth_scopes_plug_test.exs | 3 +-
test/web/auth/basic_auth_test.exs | 46 ++++++++++++++++++++++++++
4 files changed, 58 insertions(+), 4 deletions(-)
create mode 100644 test/web/auth/basic_auth_test.exs
(limited to 'test')
diff --git a/test/plugs/authentication_plug_test.exs b/test/plugs/authentication_plug_test.exs
index ae2f3f8ec..646bda9d3 100644
--- a/test/plugs/authentication_plug_test.exs
+++ b/test/plugs/authentication_plug_test.exs
@@ -6,6 +6,8 @@ defmodule Pleroma.Plugs.AuthenticationPlugTest do
use Pleroma.Web.ConnCase, async: true
alias Pleroma.Plugs.AuthenticationPlug
+ alias Pleroma.Plugs.OAuthScopesPlug
+ alias Pleroma.Plugs.PlugHelper
alias Pleroma.User
import ExUnit.CaptureLog
@@ -36,13 +38,16 @@ defmodule Pleroma.Plugs.AuthenticationPlugTest do
assert ret_conn == conn
end
- test "with a correct password in the credentials, it assigns the auth_user", %{conn: conn} do
+ test "with a correct password in the credentials, " <>
+ "it assigns the auth_user and marks OAuthScopesPlug as skipped",
+ %{conn: conn} do
conn =
conn
|> assign(:auth_credentials, %{password: "guy"})
|> AuthenticationPlug.call(%{})
assert conn.assigns.user == conn.assigns.auth_user
+ assert PlugHelper.plug_skipped?(conn, OAuthScopesPlug)
end
test "with a wrong password in the credentials, it does nothing", %{conn: conn} do
diff --git a/test/plugs/legacy_authentication_plug_test.exs b/test/plugs/legacy_authentication_plug_test.exs
index 7559de7d3..3b8c07627 100644
--- a/test/plugs/legacy_authentication_plug_test.exs
+++ b/test/plugs/legacy_authentication_plug_test.exs
@@ -8,6 +8,8 @@ defmodule Pleroma.Plugs.LegacyAuthenticationPlugTest do
import Pleroma.Factory
alias Pleroma.Plugs.LegacyAuthenticationPlug
+ alias Pleroma.Plugs.OAuthScopesPlug
+ alias Pleroma.Plugs.PlugHelper
alias Pleroma.User
setup do
@@ -36,7 +38,8 @@ defmodule Pleroma.Plugs.LegacyAuthenticationPlugTest do
end
@tag :skip_on_mac
- test "it authenticates the auth_user if present and password is correct and resets the password",
+ test "if `auth_user` is present and password is correct, " <>
+ "it authenticates the user, resets the password, marks OAuthScopesPlug as skipped",
%{
conn: conn,
user: user
@@ -49,6 +52,7 @@ defmodule Pleroma.Plugs.LegacyAuthenticationPlugTest do
conn = LegacyAuthenticationPlug.call(conn, %{})
assert conn.assigns.user.id == user.id
+ assert PlugHelper.plug_skipped?(conn, OAuthScopesPlug)
end
@tag :skip_on_mac
diff --git a/test/plugs/oauth_scopes_plug_test.exs b/test/plugs/oauth_scopes_plug_test.exs
index abab7abb0..edbc94227 100644
--- a/test/plugs/oauth_scopes_plug_test.exs
+++ b/test/plugs/oauth_scopes_plug_test.exs
@@ -7,7 +7,6 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do
alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Plugs.OAuthScopesPlug
- alias Pleroma.Plugs.PlugHelper
alias Pleroma.Repo
import Mock
@@ -21,7 +20,7 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do
with_mock OAuthScopesPlug, [:passthrough], perform: &passthrough([&1, &2]) do
conn =
conn
- |> PlugHelper.append_to_skipped_plugs(OAuthScopesPlug)
+ |> OAuthScopesPlug.skip_plug()
|> OAuthScopesPlug.call(%{scopes: ["random_scope"]})
refute called(OAuthScopesPlug.perform(:_, :_))
diff --git a/test/web/auth/basic_auth_test.exs b/test/web/auth/basic_auth_test.exs
new file mode 100644
index 000000000..64f8a6863
--- /dev/null
+++ b/test/web/auth/basic_auth_test.exs
@@ -0,0 +1,46 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.Auth.BasicAuthTest do
+ use Pleroma.Web.ConnCase
+
+ import Pleroma.Factory
+
+ test "with HTTP Basic Auth used, grants access to OAuth scope-restricted endpoints", %{
+ conn: conn
+ } do
+ user = insert(:user)
+ assert Comeonin.Pbkdf2.checkpw("test", user.password_hash)
+
+ basic_auth_contents =
+ (URI.encode_www_form(user.nickname) <> ":" <> URI.encode_www_form("test"))
+ |> Base.encode64()
+
+ # Succeeds with HTTP Basic Auth
+ response =
+ conn
+ |> put_req_header("authorization", "Basic " <> basic_auth_contents)
+ |> get("/api/v1/accounts/verify_credentials")
+ |> json_response(200)
+
+ user_nickname = user.nickname
+ assert %{"username" => ^user_nickname} = response
+
+ # Succeeds with a properly scoped OAuth token
+ valid_token = insert(:oauth_token, scopes: ["read:accounts"])
+
+ conn
+ |> put_req_header("authorization", "Bearer #{valid_token.token}")
+ |> get("/api/v1/accounts/verify_credentials")
+ |> json_response(200)
+
+ # Fails with a wrong-scoped OAuth token (proof of restriction)
+ invalid_token = insert(:oauth_token, scopes: ["read:something"])
+
+ conn
+ |> put_req_header("authorization", "Bearer #{invalid_token.token}")
+ |> get("/api/v1/accounts/verify_credentials")
+ |> json_response(403)
+ end
+end
--
cgit v1.2.3
From 8b4de61d6449f70e0a5e84be3082724c7f50ffee Mon Sep 17 00:00:00 2001
From: Ilja
Date: Mon, 20 Apr 2020 12:59:16 +0000
Subject: Fix ObjectAgePolicyTest
The policy didn't block old posts as it should.
* I fixed it and tested on a test server
* I added the settings to description so that this information is shown in nodeinfo
* TODO: I didn't work TTD and still need to fix the tests
---
.../activity_pub/mrf/object_age_policy_test.exs | 52 +++++++++++-----------
1 file changed, 27 insertions(+), 25 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/mrf/object_age_policy_test.exs b/test/web/activity_pub/mrf/object_age_policy_test.exs
index 7ee195eeb..b0fb753bd 100644
--- a/test/web/activity_pub/mrf/object_age_policy_test.exs
+++ b/test/web/activity_pub/mrf/object_age_policy_test.exs
@@ -20,26 +20,38 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do
:ok
end
+ defp get_old_message do
+ File.read!("test/fixtures/mastodon-post-activity.json")
+ |> Poison.decode!()
+ end
+
+ defp get_new_message do
+ old_message = get_old_message()
+
+ new_object =
+ old_message
+ |> Map.get("object")
+ |> Map.put("published", DateTime.utc_now() |> DateTime.to_iso8601())
+
+ old_message
+ |> Map.put("object", new_object)
+ end
+
describe "with reject action" do
test "it rejects an old post" do
Config.put([:mrf_object_age, :actions], [:reject])
- data =
- File.read!("test/fixtures/mastodon-post-activity.json")
- |> Poison.decode!()
+ data = get_old_message()
- {:reject, _} = ObjectAgePolicy.filter(data)
+ assert match?({:reject, _}, ObjectAgePolicy.filter(data))
end
test "it allows a new post" do
Config.put([:mrf_object_age, :actions], [:reject])
- data =
- File.read!("test/fixtures/mastodon-post-activity.json")
- |> Poison.decode!()
- |> Map.put("published", DateTime.utc_now() |> DateTime.to_iso8601())
+ data = get_new_message()
- {:ok, _} = ObjectAgePolicy.filter(data)
+ assert match?({:ok, _}, ObjectAgePolicy.filter(data))
end
end
@@ -47,9 +59,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do
test "it delists an old post" do
Config.put([:mrf_object_age, :actions], [:delist])
- data =
- File.read!("test/fixtures/mastodon-post-activity.json")
- |> Poison.decode!()
+ data = get_old_message()
{:ok, _u} = User.get_or_fetch_by_ap_id(data["actor"])
@@ -61,14 +71,11 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do
test "it allows a new post" do
Config.put([:mrf_object_age, :actions], [:delist])
- data =
- File.read!("test/fixtures/mastodon-post-activity.json")
- |> Poison.decode!()
- |> Map.put("published", DateTime.utc_now() |> DateTime.to_iso8601())
+ data = get_new_message()
{:ok, _user} = User.get_or_fetch_by_ap_id(data["actor"])
- {:ok, ^data} = ObjectAgePolicy.filter(data)
+ assert match?({:ok, ^data}, ObjectAgePolicy.filter(data))
end
end
@@ -76,9 +83,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do
test "it strips followers collections from an old post" do
Config.put([:mrf_object_age, :actions], [:strip_followers])
- data =
- File.read!("test/fixtures/mastodon-post-activity.json")
- |> Poison.decode!()
+ data = get_old_message()
{:ok, user} = User.get_or_fetch_by_ap_id(data["actor"])
@@ -91,14 +96,11 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do
test "it allows a new post" do
Config.put([:mrf_object_age, :actions], [:strip_followers])
- data =
- File.read!("test/fixtures/mastodon-post-activity.json")
- |> Poison.decode!()
- |> Map.put("published", DateTime.utc_now() |> DateTime.to_iso8601())
+ data = get_new_message()
{:ok, _u} = User.get_or_fetch_by_ap_id(data["actor"])
- {:ok, ^data} = ObjectAgePolicy.filter(data)
+ assert match?({:ok, ^data}, ObjectAgePolicy.filter(data))
end
end
end
--
cgit v1.2.3
From b54c8813d632cb44c7deb207e91bd32f01f33794 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Mon, 13 Apr 2020 13:48:32 -0500
Subject: Add :reject_deletes option to SimplePolicy
---
test/web/activity_pub/mrf/simple_policy_test.exs | 79 +++++++++++++++++++-----
1 file changed, 62 insertions(+), 17 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/mrf/simple_policy_test.exs b/test/web/activity_pub/mrf/simple_policy_test.exs
index eaa595706..b7b9bc6a2 100644
--- a/test/web/activity_pub/mrf/simple_policy_test.exs
+++ b/test/web/activity_pub/mrf/simple_policy_test.exs
@@ -17,7 +17,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do
reject: [],
accept: [],
avatar_removal: [],
- banner_removal: []
+ banner_removal: [],
+ reject_deletes: []
)
describe "when :media_removal" do
@@ -258,14 +259,6 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do
assert SimplePolicy.filter(remote_user) == {:reject, nil}
end
-
- test "always accept deletions" do
- Config.put([:mrf_simple, :reject], ["remote.instance"])
-
- deletion_message = build_remote_deletion_message()
-
- assert SimplePolicy.filter(deletion_message) == {:ok, deletion_message}
- end
end
describe "when :accept" do
@@ -316,14 +309,6 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do
assert SimplePolicy.filter(remote_user) == {:ok, remote_user}
end
-
- test "always accept deletions" do
- Config.put([:mrf_simple, :accept], ["non.matching.remote"])
-
- deletion_message = build_remote_deletion_message()
-
- assert SimplePolicy.filter(deletion_message) == {:ok, deletion_message}
- end
end
describe "when :avatar_removal" do
@@ -398,6 +383,66 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do
end
end
+ describe "when :reject_deletes is empty" do
+ setup do: Config.put([:mrf_simple, :reject_deletes], [])
+
+ test "it accepts deletions even from rejected servers" do
+ Config.put([:mrf_simple, :reject], ["remote.instance"])
+
+ deletion_message = build_remote_deletion_message()
+
+ assert SimplePolicy.filter(deletion_message) == {:ok, deletion_message}
+ end
+
+ test "it accepts deletions even from non-whitelisted servers" do
+ Config.put([:mrf_simple, :accept], ["non.matching.remote"])
+
+ deletion_message = build_remote_deletion_message()
+
+ assert SimplePolicy.filter(deletion_message) == {:ok, deletion_message}
+ end
+ end
+
+ describe "when :reject_deletes is not empty but it doesn't have a matching host" do
+ setup do: Config.put([:mrf_simple, :reject_deletes], ["non.matching.remote"])
+
+ test "it accepts deletions even from rejected servers" do
+ Config.put([:mrf_simple, :reject], ["remote.instance"])
+
+ deletion_message = build_remote_deletion_message()
+
+ assert SimplePolicy.filter(deletion_message) == {:ok, deletion_message}
+ end
+
+ test "it accepts deletions even from non-whitelisted servers" do
+ Config.put([:mrf_simple, :accept], ["non.matching.remote"])
+
+ deletion_message = build_remote_deletion_message()
+
+ assert SimplePolicy.filter(deletion_message) == {:ok, deletion_message}
+ end
+ end
+
+ describe "when :reject_deletes has a matching host" do
+ setup do: Config.put([:mrf_simple, :reject_deletes], ["remote.instance"])
+
+ test "it rejects the deletion" do
+ deletion_message = build_remote_deletion_message()
+
+ assert SimplePolicy.filter(deletion_message) == {:reject, nil}
+ end
+ end
+
+ describe "when :reject_deletes match with wildcard domain" do
+ setup do: Config.put([:mrf_simple, :reject_deletes], ["*.remote.instance"])
+
+ test "it rejects the deletion" do
+ deletion_message = build_remote_deletion_message()
+
+ assert SimplePolicy.filter(deletion_message) == {:reject, nil}
+ end
+ end
+
defp build_local_message do
%{
"actor" => "#{Pleroma.Web.base_url()}/users/alice",
--
cgit v1.2.3
From f685cbd30940b3fd92a2f6c8a161729bc2ceaab6 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Tue, 21 Apr 2020 16:29:19 +0300
Subject: Automatic checks of authentication / instance publicity. Definition
of missing OAuth scopes in AdminAPIController. Refactoring.
---
test/plugs/ensure_authenticated_plug_test.exs | 16 +++++-----
.../ensure_public_or_authenticated_plug_test.exs | 4 +--
test/plugs/oauth_scopes_plug_test.exs | 36 +---------------------
.../activity_pub/activity_pub_controller_test.exs | 2 +-
.../controllers/emoji_api_controller_test.exs | 11 +++----
.../twitter_api/twitter_api_controller_test.exs | 8 ++---
6 files changed, 20 insertions(+), 57 deletions(-)
(limited to 'test')
diff --git a/test/plugs/ensure_authenticated_plug_test.exs b/test/plugs/ensure_authenticated_plug_test.exs
index 7f3559b83..689fe757f 100644
--- a/test/plugs/ensure_authenticated_plug_test.exs
+++ b/test/plugs/ensure_authenticated_plug_test.exs
@@ -20,7 +20,7 @@ defmodule Pleroma.Plugs.EnsureAuthenticatedPlugTest do
conn = assign(conn, :user, %User{})
ret_conn = EnsureAuthenticatedPlug.call(conn, %{})
- assert ret_conn == conn
+ refute ret_conn.halted
end
end
@@ -34,20 +34,22 @@ defmodule Pleroma.Plugs.EnsureAuthenticatedPlugTest do
test "it continues if a user is assigned", %{conn: conn, true_fn: true_fn, false_fn: false_fn} do
conn = assign(conn, :user, %User{})
- assert EnsureAuthenticatedPlug.call(conn, if_func: true_fn) == conn
- assert EnsureAuthenticatedPlug.call(conn, if_func: false_fn) == conn
- assert EnsureAuthenticatedPlug.call(conn, unless_func: true_fn) == conn
- assert EnsureAuthenticatedPlug.call(conn, unless_func: false_fn) == conn
+ refute EnsureAuthenticatedPlug.call(conn, if_func: true_fn).halted
+ refute EnsureAuthenticatedPlug.call(conn, if_func: false_fn).halted
+ refute EnsureAuthenticatedPlug.call(conn, unless_func: true_fn).halted
+ refute EnsureAuthenticatedPlug.call(conn, unless_func: false_fn).halted
end
test "it continues if a user is NOT assigned but :if_func evaluates to `false`",
%{conn: conn, false_fn: false_fn} do
- assert EnsureAuthenticatedPlug.call(conn, if_func: false_fn) == conn
+ ret_conn = EnsureAuthenticatedPlug.call(conn, if_func: false_fn)
+ refute ret_conn.halted
end
test "it continues if a user is NOT assigned but :unless_func evaluates to `true`",
%{conn: conn, true_fn: true_fn} do
- assert EnsureAuthenticatedPlug.call(conn, unless_func: true_fn) == conn
+ ret_conn = EnsureAuthenticatedPlug.call(conn, unless_func: true_fn)
+ refute ret_conn.halted
end
test "it halts if a user is NOT assigned and :if_func evaluates to `true`",
diff --git a/test/plugs/ensure_public_or_authenticated_plug_test.exs b/test/plugs/ensure_public_or_authenticated_plug_test.exs
index 411252274..fc2934369 100644
--- a/test/plugs/ensure_public_or_authenticated_plug_test.exs
+++ b/test/plugs/ensure_public_or_authenticated_plug_test.exs
@@ -29,7 +29,7 @@ defmodule Pleroma.Plugs.EnsurePublicOrAuthenticatedPlugTest do
conn
|> EnsurePublicOrAuthenticatedPlug.call(%{})
- assert ret_conn == conn
+ refute ret_conn.halted
end
test "it continues if a user is assigned, even if not public", %{conn: conn} do
@@ -43,6 +43,6 @@ defmodule Pleroma.Plugs.EnsurePublicOrAuthenticatedPlugTest do
conn
|> EnsurePublicOrAuthenticatedPlug.call(%{})
- assert ret_conn == conn
+ refute ret_conn.halted
end
end
diff --git a/test/plugs/oauth_scopes_plug_test.exs b/test/plugs/oauth_scopes_plug_test.exs
index edbc94227..884de7b4d 100644
--- a/test/plugs/oauth_scopes_plug_test.exs
+++ b/test/plugs/oauth_scopes_plug_test.exs
@@ -5,17 +5,12 @@
defmodule Pleroma.Plugs.OAuthScopesPlugTest do
use Pleroma.Web.ConnCase, async: true
- alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.Repo
import Mock
import Pleroma.Factory
- setup_with_mocks([{EnsurePublicOrAuthenticatedPlug, [], [call: fn conn, _ -> conn end]}]) do
- :ok
- end
-
test "is not performed if marked as skipped", %{conn: conn} do
with_mock OAuthScopesPlug, [:passthrough], perform: &passthrough([&1, &2]) do
conn =
@@ -60,7 +55,7 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do
describe "with `fallback: :proceed_unauthenticated` option, " do
test "if `token.scopes` doesn't fulfill specified conditions, " <>
- "clears :user and :token assigns and calls EnsurePublicOrAuthenticatedPlug",
+ "clears :user and :token assigns",
%{conn: conn} do
user = insert(:user)
token1 = insert(:oauth_token, scopes: ["read", "write"], user: user)
@@ -79,35 +74,6 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do
refute ret_conn.halted
refute ret_conn.assigns[:user]
refute ret_conn.assigns[:token]
-
- assert called(EnsurePublicOrAuthenticatedPlug.call(ret_conn, :_))
- end
- end
-
- test "with :skip_instance_privacy_check option, " <>
- "if `token.scopes` doesn't fulfill specified conditions, " <>
- "clears :user and :token assigns and does NOT call EnsurePublicOrAuthenticatedPlug",
- %{conn: conn} do
- user = insert(:user)
- token1 = insert(:oauth_token, scopes: ["read:statuses", "write"], user: user)
-
- for token <- [token1, nil], op <- [:|, :&] do
- ret_conn =
- conn
- |> assign(:user, user)
- |> assign(:token, token)
- |> OAuthScopesPlug.call(%{
- scopes: ["read"],
- op: op,
- fallback: :proceed_unauthenticated,
- skip_instance_privacy_check: true
- })
-
- refute ret_conn.halted
- refute ret_conn.assigns[:user]
- refute ret_conn.assigns[:token]
-
- refute called(EnsurePublicOrAuthenticatedPlug.call(ret_conn, :_))
end
end
end
diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs
index fbacb3993..eca526604 100644
--- a/test/web/activity_pub/activity_pub_controller_test.exs
+++ b/test/web/activity_pub/activity_pub_controller_test.exs
@@ -766,7 +766,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
end
describe "POST /users/:nickname/outbox" do
- test "it rejects posts from other users / unauuthenticated users", %{conn: conn} do
+ test "it rejects posts from other users / unauthenticated users", %{conn: conn} do
data = File.read!("test/fixtures/activitypub-client-post-activity.json") |> Poison.decode!()
user = insert(:user)
other_user = insert(:user)
diff --git a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
index 435fb6592..4246eb400 100644
--- a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
@@ -38,8 +38,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end
test "listing remote packs" do
- admin = insert(:user, is_admin: true)
- %{conn: conn} = oauth_access(["admin:write"], user: admin)
+ conn = build_conn()
resp =
build_conn()
@@ -76,7 +75,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
assert Enum.find(arch, fn {n, _} -> n == 'blank.png' end)
end
- test "downloading shared & unshared packs from another instance via download_from, deleting them" do
+ test "downloading shared & unshared packs from another instance, deleting them" do
on_exit(fn ->
File.rm_rf!("#{@emoji_dir_path}/test_pack2")
File.rm_rf!("#{@emoji_dir_path}/test_pack_nonshared2")
@@ -136,7 +135,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
|> post(
emoji_api_path(
conn,
- :download_from
+ :save_from
),
%{
instance_address: "https://old-instance",
@@ -152,7 +151,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
|> post(
emoji_api_path(
conn,
- :download_from
+ :save_from
),
%{
instance_address: "https://example.com",
@@ -179,7 +178,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
|> post(
emoji_api_path(
conn,
- :download_from
+ :save_from
),
%{
instance_address: "https://example.com",
diff --git a/test/web/twitter_api/twitter_api_controller_test.exs b/test/web/twitter_api/twitter_api_controller_test.exs
index ab0a2c3df..464d0ea2e 100644
--- a/test/web/twitter_api/twitter_api_controller_test.exs
+++ b/test/web/twitter_api/twitter_api_controller_test.exs
@@ -19,13 +19,9 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do
end
test "with credentials, without any params" do
- %{user: current_user, conn: conn} =
- oauth_access(["read:notifications", "write:notifications"])
+ %{conn: conn} = oauth_access(["write:notifications"])
- conn =
- conn
- |> assign(:user, current_user)
- |> post("/api/qvitter/statuses/notifications/read")
+ conn = post(conn, "/api/qvitter/statuses/notifications/read")
assert json_response(conn, 400) == %{
"error" => "You need to specify latest_id",
--
cgit v1.2.3
From f719a5b23a9bec4ed94f36c07e24aa1413654bae Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 22 Apr 2020 13:28:34 +0200
Subject: WebPush: Return proper values for jobs.
---
test/web/push/impl_test.exs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/push/impl_test.exs b/test/web/push/impl_test.exs
index 9121d90e7..b2664bf28 100644
--- a/test/web/push/impl_test.exs
+++ b/test/web/push/impl_test.exs
@@ -63,12 +63,12 @@ defmodule Pleroma.Web.Push.ImplTest do
activity: activity
)
- assert Impl.perform(notif) == [:ok, :ok]
+ assert Impl.perform(notif) == {:ok, [:ok, :ok]}
end
@tag capture_log: true
test "returns error if notif does not match " do
- assert Impl.perform(%{}) == :error
+ assert Impl.perform(%{}) == {:error, :unknown_type}
end
test "successful message sending" do
--
cgit v1.2.3
From 923513b6417973f700a80ee969c6c92ed2c9faee Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 22 Apr 2020 13:28:52 +0200
Subject: Federator: Return proper values for jobs
---
test/web/federator_test.exs | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/federator_test.exs b/test/web/federator_test.exs
index 59e53bb03..261518ef0 100644
--- a/test/web/federator_test.exs
+++ b/test/web/federator_test.exs
@@ -130,6 +130,9 @@ defmodule Pleroma.Web.FederatorTest do
assert {:ok, job} = Federator.incoming_ap_doc(params)
assert {:ok, _activity} = ObanHelpers.perform(job)
+
+ assert {:ok, job} = Federator.incoming_ap_doc(params)
+ assert {:error, :already_present} = ObanHelpers.perform(job)
end
test "rejects incoming AP docs with incorrect origin" do
@@ -148,7 +151,7 @@ defmodule Pleroma.Web.FederatorTest do
}
assert {:ok, job} = Federator.incoming_ap_doc(params)
- assert :error = ObanHelpers.perform(job)
+ assert {:error, :origin_containment_failed} = ObanHelpers.perform(job)
end
test "it does not crash if MRF rejects the post" do
@@ -164,7 +167,7 @@ defmodule Pleroma.Web.FederatorTest do
|> Poison.decode!()
assert {:ok, job} = Federator.incoming_ap_doc(params)
- assert :error = ObanHelpers.perform(job)
+ assert {:error, _} = ObanHelpers.perform(job)
end
end
end
--
cgit v1.2.3
From 5102468d0f8067548ef233b5947da4bc517f5774 Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 22 Apr 2020 14:06:39 +0200
Subject: Polls: Persist and show voters' count
---
test/web/mastodon_api/views/poll_view_test.exs | 16 ++++++++++++++--
1 file changed, 14 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/views/poll_view_test.exs b/test/web/mastodon_api/views/poll_view_test.exs
index 6211fa888..63b204387 100644
--- a/test/web/mastodon_api/views/poll_view_test.exs
+++ b/test/web/mastodon_api/views/poll_view_test.exs
@@ -43,7 +43,8 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do
%{title: "why are you even asking?", votes_count: 0}
],
voted: false,
- votes_count: 0
+ votes_count: 0,
+ voters_count: nil
}
result = PollView.render("show.json", %{object: object})
@@ -69,9 +70,20 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do
}
})
+ voter = insert(:user)
+
object = Object.normalize(activity)
- assert %{multiple: true} = PollView.render("show.json", %{object: object})
+ {:ok, _votes, object} = CommonAPI.vote(voter, object, [0, 1])
+
+ assert match?(
+ %{
+ multiple: true,
+ voters_count: 1,
+ votes_count: 2
+ },
+ PollView.render("show.json", %{object: object})
+ )
end
test "detects emoji" do
--
cgit v1.2.3
From c10485db163d56acd7206980f91f0e51153ef36a Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 22 Apr 2020 14:26:19 +0200
Subject: StatusController: Ignore nil scheduled_at parameters.
---
test/web/mastodon_api/controllers/status_controller_test.exs | 11 +++++++++++
1 file changed, 11 insertions(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/status_controller_test.exs b/test/web/mastodon_api/controllers/status_controller_test.exs
index 162f7b1b2..85068edd0 100644
--- a/test/web/mastodon_api/controllers/status_controller_test.exs
+++ b/test/web/mastodon_api/controllers/status_controller_test.exs
@@ -302,6 +302,17 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
assert [] == Repo.all(Activity)
end
+ test "ignores nil values", %{conn: conn} do
+ conn =
+ post(conn, "/api/v1/statuses", %{
+ "status" => "not scheduled",
+ "scheduled_at" => nil
+ })
+
+ assert result = json_response(conn, 200)
+ assert Activity.get_by_id(result["id"])
+ end
+
test "creates a scheduled activity with a media attachment", %{user: user, conn: conn} do
scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond)
--
cgit v1.2.3
From 5b3952619818d38f8fdba9a64b050ce3f24394ff Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 22 Apr 2020 15:04:26 +0200
Subject: AccountController: Use code 400 for self-follow.
---
test/web/mastodon_api/controllers/account_controller_test.exs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 61c2697b2..8c428efee 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -681,17 +681,17 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "following / unfollowing errors", %{user: user, conn: conn} do
# self follow
conn_res = post(conn, "/api/v1/accounts/#{user.id}/follow")
- assert %{"error" => "Record not found"} = json_response(conn_res, 404)
+ assert %{"error" => "Can not follow yourself"} = json_response(conn_res, 400)
# self unfollow
user = User.get_cached_by_id(user.id)
conn_res = post(conn, "/api/v1/accounts/#{user.id}/unfollow")
- assert %{"error" => "Record not found"} = json_response(conn_res, 404)
+ assert %{"error" => "Can not unfollow yourself"} = json_response(conn_res, 400)
# self follow via uri
user = User.get_cached_by_id(user.id)
conn_res = post(conn, "/api/v1/follows", %{"uri" => user.nickname})
- assert %{"error" => "Record not found"} = json_response(conn_res, 404)
+ assert %{"error" => "Can not follow yourself"} = json_response(conn_res, 400)
# follow non existing user
conn_res = post(conn, "/api/v1/accounts/doesntexist/follow")
--
cgit v1.2.3
From 8b88e2a6e2b3a777ca99bf94676ab47f2d4cc0ea Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 22 Apr 2020 15:31:37 +0200
Subject: Stats: Ignore internal users for user count.
---
test/stat_test.exs | 70 ---------------------------------------------
test/stats_test.exs | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 81 insertions(+), 70 deletions(-)
delete mode 100644 test/stat_test.exs
create mode 100644 test/stats_test.exs
(limited to 'test')
diff --git a/test/stat_test.exs b/test/stat_test.exs
deleted file mode 100644
index bccc1c8d0..000000000
--- a/test/stat_test.exs
+++ /dev/null
@@ -1,70 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.StateTest do
- use Pleroma.DataCase
- import Pleroma.Factory
- alias Pleroma.Web.CommonAPI
-
- describe "status visibility count" do
- test "on new status" do
- user = insert(:user)
- other_user = insert(:user)
-
- CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
-
- Enum.each(0..1, fn _ ->
- CommonAPI.post(user, %{
- "visibility" => "unlisted",
- "status" => "hey"
- })
- end)
-
- Enum.each(0..2, fn _ ->
- CommonAPI.post(user, %{
- "visibility" => "direct",
- "status" => "hey @#{other_user.nickname}"
- })
- end)
-
- Enum.each(0..3, fn _ ->
- CommonAPI.post(user, %{
- "visibility" => "private",
- "status" => "hey"
- })
- end)
-
- assert %{direct: 3, private: 4, public: 1, unlisted: 2} =
- Pleroma.Stats.get_status_visibility_count()
- end
-
- test "on status delete" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
- assert %{public: 1} = Pleroma.Stats.get_status_visibility_count()
- CommonAPI.delete(activity.id, user)
- assert %{public: 0} = Pleroma.Stats.get_status_visibility_count()
- end
-
- test "on status visibility update" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
- assert %{public: 1, private: 0} = Pleroma.Stats.get_status_visibility_count()
- {:ok, _} = CommonAPI.update_activity_scope(activity.id, %{"visibility" => "private"})
- assert %{public: 0, private: 1} = Pleroma.Stats.get_status_visibility_count()
- end
-
- test "doesn't count unrelated activities" do
- user = insert(:user)
- other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
- _ = CommonAPI.follow(user, other_user)
- CommonAPI.favorite(other_user, activity.id)
- CommonAPI.repeat(activity.id, other_user)
-
- assert %{direct: 0, private: 0, public: 1, unlisted: 0} =
- Pleroma.Stats.get_status_visibility_count()
- end
- end
-end
diff --git a/test/stats_test.exs b/test/stats_test.exs
new file mode 100644
index 000000000..73c7c1495
--- /dev/null
+++ b/test/stats_test.exs
@@ -0,0 +1,81 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.StatsTest do
+ use Pleroma.DataCase
+ import Pleroma.Factory
+ alias Pleroma.Web.CommonAPI
+
+ describe "user count" do
+ test "it ignores internal users" do
+ _user = insert(:user, local: true)
+ _internal = insert(:user, local: true, nickname: nil)
+ _internal = insert(:user, local: true, nickname: "internal.dude")
+ _internal = Pleroma.Web.ActivityPub.Relay.get_actor()
+
+ assert match?(%{stats: %{user_count: 1}}, Pleroma.Stats.calculate_stat_data())
+ end
+ end
+
+ describe "status visibility count" do
+ test "on new status" do
+ user = insert(:user)
+ other_user = insert(:user)
+
+ CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
+
+ Enum.each(0..1, fn _ ->
+ CommonAPI.post(user, %{
+ "visibility" => "unlisted",
+ "status" => "hey"
+ })
+ end)
+
+ Enum.each(0..2, fn _ ->
+ CommonAPI.post(user, %{
+ "visibility" => "direct",
+ "status" => "hey @#{other_user.nickname}"
+ })
+ end)
+
+ Enum.each(0..3, fn _ ->
+ CommonAPI.post(user, %{
+ "visibility" => "private",
+ "status" => "hey"
+ })
+ end)
+
+ assert %{direct: 3, private: 4, public: 1, unlisted: 2} =
+ Pleroma.Stats.get_status_visibility_count()
+ end
+
+ test "on status delete" do
+ user = insert(:user)
+ {:ok, activity} = CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
+ assert %{public: 1} = Pleroma.Stats.get_status_visibility_count()
+ CommonAPI.delete(activity.id, user)
+ assert %{public: 0} = Pleroma.Stats.get_status_visibility_count()
+ end
+
+ test "on status visibility update" do
+ user = insert(:user)
+ {:ok, activity} = CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
+ assert %{public: 1, private: 0} = Pleroma.Stats.get_status_visibility_count()
+ {:ok, _} = CommonAPI.update_activity_scope(activity.id, %{"visibility" => "private"})
+ assert %{public: 0, private: 1} = Pleroma.Stats.get_status_visibility_count()
+ end
+
+ test "doesn't count unrelated activities" do
+ user = insert(:user)
+ other_user = insert(:user)
+ {:ok, activity} = CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
+ _ = CommonAPI.follow(user, other_user)
+ CommonAPI.favorite(other_user, activity.id)
+ CommonAPI.repeat(activity.id, other_user)
+
+ assert %{direct: 0, private: 0, public: 1, unlisted: 0} =
+ Pleroma.Stats.get_status_visibility_count()
+ end
+ end
+end
--
cgit v1.2.3
From 7a3a88a13ef526fba18bb6aeadc93f5da934dc5b Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 22 Apr 2020 17:21:13 +0200
Subject: Streamer: Stream boosts to the boosting user.
---
test/user_test.exs | 12 ++++++++++++
test/web/streamer/streamer_test.exs | 36 ++++++++++++++++++++++++++++++++++++
2 files changed, 48 insertions(+)
(limited to 'test')
diff --git a/test/user_test.exs b/test/user_test.exs
index 65e118d6d..cd4041673 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -987,6 +987,18 @@ defmodule Pleroma.UserTest do
end
describe "get_recipients_from_activity" do
+ test "works for announces" do
+ actor = insert(:user)
+ user = insert(:user, local: true)
+
+ {:ok, activity} = CommonAPI.post(actor, %{"status" => "hello"})
+ {:ok, announce, _} = CommonAPI.repeat(activity.id, user)
+
+ recipients = User.get_recipients_from_activity(announce)
+
+ assert user in recipients
+ end
+
test "get recipients" do
actor = insert(:user)
user = insert(:user, local: true)
diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs
index eb082b79f..8b8d8af6c 100644
--- a/test/web/streamer/streamer_test.exs
+++ b/test/web/streamer/streamer_test.exs
@@ -28,6 +28,42 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, %{user: user, notify: notify}}
end
+ test "it streams the user's post in the 'user' stream", %{user: user} do
+ task =
+ Task.async(fn ->
+ assert_receive {:text, _}, @streamer_timeout
+ end)
+
+ Streamer.add_socket(
+ "user",
+ %{transport_pid: task.pid, assigns: %{user: user}}
+ )
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
+
+ Streamer.stream("user", activity)
+ Task.await(task)
+ end
+
+ test "it streams boosts of the user in the 'user' stream", %{user: user} do
+ task =
+ Task.async(fn ->
+ assert_receive {:text, _}, @streamer_timeout
+ end)
+
+ Streamer.add_socket(
+ "user",
+ %{transport_pid: task.pid, assigns: %{user: user}}
+ )
+
+ other_user = insert(:user)
+ {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hey"})
+ {:ok, announce, _} = CommonAPI.repeat(activity.id, user)
+
+ Streamer.stream("user", announce)
+ Task.await(task)
+ end
+
test "it sends notify to in the 'user' stream", %{user: user, notify: notify} do
task =
Task.async(fn ->
--
cgit v1.2.3
From 88b82e5c3edae649f1caa45c6ef805828e4b8b1e Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 21 Apr 2020 20:05:25 +0400
Subject: Fix follow import
---
test/web/twitter_api/util_controller_test.exs | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
(limited to 'test')
diff --git a/test/web/twitter_api/util_controller_test.exs b/test/web/twitter_api/util_controller_test.exs
index 30e54bebd..85aaab19b 100644
--- a/test/web/twitter_api/util_controller_test.exs
+++ b/test/web/twitter_api/util_controller_test.exs
@@ -95,6 +95,30 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do
end
end
end
+
+ test "it imports with different nickname variations", %{conn: conn} do
+ [user2, user3, user4, user5, user6] = insert_list(5, :user)
+
+ identifiers =
+ [
+ user2.ap_id,
+ user3.nickname,
+ " ",
+ "@" <> user4.nickname,
+ user5.nickname <> "@localhost",
+ "@" <> user6.nickname <> "@localhost"
+ ]
+ |> Enum.join("\n")
+
+ response =
+ conn
+ |> post("/api/pleroma/follow_import", %{"list" => identifiers})
+ |> json_response(:ok)
+
+ assert response == "job started"
+ assert [job_result] = ObanHelpers.perform_all()
+ assert job_result == [user2, user3, user4, user5, user6]
+ end
end
describe "POST /api/pleroma/blocks_import" do
--
cgit v1.2.3
From e7771424a895572626ec36a98bf862952dc6ff07 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 22 Apr 2020 18:13:13 +0400
Subject: Fix blocks import
---
test/web/twitter_api/util_controller_test.exs | 25 ++++++++++++++++++++++++-
1 file changed, 24 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/twitter_api/util_controller_test.exs b/test/web/twitter_api/util_controller_test.exs
index 85aaab19b..d835331ae 100644
--- a/test/web/twitter_api/util_controller_test.exs
+++ b/test/web/twitter_api/util_controller_test.exs
@@ -96,7 +96,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do
end
end
- test "it imports with different nickname variations", %{conn: conn} do
+ test "it imports follows with different nickname variations", %{conn: conn} do
[user2, user3, user4, user5, user6] = insert_list(5, :user)
identifiers =
@@ -160,6 +160,29 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do
)
end
end
+
+ test "it imports blocks with different nickname variations", %{conn: conn} do
+ [user2, user3, user4, user5, user6] = insert_list(5, :user)
+
+ identifiers =
+ [
+ user2.ap_id,
+ user3.nickname,
+ "@" <> user4.nickname,
+ user5.nickname <> "@localhost",
+ "@" <> user6.nickname <> "@localhost"
+ ]
+ |> Enum.join(" ")
+
+ response =
+ conn
+ |> post("/api/pleroma/blocks_import", %{"list" => identifiers})
+ |> json_response(:ok)
+
+ assert response == "job started"
+ assert [job_result] = ObanHelpers.perform_all()
+ assert job_result == [user2, user3, user4, user5, user6]
+ end
end
describe "PUT /api/pleroma/notification_settings" do
--
cgit v1.2.3
From 6db52c3b3680efbdb56d53d84d5dec0f4b6e34f0 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 22 Apr 2020 19:00:08 +0400
Subject: Fix Oban warning
Warning example:
[warn] Expected Elixir.Pleroma.Workers.BackgroundWorker.perform/2 to return :ok, {:ok, value}, or {:error, reason}. Instead received: [error: "not found @user@server.party", error: "not found "] The job will be considered a success.
---
test/user_test.exs | 4 ++--
test/web/twitter_api/util_controller_test.exs | 4 ++--
2 files changed, 4 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/user_test.exs b/test/user_test.exs
index 65e118d6d..23e7cf6e3 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -756,8 +756,8 @@ defmodule Pleroma.UserTest do
]
{:ok, job} = User.follow_import(user1, identifiers)
- result = ObanHelpers.perform(job)
+ assert {:ok, result} = ObanHelpers.perform(job)
assert is_list(result)
assert result == [user2, user3]
end
@@ -979,8 +979,8 @@ defmodule Pleroma.UserTest do
]
{:ok, job} = User.blocks_import(user1, identifiers)
- result = ObanHelpers.perform(job)
+ assert {:ok, result} = ObanHelpers.perform(job)
assert is_list(result)
assert result == [user2, user3]
end
diff --git a/test/web/twitter_api/util_controller_test.exs b/test/web/twitter_api/util_controller_test.exs
index d835331ae..b701239a0 100644
--- a/test/web/twitter_api/util_controller_test.exs
+++ b/test/web/twitter_api/util_controller_test.exs
@@ -116,7 +116,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do
|> json_response(:ok)
assert response == "job started"
- assert [job_result] = ObanHelpers.perform_all()
+ assert [{:ok, job_result}] = ObanHelpers.perform_all()
assert job_result == [user2, user3, user4, user5, user6]
end
end
@@ -180,7 +180,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do
|> json_response(:ok)
assert response == "job started"
- assert [job_result] = ObanHelpers.perform_all()
+ assert [{:ok, job_result}] = ObanHelpers.perform_all()
assert job_result == [user2, user3, user4, user5, user6]
end
end
--
cgit v1.2.3
From e62173dfc8b739508345b7ab97477ae04fcdb457 Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 22 Apr 2020 18:40:53 +0200
Subject: SideEffects: Run in transaction.
This fixes race conditions.
---
test/web/common_api/common_api_test.exs | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)
(limited to 'test')
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index e130736ec..68a29108a 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -21,6 +21,33 @@ defmodule Pleroma.Web.CommonAPITest do
setup do: clear_config([:instance, :limit])
setup do: clear_config([:instance, :max_pinned_statuses])
+ test "favoriting race condition" do
+ user = insert(:user)
+ users_serial = insert_list(10, :user)
+ users = insert_list(10, :user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "."})
+
+ users_serial
+ |> Enum.map(fn user ->
+ CommonAPI.favorite(user, activity.id)
+ end)
+
+ object = Object.get_by_ap_id(activity.data["object"])
+ assert object.data["like_count"] == 10
+
+ users
+ |> Enum.map(fn user ->
+ Task.async(fn ->
+ CommonAPI.favorite(user, activity.id)
+ end)
+ end)
+ |> Enum.map(&Task.await/1)
+
+ object = Object.get_by_ap_id(activity.data["object"])
+ assert object.data["like_count"] == 20
+ end
+
test "when replying to a conversation / participation, it will set the correct context id even if no explicit reply_to is given" do
user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
--
cgit v1.2.3
From f5bda09de648a6de3151c8614005ebc70447facb Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 22 Apr 2020 19:02:22 +0200
Subject: Stats: Use `invisible` property for filtering.
---
test/stats_test.exs | 1 -
1 file changed, 1 deletion(-)
(limited to 'test')
diff --git a/test/stats_test.exs b/test/stats_test.exs
index 73c7c1495..c1aeb2c7f 100644
--- a/test/stats_test.exs
+++ b/test/stats_test.exs
@@ -11,7 +11,6 @@ defmodule Pleroma.StatsTest do
test "it ignores internal users" do
_user = insert(:user, local: true)
_internal = insert(:user, local: true, nickname: nil)
- _internal = insert(:user, local: true, nickname: "internal.dude")
_internal = Pleroma.Web.ActivityPub.Relay.get_actor()
assert match?(%{stats: %{user_count: 1}}, Pleroma.Stats.calculate_stat_data())
--
cgit v1.2.3
From 7d38197894692306c940b55045b91d563e138284 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 23 Apr 2020 13:33:30 +0200
Subject: CommonAPI: Don't make repeating announces possible
---
test/web/common_api/common_api_test.exs | 18 +++++++++++++++---
test/web/common_api/common_api_utils_test.exs | 20 --------------------
2 files changed, 15 insertions(+), 23 deletions(-)
(limited to 'test')
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index 68a29108a..e87193c83 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -283,6 +283,16 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, %Activity{}, _} = CommonAPI.repeat(activity.id, user)
end
+ test "can't repeat a repeat" do
+ user = insert(:user)
+ other_user = insert(:user)
+ {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
+
+ {:ok, %Activity{} = announce, _} = CommonAPI.repeat(activity.id, other_user)
+
+ refute match?({:ok, %Activity{}, _}, CommonAPI.repeat(announce.id, user))
+ end
+
test "repeating a status privately" do
user = insert(:user)
other_user = insert(:user)
@@ -312,8 +322,8 @@ defmodule Pleroma.Web.CommonAPITest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
- {:ok, %Activity{} = activity, object} = CommonAPI.repeat(activity.id, user)
- {:ok, ^activity, ^object} = CommonAPI.repeat(activity.id, user)
+ {:ok, %Activity{} = announce, object} = CommonAPI.repeat(activity.id, user)
+ {:ok, ^announce, ^object} = CommonAPI.repeat(activity.id, user)
end
test "favoriting a status twice returns ok, but without the like activity" do
@@ -387,7 +397,9 @@ defmodule Pleroma.Web.CommonAPITest do
user = refresh_record(user)
- assert {:ok, ^activity} = CommonAPI.unpin(activity.id, user)
+ id = activity.id
+
+ assert match?({:ok, %{id: ^id}}, CommonAPI.unpin(activity.id, user))
user = refresh_record(user)
diff --git a/test/web/common_api/common_api_utils_test.exs b/test/web/common_api/common_api_utils_test.exs
index b21445fe9..18a3b3b87 100644
--- a/test/web/common_api/common_api_utils_test.exs
+++ b/test/web/common_api/common_api_utils_test.exs
@@ -335,26 +335,6 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
end
end
- describe "get_by_id_or_ap_id/1" do
- test "get activity by id" do
- activity = insert(:note_activity)
- %Pleroma.Activity{} = note = Utils.get_by_id_or_ap_id(activity.id)
- assert note.id == activity.id
- end
-
- test "get activity by ap_id" do
- activity = insert(:note_activity)
- %Pleroma.Activity{} = note = Utils.get_by_id_or_ap_id(activity.data["object"])
- assert note.id == activity.id
- end
-
- test "get activity by object when type isn't `Create` " do
- activity = insert(:like_activity)
- %Pleroma.Activity{} = like = Utils.get_by_id_or_ap_id(activity.id)
- assert like.data["object"] == activity.data["object"]
- end
- end
-
describe "to_master_date/1" do
test "removes microseconds from date (NaiveDateTime)" do
assert Utils.to_masto_date(~N[2015-01-23 23:50:07.123]) == "2015-01-23T23:50:07.000Z"
--
cgit v1.2.3
From f362836742aabd5b60b92c1296f2bbb6d83a3d59 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Fri, 24 Apr 2020 14:46:59 +0400
Subject: Support validation for inline OpenAPI schema and automatic tests for
examples
---
test/support/api_spec_helpers.ex | 57 ++++++++++++++++++++++
test/support/conn_case.ex | 36 ++++++++++++++
test/web/api_spec/app_operation_test.exs | 45 -----------------
test/web/api_spec/schema_examples_test.exs | 43 ++++++++++++++++
.../controllers/app_controller_test.exs | 4 +-
.../controllers/custom_emoji_controller_test.exs | 17 +------
.../controllers/domain_block_controller_test.exs | 28 +++--------
7 files changed, 146 insertions(+), 84 deletions(-)
create mode 100644 test/support/api_spec_helpers.ex
delete mode 100644 test/web/api_spec/app_operation_test.exs
create mode 100644 test/web/api_spec/schema_examples_test.exs
(limited to 'test')
diff --git a/test/support/api_spec_helpers.ex b/test/support/api_spec_helpers.ex
new file mode 100644
index 000000000..80c69c788
--- /dev/null
+++ b/test/support/api_spec_helpers.ex
@@ -0,0 +1,57 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Tests.ApiSpecHelpers do
+ @moduledoc """
+ OpenAPI spec test helpers
+ """
+
+ import ExUnit.Assertions
+
+ alias OpenApiSpex.Cast.Error
+ alias OpenApiSpex.Reference
+ alias OpenApiSpex.Schema
+
+ def assert_schema(value, schema) do
+ api_spec = Pleroma.Web.ApiSpec.spec()
+
+ case OpenApiSpex.cast_value(value, schema, api_spec) do
+ {:ok, data} ->
+ data
+
+ {:error, errors} ->
+ errors =
+ Enum.map(errors, fn error ->
+ message = Error.message(error)
+ path = Error.path_to_string(error)
+ "#{message} at #{path}"
+ end)
+
+ flunk(
+ "Value does not conform to schema #{schema.title}: #{Enum.join(errors, "\n")}\n#{
+ inspect(value)
+ }"
+ )
+ end
+ end
+
+ def resolve_schema(%Schema{} = schema), do: schema
+
+ def resolve_schema(%Reference{} = ref) do
+ schemas = Pleroma.Web.ApiSpec.spec().components.schemas
+ Reference.resolve_schema(ref, schemas)
+ end
+
+ def api_operations do
+ paths = Pleroma.Web.ApiSpec.spec().paths
+
+ Enum.flat_map(paths, fn {_, path_item} ->
+ path_item
+ |> Map.take([:delete, :get, :head, :options, :patch, :post, :put, :trace])
+ |> Map.values()
+ |> Enum.reject(&is_nil/1)
+ |> Enum.uniq()
+ end)
+ end
+end
diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex
index 064874201..781622476 100644
--- a/test/support/conn_case.ex
+++ b/test/support/conn_case.ex
@@ -51,6 +51,42 @@ defmodule Pleroma.Web.ConnCase do
%{user: user, token: token, conn: conn}
end
+ defp json_response_and_validate_schema(conn, status \\ nil) do
+ content_type =
+ conn
+ |> Plug.Conn.get_resp_header("content-type")
+ |> List.first()
+ |> String.split(";")
+ |> List.first()
+
+ status = status || conn.status
+
+ %{private: %{open_api_spex: %{operation_id: op_id, operation_lookup: lookup, spec: spec}}} =
+ conn
+
+ schema = lookup[op_id].responses[status].content[content_type].schema
+ json = json_response(conn, status)
+
+ case OpenApiSpex.cast_value(json, schema, spec) do
+ {:ok, _data} ->
+ json
+
+ {:error, errors} ->
+ errors =
+ Enum.map(errors, fn error ->
+ message = OpenApiSpex.Cast.Error.message(error)
+ path = OpenApiSpex.Cast.Error.path_to_string(error)
+ "#{message} at #{path}"
+ end)
+
+ flunk(
+ "Response does not conform to schema of #{op_id} operation: #{
+ Enum.join(errors, "\n")
+ }\n#{inspect(json)}"
+ )
+ end
+ end
+
defp ensure_federating_or_authenticated(conn, url, user) do
initial_setting = Config.get([:instance, :federating])
on_exit(fn -> Config.put([:instance, :federating], initial_setting) end)
diff --git a/test/web/api_spec/app_operation_test.exs b/test/web/api_spec/app_operation_test.exs
deleted file mode 100644
index 5b96abb44..000000000
--- a/test/web/api_spec/app_operation_test.exs
+++ /dev/null
@@ -1,45 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Web.ApiSpec.AppOperationTest do
- use Pleroma.Web.ConnCase, async: true
-
- alias Pleroma.Web.ApiSpec
- alias Pleroma.Web.ApiSpec.Schemas.AppCreateRequest
- alias Pleroma.Web.ApiSpec.Schemas.AppCreateResponse
-
- import OpenApiSpex.TestAssertions
- import Pleroma.Factory
-
- test "AppCreateRequest example matches schema" do
- api_spec = ApiSpec.spec()
- schema = AppCreateRequest.schema()
- assert_schema(schema.example, "AppCreateRequest", api_spec)
- end
-
- test "AppCreateResponse example matches schema" do
- api_spec = ApiSpec.spec()
- schema = AppCreateResponse.schema()
- assert_schema(schema.example, "AppCreateResponse", api_spec)
- end
-
- test "AppController produces a AppCreateResponse", %{conn: conn} do
- api_spec = ApiSpec.spec()
- app_attrs = build(:oauth_app)
-
- json =
- conn
- |> put_req_header("content-type", "application/json")
- |> post(
- "/api/v1/apps",
- Jason.encode!(%{
- client_name: app_attrs.client_name,
- redirect_uris: app_attrs.redirect_uris
- })
- )
- |> json_response(200)
-
- assert_schema(json, "AppCreateResponse", api_spec)
- end
-end
diff --git a/test/web/api_spec/schema_examples_test.exs b/test/web/api_spec/schema_examples_test.exs
new file mode 100644
index 000000000..88b6f07cb
--- /dev/null
+++ b/test/web/api_spec/schema_examples_test.exs
@@ -0,0 +1,43 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ApiSpec.SchemaExamplesTest do
+ use ExUnit.Case, async: true
+ import Pleroma.Tests.ApiSpecHelpers
+
+ @content_type "application/json"
+
+ for operation <- api_operations() do
+ describe operation.operationId <> " Request Body" do
+ if operation.requestBody do
+ @media_type operation.requestBody.content[@content_type]
+ @schema resolve_schema(@media_type.schema)
+
+ if @media_type.example do
+ test "request body media type example matches schema" do
+ assert_schema(@media_type.example, @schema)
+ end
+ end
+
+ if @schema.example do
+ test "request body schema example matches schema" do
+ assert_schema(@schema.example, @schema)
+ end
+ end
+ end
+ end
+
+ for {status, response} <- operation.responses do
+ describe "#{operation.operationId} - #{status} Response" do
+ @schema resolve_schema(response.content[@content_type].schema)
+
+ if @schema.example do
+ test "example matches schema" do
+ assert_schema(@schema.example, @schema)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/test/web/mastodon_api/controllers/app_controller_test.exs b/test/web/mastodon_api/controllers/app_controller_test.exs
index e7b11d14e..a0b8b126c 100644
--- a/test/web/mastodon_api/controllers/app_controller_test.exs
+++ b/test/web/mastodon_api/controllers/app_controller_test.exs
@@ -27,7 +27,7 @@ defmodule Pleroma.Web.MastodonAPI.AppControllerTest do
"vapid_key" => Push.vapid_config() |> Keyword.get(:public_key)
}
- assert expected == json_response(conn, 200)
+ assert expected == json_response_and_validate_schema(conn, 200)
end
test "creates an oauth app", %{conn: conn} do
@@ -55,6 +55,6 @@ defmodule Pleroma.Web.MastodonAPI.AppControllerTest do
"vapid_key" => Push.vapid_config() |> Keyword.get(:public_key)
}
- assert expected == json_response(conn, 200)
+ assert expected == json_response_and_validate_schema(conn, 200)
end
end
diff --git a/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs b/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs
index 0b2ffa470..4222556a4 100644
--- a/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs
+++ b/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs
@@ -5,15 +5,13 @@
defmodule Pleroma.Web.MastodonAPI.CustomEmojiControllerTest do
use Pleroma.Web.ConnCase, async: true
alias Pleroma.Web.ApiSpec
- alias Pleroma.Web.ApiSpec.Schemas.CustomEmoji
- alias Pleroma.Web.ApiSpec.Schemas.CustomEmojisResponse
import OpenApiSpex.TestAssertions
test "with tags", %{conn: conn} do
assert resp =
conn
|> get("/api/v1/custom_emojis")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert [emoji | _body] = resp
assert Map.has_key?(emoji, "shortcode")
@@ -23,19 +21,6 @@ defmodule Pleroma.Web.MastodonAPI.CustomEmojiControllerTest do
assert Map.has_key?(emoji, "category")
assert Map.has_key?(emoji, "url")
assert Map.has_key?(emoji, "visible_in_picker")
- assert_schema(resp, "CustomEmojisResponse", ApiSpec.spec())
assert_schema(emoji, "CustomEmoji", ApiSpec.spec())
end
-
- test "CustomEmoji example matches schema" do
- api_spec = ApiSpec.spec()
- schema = CustomEmoji.schema()
- assert_schema(schema.example, "CustomEmoji", api_spec)
- end
-
- test "CustomEmojisResponse example matches schema" do
- api_spec = ApiSpec.spec()
- schema = CustomEmojisResponse.schema()
- assert_schema(schema.example, "CustomEmojisResponse", api_spec)
- end
end
diff --git a/test/web/mastodon_api/controllers/domain_block_controller_test.exs b/test/web/mastodon_api/controllers/domain_block_controller_test.exs
index d66190c90..01a24afcf 100644
--- a/test/web/mastodon_api/controllers/domain_block_controller_test.exs
+++ b/test/web/mastodon_api/controllers/domain_block_controller_test.exs
@@ -6,11 +6,8 @@ defmodule Pleroma.Web.MastodonAPI.DomainBlockControllerTest do
use Pleroma.Web.ConnCase
alias Pleroma.User
- alias Pleroma.Web.ApiSpec
- alias Pleroma.Web.ApiSpec.Schemas.DomainBlocksResponse
import Pleroma.Factory
- import OpenApiSpex.TestAssertions
test "blocking / unblocking a domain" do
%{user: user, conn: conn} = oauth_access(["write:blocks"])
@@ -21,7 +18,7 @@ defmodule Pleroma.Web.MastodonAPI.DomainBlockControllerTest do
|> put_req_header("content-type", "application/json")
|> post("/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"})
- assert %{} = json_response(ret_conn, 200)
+ assert %{} == json_response_and_validate_schema(ret_conn, 200)
user = User.get_cached_by_ap_id(user.ap_id)
assert User.blocks?(user, other_user)
@@ -30,7 +27,7 @@ defmodule Pleroma.Web.MastodonAPI.DomainBlockControllerTest do
|> put_req_header("content-type", "application/json")
|> delete("/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"})
- assert %{} = json_response(ret_conn, 200)
+ assert %{} == json_response_and_validate_schema(ret_conn, 200)
user = User.get_cached_by_ap_id(user.ap_id)
refute User.blocks?(user, other_user)
end
@@ -41,21 +38,10 @@ defmodule Pleroma.Web.MastodonAPI.DomainBlockControllerTest do
{:ok, user} = User.block_domain(user, "bad.site")
{:ok, user} = User.block_domain(user, "even.worse.site")
- conn =
- conn
- |> assign(:user, user)
- |> get("/api/v1/domain_blocks")
-
- domain_blocks = json_response(conn, 200)
-
- assert "bad.site" in domain_blocks
- assert "even.worse.site" in domain_blocks
- assert_schema(domain_blocks, "DomainBlocksResponse", ApiSpec.spec())
- end
-
- test "DomainBlocksResponse example matches schema" do
- api_spec = ApiSpec.spec()
- schema = DomainBlocksResponse.schema()
- assert_schema(schema.example, "DomainBlocksResponse", api_spec)
+ assert ["even.worse.site", "bad.site"] ==
+ conn
+ |> assign(:user, user)
+ |> get("/api/v1/domain_blocks")
+ |> json_response_and_validate_schema(200)
end
end
--
cgit v1.2.3
From bbf8554c975ea1ba9b5c809a7891ec0fb4a8e537 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 24 Apr 2020 13:48:13 +0200
Subject: ActivitPub: Remove `like` function.
We don't need another way to build likes.
---
test/web/activity_pub/activity_pub_test.exs | 77 +++--------------------------
test/web/activity_pub/utils_test.exs | 5 +-
2 files changed, 9 insertions(+), 73 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 6410df49b..53176917e 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -994,72 +994,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
end
end
- describe "like an object" do
- test_with_mock "sends an activity to federation", Federator, [:passthrough], [] do
- Config.put([:instance, :federating], true)
- note_activity = insert(:note_activity)
- assert object_activity = Object.normalize(note_activity)
-
- user = insert(:user)
-
- {:ok, like_activity, _object} = ActivityPub.like(user, object_activity)
- assert called(Federator.publish(like_activity))
- end
-
- test "returns exist activity if object already liked" do
- note_activity = insert(:note_activity)
- assert object_activity = Object.normalize(note_activity)
-
- user = insert(:user)
-
- {:ok, like_activity, _object} = ActivityPub.like(user, object_activity)
-
- {:ok, like_activity_exist, _object} = ActivityPub.like(user, object_activity)
- assert like_activity == like_activity_exist
- end
-
- test "reverts like activity on error" do
- note_activity = insert(:note_activity)
- object = Object.normalize(note_activity)
- user = insert(:user)
-
- with_mock(Utils, [:passthrough], maybe_federate: fn _ -> {:error, :reverted} end) do
- assert {:error, :reverted} = ActivityPub.like(user, object)
- end
-
- assert Repo.aggregate(Activity, :count, :id) == 1
- assert Repo.get(Object, object.id) == object
- end
-
- test "adds a like activity to the db" do
- note_activity = insert(:note_activity)
- assert object = Object.normalize(note_activity)
-
- user = insert(:user)
- user_two = insert(:user)
-
- {:ok, like_activity, object} = ActivityPub.like(user, object)
-
- assert like_activity.data["actor"] == user.ap_id
- assert like_activity.data["type"] == "Like"
- assert like_activity.data["object"] == object.data["id"]
- assert like_activity.data["to"] == [User.ap_followers(user), note_activity.data["actor"]]
- assert like_activity.data["context"] == object.data["context"]
- assert object.data["like_count"] == 1
- assert object.data["likes"] == [user.ap_id]
-
- # Just return the original activity if the user already liked it.
- {:ok, same_like_activity, object} = ActivityPub.like(user, object)
-
- assert like_activity == same_like_activity
- assert object.data["likes"] == [user.ap_id]
- assert object.data["like_count"] == 1
-
- {:ok, _like_activity, object} = ActivityPub.like(user_two, object)
- assert object.data["like_count"] == 2
- end
- end
-
describe "unliking" do
test_with_mock "sends an activity to federation", Federator, [:passthrough], [] do
Config.put([:instance, :federating], true)
@@ -1071,7 +1005,8 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, object} = ActivityPub.unlike(user, object)
refute called(Federator.publish())
- {:ok, _like_activity, object} = ActivityPub.like(user, object)
+ {:ok, _like_activity} = CommonAPI.favorite(user, note_activity.id)
+ object = Object.get_by_id(object.id)
assert object.data["like_count"] == 1
{:ok, unlike_activity, _, object} = ActivityPub.unlike(user, object)
@@ -1082,10 +1017,10 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
test "reverts unliking on error" do
note_activity = insert(:note_activity)
- object = Object.normalize(note_activity)
user = insert(:user)
- {:ok, like_activity, object} = ActivityPub.like(user, object)
+ {:ok, like_activity} = CommonAPI.favorite(user, note_activity.id)
+ object = Object.normalize(note_activity)
assert object.data["like_count"] == 1
with_mock(Utils, [:passthrough], maybe_federate: fn _ -> {:error, :reverted} end) do
@@ -1106,7 +1041,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, object} = ActivityPub.unlike(user, object)
assert object.data["like_count"] == 0
- {:ok, like_activity, object} = ActivityPub.like(user, object)
+ {:ok, like_activity} = CommonAPI.favorite(user, note_activity.id)
+
+ object = Object.get_by_id(object.id)
assert object.data["like_count"] == 1
{:ok, unlike_activity, _, object} = ActivityPub.unlike(user, object)
diff --git a/test/web/activity_pub/utils_test.exs b/test/web/activity_pub/utils_test.exs
index e913a5148..b0bfed917 100644
--- a/test/web/activity_pub/utils_test.exs
+++ b/test/web/activity_pub/utils_test.exs
@@ -224,8 +224,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do
object = Object.normalize(activity)
{:ok, [vote], object} = CommonAPI.vote(other_user, object, [0])
- vote_object = Object.normalize(vote)
- {:ok, _activity, _object} = ActivityPub.like(user, vote_object)
+ {:ok, _activity} = CommonAPI.favorite(user, activity.id)
[fetched_vote] = Utils.get_existing_votes(other_user.ap_id, object)
assert fetched_vote.id == vote.id
end
@@ -346,7 +345,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do
user = insert(:user)
refute Utils.get_existing_like(user.ap_id, object)
- {:ok, like_activity, _object} = ActivityPub.like(user, object)
+ {:ok, like_activity} = CommonAPI.favorite(user, note_activity.id)
assert ^like_activity = Utils.get_existing_like(user.ap_id, object)
end
--
cgit v1.2.3
From cb12585098e0cc1e2e85d253812e1898e8034b7f Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 24 Apr 2020 14:37:53 +0200
Subject: Announcements: Prevent race condition.
---
test/web/common_api/common_api_test.exs | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)
(limited to 'test')
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index e87193c83..1758662b0 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -48,6 +48,33 @@ defmodule Pleroma.Web.CommonAPITest do
assert object.data["like_count"] == 20
end
+ test "repeating race condition" do
+ user = insert(:user)
+ users_serial = insert_list(10, :user)
+ users = insert_list(10, :user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "."})
+
+ users_serial
+ |> Enum.map(fn user ->
+ CommonAPI.repeat(activity.id, user)
+ end)
+
+ object = Object.get_by_ap_id(activity.data["object"])
+ assert object.data["announcement_count"] == 10
+
+ users
+ |> Enum.map(fn user ->
+ Task.async(fn ->
+ CommonAPI.repeat(activity.id, user)
+ end)
+ end)
+ |> Enum.map(&Task.await/1)
+
+ object = Object.get_by_ap_id(activity.data["object"])
+ assert object.data["announcement_count"] == 20
+ end
+
test "when replying to a conversation / participation, it will set the correct context id even if no explicit reply_to is given" do
user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
--
cgit v1.2.3
From 6e625a427cdc829714ad0365560d79aa4ee9c2e5 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Wed, 4 Dec 2019 09:49:17 +0300
Subject: reply filtering
---
test/web/activity_pub/activity_pub_test.exs | 486 ++++++++++++++++++++++++++++
1 file changed, 486 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 53176917e..8a1638a23 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -1910,4 +1910,490 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
ActivityPub.move(old_user, new_user)
end
end
+
+ test "doesn't retrieve replies activities with exclude_replies" do
+ user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "yeah"})
+
+ {:ok, _reply} =
+ CommonAPI.post(user, %{"status" => "yeah", "in_reply_to_status_id" => activity.id})
+
+ [result] = ActivityPub.fetch_public_activities(%{"exclude_replies" => "true"})
+
+ assert result.id == activity.id
+
+ assert length(ActivityPub.fetch_public_activities()) == 2
+ end
+
+ describe "replies filtering with public messages" do
+ setup :public_messages
+
+ test "public timeline", %{users: %{u1: user}} do
+ activities_ids =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("local_only", false)
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("user", user)
+ |> ActivityPub.fetch_public_activities()
+ |> Enum.map(& &1.id)
+
+ assert length(activities_ids) == 16
+ end
+
+ test "public timeline with reply_visibility `following`", %{
+ users: %{u1: user},
+ u1: u1,
+ u2: u2,
+ u3: u3,
+ u4: u4,
+ activities: activities
+ } do
+ activities_ids =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("local_only", false)
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("reply_visibility", "following")
+ |> Map.put("user", user)
+ |> ActivityPub.fetch_public_activities()
+ |> Enum.map(& &1.id)
+
+ assert length(activities_ids) == 14
+
+ visible_ids =
+ Map.values(u1) ++ Map.values(u2) ++ Map.values(u4) ++ Map.values(activities) ++ [u3[:r1]]
+
+ assert Enum.all?(visible_ids, &(&1 in activities_ids))
+ end
+
+ test "public timeline with reply_visibility `self`", %{
+ users: %{u1: user},
+ u1: u1,
+ u2: u2,
+ u3: u3,
+ u4: u4,
+ activities: activities
+ } do
+ activities_ids =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("local_only", false)
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("reply_visibility", "self")
+ |> Map.put("user", user)
+ |> ActivityPub.fetch_public_activities()
+ |> Enum.map(& &1.id)
+
+ assert length(activities_ids) == 10
+ visible_ids = Map.values(u1) ++ [u2[:r1], u3[:r1], u4[:r1]] ++ Map.values(activities)
+ assert Enum.all?(visible_ids, &(&1 in activities_ids))
+ end
+
+ test "home timeline", %{
+ users: %{u1: user},
+ activities: activities,
+ u1: u1,
+ u2: u2,
+ u3: u3,
+ u4: u4
+ } do
+ params =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("user", user)
+
+ activities_ids =
+ ActivityPub.fetch_activities([user.ap_id | User.following(user)], params)
+ |> Enum.map(& &1.id)
+
+ assert length(activities_ids) == 13
+
+ visible_ids =
+ Map.values(u1) ++
+ Map.values(u3) ++
+ [
+ activities[:a1],
+ activities[:a2],
+ activities[:a4],
+ u2[:r1],
+ u2[:r3],
+ u4[:r1],
+ u4[:r2]
+ ]
+
+ assert Enum.all?(visible_ids, &(&1 in activities_ids))
+ end
+
+ test "home timeline with reply_visibility `following`", %{
+ users: %{u1: user},
+ activities: activities,
+ u1: u1,
+ u2: u2,
+ u3: u3,
+ u4: u4
+ } do
+ params =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("user", user)
+ |> Map.put("reply_visibility", "following")
+
+ activities_ids =
+ ActivityPub.fetch_activities([user.ap_id | User.following(user)], params)
+ |> Enum.map(& &1.id)
+
+ assert length(activities_ids) == 11
+
+ visible_ids =
+ Map.values(u1) ++
+ [
+ activities[:a1],
+ activities[:a2],
+ activities[:a4],
+ u2[:r1],
+ u2[:r3],
+ u3[:r1],
+ u4[:r1],
+ u4[:r2]
+ ]
+
+ assert Enum.all?(visible_ids, &(&1 in activities_ids))
+ end
+
+ test "home timeline with reply_visibility `self`", %{
+ users: %{u1: user},
+ activities: activities,
+ u1: u1,
+ u2: u2,
+ u3: u3,
+ u4: u4
+ } do
+ params =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("user", user)
+ |> Map.put("reply_visibility", "self")
+
+ activities_ids =
+ ActivityPub.fetch_activities([user.ap_id | User.following(user)], params)
+ |> Enum.map(& &1.id)
+
+ assert length(activities_ids) == 9
+
+ visible_ids =
+ Map.values(u1) ++
+ [
+ activities[:a1],
+ activities[:a2],
+ activities[:a4],
+ u2[:r1],
+ u3[:r1],
+ u4[:r1]
+ ]
+
+ assert Enum.all?(visible_ids, &(&1 in activities_ids))
+ end
+ end
+
+ describe "replies filtering with private messages" do
+ setup :private_messages
+
+ test "public timeline", %{users: %{u1: user}} do
+ activities_ids =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("local_only", false)
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("user", user)
+ |> ActivityPub.fetch_public_activities()
+ |> Enum.map(& &1.id)
+
+ assert activities_ids == []
+ end
+
+ test "public timeline with default reply_visibility `following`", %{users: %{u1: user}} do
+ activities_ids =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("local_only", false)
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("reply_visibility", "following")
+ |> Map.put("user", user)
+ |> ActivityPub.fetch_public_activities()
+ |> Enum.map(& &1.id)
+
+ assert activities_ids == []
+ end
+
+ test "public timeline with default reply_visibility `self`", %{users: %{u1: user}} do
+ activities_ids =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("local_only", false)
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("reply_visibility", "self")
+ |> Map.put("user", user)
+ |> ActivityPub.fetch_public_activities()
+ |> Enum.map(& &1.id)
+
+ assert activities_ids == []
+ end
+
+ test "home timeline", %{users: %{u1: user}} do
+ params =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("user", user)
+
+ activities_ids =
+ ActivityPub.fetch_activities([user.ap_id | User.following(user)], params)
+ |> Enum.map(& &1.id)
+
+ assert length(activities_ids) == 12
+ end
+
+ test "home timeline with default reply_visibility `following`", %{users: %{u1: user}} do
+ params =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("user", user)
+ |> Map.put("reply_visibility", "following")
+
+ activities_ids =
+ ActivityPub.fetch_activities([user.ap_id | User.following(user)], params)
+ |> Enum.map(& &1.id)
+
+ assert length(activities_ids) == 12
+ end
+
+ test "home timeline with default reply_visibility `self`", %{
+ users: %{u1: user},
+ activities: activities,
+ u1: u1,
+ u2: u2,
+ u3: u3,
+ u4: u4
+ } do
+ params =
+ %{}
+ |> Map.put("type", ["Create", "Announce"])
+ |> Map.put("blocking_user", user)
+ |> Map.put("muting_user", user)
+ |> Map.put("user", user)
+ |> Map.put("reply_visibility", "self")
+
+ activities_ids =
+ ActivityPub.fetch_activities([user.ap_id | User.following(user)], params)
+ |> Enum.map(& &1.id)
+
+ assert length(activities_ids) == 10
+
+ visible_ids =
+ Map.values(u1) ++ Map.values(u4) ++ [u2[:r1], u3[:r1]] ++ Map.values(activities)
+
+ assert Enum.all?(visible_ids, &(&1 in activities_ids))
+ end
+ end
+
+ defp public_messages(_) do
+ [u1, u2, u3, u4] = insert_list(4, :user)
+ {:ok, u1} = User.follow(u1, u2)
+ {:ok, u2} = User.follow(u2, u1)
+ {:ok, u1} = User.follow(u1, u4)
+ {:ok, u4} = User.follow(u4, u1)
+
+ {:ok, u2} = User.follow(u2, u3)
+ {:ok, u3} = User.follow(u3, u2)
+
+ {:ok, a1} = CommonAPI.post(u1, %{"status" => "Status"})
+
+ {:ok, r1_1} =
+ CommonAPI.post(u2, %{
+ "status" => "@#{u1.nickname} reply from u2 to u1",
+ "in_reply_to_status_id" => a1.id
+ })
+
+ {:ok, r1_2} =
+ CommonAPI.post(u3, %{
+ "status" => "@#{u1.nickname} reply from u3 to u1",
+ "in_reply_to_status_id" => a1.id
+ })
+
+ {:ok, r1_3} =
+ CommonAPI.post(u4, %{
+ "status" => "@#{u1.nickname} reply from u4 to u1",
+ "in_reply_to_status_id" => a1.id
+ })
+
+ {:ok, a2} = CommonAPI.post(u2, %{"status" => "Status"})
+
+ {:ok, r2_1} =
+ CommonAPI.post(u1, %{
+ "status" => "@#{u2.nickname} reply from u1 to u2",
+ "in_reply_to_status_id" => a2.id
+ })
+
+ {:ok, r2_2} =
+ CommonAPI.post(u3, %{
+ "status" => "@#{u2.nickname} reply from u3 to u2",
+ "in_reply_to_status_id" => a2.id
+ })
+
+ {:ok, r2_3} =
+ CommonAPI.post(u4, %{
+ "status" => "@#{u2.nickname} reply from u4 to u2",
+ "in_reply_to_status_id" => a2.id
+ })
+
+ {:ok, a3} = CommonAPI.post(u3, %{"status" => "Status"})
+
+ {:ok, r3_1} =
+ CommonAPI.post(u1, %{
+ "status" => "@#{u3.nickname} reply from u1 to u3",
+ "in_reply_to_status_id" => a3.id
+ })
+
+ {:ok, r3_2} =
+ CommonAPI.post(u2, %{
+ "status" => "@#{u3.nickname} reply from u2 to u3",
+ "in_reply_to_status_id" => a3.id
+ })
+
+ {:ok, r3_3} =
+ CommonAPI.post(u4, %{
+ "status" => "@#{u3.nickname} reply from u4 to u3",
+ "in_reply_to_status_id" => a3.id
+ })
+
+ {:ok, a4} = CommonAPI.post(u4, %{"status" => "Status"})
+
+ {:ok, r4_1} =
+ CommonAPI.post(u1, %{
+ "status" => "@#{u4.nickname} reply from u1 to u4",
+ "in_reply_to_status_id" => a4.id
+ })
+
+ {:ok, r4_2} =
+ CommonAPI.post(u2, %{
+ "status" => "@#{u4.nickname} reply from u2 to u4",
+ "in_reply_to_status_id" => a4.id
+ })
+
+ {:ok, r4_3} =
+ CommonAPI.post(u3, %{
+ "status" => "@#{u4.nickname} reply from u3 to u4",
+ "in_reply_to_status_id" => a4.id
+ })
+
+ {:ok,
+ users: %{u1: u1, u2: u2, u3: u3, u4: u4},
+ activities: %{a1: a1.id, a2: a2.id, a3: a3.id, a4: a4.id},
+ u1: %{r1: r1_1.id, r2: r1_2.id, r3: r1_3.id},
+ u2: %{r1: r2_1.id, r2: r2_2.id, r3: r2_3.id},
+ u3: %{r1: r3_1.id, r2: r3_2.id, r3: r3_3.id},
+ u4: %{r1: r4_1.id, r2: r4_2.id, r3: r4_3.id}}
+ end
+
+ defp private_messages(_) do
+ [u1, u2, u3, u4] = insert_list(4, :user)
+ {:ok, u1} = User.follow(u1, u2)
+ {:ok, u2} = User.follow(u2, u1)
+ {:ok, u1} = User.follow(u1, u3)
+ {:ok, u3} = User.follow(u3, u1)
+ {:ok, u1} = User.follow(u1, u4)
+ {:ok, u4} = User.follow(u4, u1)
+
+ {:ok, u2} = User.follow(u2, u3)
+ {:ok, u3} = User.follow(u3, u2)
+
+ {:ok, a1} = CommonAPI.post(u1, %{"status" => "Status", "visibility" => "private"})
+
+ {:ok, r1_1} =
+ CommonAPI.post(u2, %{
+ "status" => "@#{u1.nickname} reply from u2 to u1",
+ "in_reply_to_status_id" => a1.id,
+ "visibility" => "private"
+ })
+
+ {:ok, r1_2} =
+ CommonAPI.post(u3, %{
+ "status" => "@#{u1.nickname} reply from u3 to u1",
+ "in_reply_to_status_id" => a1.id,
+ "visibility" => "private"
+ })
+
+ {:ok, r1_3} =
+ CommonAPI.post(u4, %{
+ "status" => "@#{u1.nickname} reply from u4 to u1",
+ "in_reply_to_status_id" => a1.id,
+ "visibility" => "private"
+ })
+
+ {:ok, a2} = CommonAPI.post(u2, %{"status" => "Status", "visibility" => "private"})
+
+ {:ok, r2_1} =
+ CommonAPI.post(u1, %{
+ "status" => "@#{u2.nickname} reply from u1 to u2",
+ "in_reply_to_status_id" => a2.id,
+ "visibility" => "private"
+ })
+
+ {:ok, r2_2} =
+ CommonAPI.post(u3, %{
+ "status" => "@#{u2.nickname} reply from u3 to u2",
+ "in_reply_to_status_id" => a2.id,
+ "visibility" => "private"
+ })
+
+ {:ok, a3} = CommonAPI.post(u3, %{"status" => "Status", "visibility" => "private"})
+
+ {:ok, r3_1} =
+ CommonAPI.post(u1, %{
+ "status" => "@#{u3.nickname} reply from u1 to u3",
+ "in_reply_to_status_id" => a3.id,
+ "visibility" => "private"
+ })
+
+ {:ok, r3_2} =
+ CommonAPI.post(u2, %{
+ "status" => "@#{u3.nickname} reply from u2 to u3",
+ "in_reply_to_status_id" => a3.id,
+ "visibility" => "private"
+ })
+
+ {:ok, a4} = CommonAPI.post(u4, %{"status" => "Status", "visibility" => "private"})
+
+ {:ok, r4_1} =
+ CommonAPI.post(u1, %{
+ "status" => "@#{u4.nickname} reply from u1 to u4",
+ "in_reply_to_status_id" => a4.id,
+ "visibility" => "private"
+ })
+
+ {:ok,
+ users: %{u1: u1, u2: u2, u3: u3, u4: u4},
+ activities: %{a1: a1.id, a2: a2.id, a3: a3.id, a4: a4.id},
+ u1: %{r1: r1_1.id, r2: r1_2.id, r3: r1_3.id},
+ u2: %{r1: r2_1.id, r2: r2_2.id},
+ u3: %{r1: r3_1.id, r2: r3_2.id},
+ u4: %{r1: r4_1.id}}
+ end
end
--
cgit v1.2.3
From 00e62161f64802317d7d789e7eac42c33f0540f5 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Fri, 24 Apr 2020 16:52:38 +0300
Subject: [#2409] Tested all auth setup configs in AuthTestControllerTest.
Adjusted :skip_plug definitions for some endpoints.
---
test/web/auth/auth_test_controller_test.exs | 242 +++++++++++++++++++++
test/web/auth/oauth_test_controller_test.exs | 49 -----
.../mastodon_api/mastodon_api_controller_test.exs | 33 ++-
3 files changed, 255 insertions(+), 69 deletions(-)
create mode 100644 test/web/auth/auth_test_controller_test.exs
delete mode 100644 test/web/auth/oauth_test_controller_test.exs
(limited to 'test')
diff --git a/test/web/auth/auth_test_controller_test.exs b/test/web/auth/auth_test_controller_test.exs
new file mode 100644
index 000000000..fed52b7f3
--- /dev/null
+++ b/test/web/auth/auth_test_controller_test.exs
@@ -0,0 +1,242 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Tests.AuthTestControllerTest do
+ use Pleroma.Web.ConnCase
+
+ import Pleroma.Factory
+
+ describe "do_oauth_check" do
+ test "serves with proper OAuth token (fulfilling requested scopes)" do
+ %{conn: good_token_conn, user: user} = oauth_access(["read"])
+
+ assert %{"user_id" => user.id} ==
+ good_token_conn
+ |> get("/test/authenticated_api/do_oauth_check")
+ |> json_response(200)
+
+ # Unintended usage (:api) — use with :authenticated_api instead
+ assert %{"user_id" => user.id} ==
+ good_token_conn
+ |> get("/test/api/do_oauth_check")
+ |> json_response(200)
+ end
+
+ test "fails on no token / missing scope(s)" do
+ %{conn: bad_token_conn} = oauth_access(["irrelevant_scope"])
+
+ bad_token_conn
+ |> get("/test/authenticated_api/do_oauth_check")
+ |> json_response(403)
+
+ bad_token_conn
+ |> assign(:token, nil)
+ |> get("/test/api/do_oauth_check")
+ |> json_response(403)
+ end
+ end
+
+ describe "fallback_oauth_check" do
+ test "serves with proper OAuth token (fulfilling requested scopes)" do
+ %{conn: good_token_conn, user: user} = oauth_access(["read"])
+
+ assert %{"user_id" => user.id} ==
+ good_token_conn
+ |> get("/test/api/fallback_oauth_check")
+ |> json_response(200)
+
+ # Unintended usage (:authenticated_api) — use with :api instead
+ assert %{"user_id" => user.id} ==
+ good_token_conn
+ |> get("/test/authenticated_api/fallback_oauth_check")
+ |> json_response(200)
+ end
+
+ test "for :api on public instance, drops :user and renders on no token / missing scope(s)" do
+ clear_config([:instance, :public], true)
+
+ %{conn: bad_token_conn} = oauth_access(["irrelevant_scope"])
+
+ assert %{"user_id" => nil} ==
+ bad_token_conn
+ |> get("/test/api/fallback_oauth_check")
+ |> json_response(200)
+
+ assert %{"user_id" => nil} ==
+ bad_token_conn
+ |> assign(:token, nil)
+ |> get("/test/api/fallback_oauth_check")
+ |> json_response(200)
+ end
+
+ test "for :api on private instance, fails on no token / missing scope(s)" do
+ clear_config([:instance, :public], false)
+
+ %{conn: bad_token_conn} = oauth_access(["irrelevant_scope"])
+
+ bad_token_conn
+ |> get("/test/api/fallback_oauth_check")
+ |> json_response(403)
+
+ bad_token_conn
+ |> assign(:token, nil)
+ |> get("/test/api/fallback_oauth_check")
+ |> json_response(403)
+ end
+ end
+
+ describe "skip_oauth_check" do
+ test "for :authenticated_api, serves if :user is set (regardless of token / token scopes)" do
+ user = insert(:user)
+
+ assert %{"user_id" => user.id} ==
+ build_conn()
+ |> assign(:user, user)
+ |> get("/test/authenticated_api/skip_oauth_check")
+ |> json_response(200)
+
+ %{conn: bad_token_conn, user: user} = oauth_access(["irrelevant_scope"])
+
+ assert %{"user_id" => user.id} ==
+ bad_token_conn
+ |> get("/test/authenticated_api/skip_oauth_check")
+ |> json_response(200)
+ end
+
+ test "serves via :api on public instance if :user is not set" do
+ clear_config([:instance, :public], true)
+
+ assert %{"user_id" => nil} ==
+ build_conn()
+ |> get("/test/api/skip_oauth_check")
+ |> json_response(200)
+
+ build_conn()
+ |> get("/test/authenticated_api/skip_oauth_check")
+ |> json_response(403)
+ end
+
+ test "fails on private instance if :user is not set" do
+ clear_config([:instance, :public], false)
+
+ build_conn()
+ |> get("/test/api/skip_oauth_check")
+ |> json_response(403)
+
+ build_conn()
+ |> get("/test/authenticated_api/skip_oauth_check")
+ |> json_response(403)
+ end
+ end
+
+ describe "fallback_oauth_skip_publicity_check" do
+ test "serves with proper OAuth token (fulfilling requested scopes)" do
+ %{conn: good_token_conn, user: user} = oauth_access(["read"])
+
+ assert %{"user_id" => user.id} ==
+ good_token_conn
+ |> get("/test/api/fallback_oauth_skip_publicity_check")
+ |> json_response(200)
+
+ # Unintended usage (:authenticated_api)
+ assert %{"user_id" => user.id} ==
+ good_token_conn
+ |> get("/test/authenticated_api/fallback_oauth_skip_publicity_check")
+ |> json_response(200)
+ end
+
+ test "for :api on private / public instance, drops :user and renders on token issue" do
+ %{conn: bad_token_conn} = oauth_access(["irrelevant_scope"])
+
+ for is_public <- [true, false] do
+ clear_config([:instance, :public], is_public)
+
+ assert %{"user_id" => nil} ==
+ bad_token_conn
+ |> get("/test/api/fallback_oauth_skip_publicity_check")
+ |> json_response(200)
+
+ assert %{"user_id" => nil} ==
+ bad_token_conn
+ |> assign(:token, nil)
+ |> get("/test/api/fallback_oauth_skip_publicity_check")
+ |> json_response(200)
+ end
+ end
+ end
+
+ describe "skip_oauth_skip_publicity_check" do
+ test "for :authenticated_api, serves if :user is set (regardless of token / token scopes)" do
+ user = insert(:user)
+
+ assert %{"user_id" => user.id} ==
+ build_conn()
+ |> assign(:user, user)
+ |> get("/test/authenticated_api/skip_oauth_skip_publicity_check")
+ |> json_response(200)
+
+ %{conn: bad_token_conn, user: user} = oauth_access(["irrelevant_scope"])
+
+ assert %{"user_id" => user.id} ==
+ bad_token_conn
+ |> get("/test/authenticated_api/skip_oauth_skip_publicity_check")
+ |> json_response(200)
+ end
+
+ test "for :api, serves on private and public instances regardless of whether :user is set" do
+ user = insert(:user)
+
+ for is_public <- [true, false] do
+ clear_config([:instance, :public], is_public)
+
+ assert %{"user_id" => nil} ==
+ build_conn()
+ |> get("/test/api/skip_oauth_skip_publicity_check")
+ |> json_response(200)
+
+ assert %{"user_id" => user.id} ==
+ build_conn()
+ |> assign(:user, user)
+ |> get("/test/api/skip_oauth_skip_publicity_check")
+ |> json_response(200)
+ end
+ end
+ end
+
+ describe "missing_oauth_check_definition" do
+ def test_missing_oauth_check_definition_failure(endpoint, expected_error) do
+ %{conn: conn} = oauth_access(["read", "write", "follow", "push", "admin"])
+
+ assert %{"error" => expected_error} ==
+ conn
+ |> get(endpoint)
+ |> json_response(403)
+ end
+
+ test "fails if served via :authenticated_api" do
+ test_missing_oauth_check_definition_failure(
+ "/test/authenticated_api/missing_oauth_check_definition",
+ "Security violation: OAuth scopes check was neither handled nor explicitly skipped."
+ )
+ end
+
+ test "fails if served via :api and the instance is private" do
+ clear_config([:instance, :public], false)
+
+ test_missing_oauth_check_definition_failure(
+ "/test/api/missing_oauth_check_definition",
+ "This resource requires authentication."
+ )
+ end
+
+ test "succeeds with dropped :user if served via :api on public instance" do
+ %{conn: conn} = oauth_access(["read", "write", "follow", "push", "admin"])
+
+ assert %{"user_id" => nil} ==
+ conn
+ |> get("/test/api/missing_oauth_check_definition")
+ |> json_response(200)
+ end
+ end
+end
diff --git a/test/web/auth/oauth_test_controller_test.exs b/test/web/auth/oauth_test_controller_test.exs
deleted file mode 100644
index a2f6009ac..000000000
--- a/test/web/auth/oauth_test_controller_test.exs
+++ /dev/null
@@ -1,49 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Tests.OAuthTestControllerTest do
- use Pleroma.Web.ConnCase
-
- import Pleroma.Factory
-
- setup %{conn: conn} do
- user = insert(:user)
- conn = assign(conn, :user, user)
- %{conn: conn, user: user}
- end
-
- test "missed_oauth", %{conn: conn} do
- res =
- conn
- |> get("/test/authenticated_api/missed_oauth")
- |> json_response(403)
-
- assert res ==
- %{
- "error" =>
- "Security violation: OAuth scopes check was neither handled nor explicitly skipped."
- }
- end
-
- test "skipped_oauth", %{conn: conn} do
- conn
- |> assign(:token, nil)
- |> get("/test/authenticated_api/skipped_oauth")
- |> json_response(200)
- end
-
- test "performed_oauth", %{user: user} do
- %{conn: good_token_conn} = oauth_access(["read"], user: user)
-
- good_token_conn
- |> get("/test/authenticated_api/performed_oauth")
- |> json_response(200)
-
- %{conn: bad_token_conn} = oauth_access(["follow"], user: user)
-
- bad_token_conn
- |> get("/test/authenticated_api/performed_oauth")
- |> json_response(403)
- end
-end
diff --git a/test/web/mastodon_api/mastodon_api_controller_test.exs b/test/web/mastodon_api/mastodon_api_controller_test.exs
index 75f184242..bb4bc4396 100644
--- a/test/web/mastodon_api/mastodon_api_controller_test.exs
+++ b/test/web/mastodon_api/mastodon_api_controller_test.exs
@@ -7,35 +7,28 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do
describe "empty_array/2 (stubs)" do
test "GET /api/v1/accounts/:id/identity_proofs" do
- %{user: user, conn: conn} = oauth_access(["n/a"])
+ %{user: user, conn: conn} = oauth_access(["read:accounts"])
- res =
- conn
- |> assign(:user, user)
- |> get("/api/v1/accounts/#{user.id}/identity_proofs")
- |> json_response(200)
-
- assert res == []
+ assert [] ==
+ conn
+ |> get("/api/v1/accounts/#{user.id}/identity_proofs")
+ |> json_response(200)
end
test "GET /api/v1/endorsements" do
%{conn: conn} = oauth_access(["read:accounts"])
- res =
- conn
- |> get("/api/v1/endorsements")
- |> json_response(200)
-
- assert res == []
+ assert [] ==
+ conn
+ |> get("/api/v1/endorsements")
+ |> json_response(200)
end
test "GET /api/v1/trends", %{conn: conn} do
- res =
- conn
- |> get("/api/v1/trends")
- |> json_response(200)
-
- assert res == []
+ assert [] ==
+ conn
+ |> get("/api/v1/trends")
+ |> json_response(200)
end
end
end
--
cgit v1.2.3
From d89cd0a19733eec27b79b768df2e30a68bfc6d6b Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 24 Apr 2020 18:25:26 +0200
Subject: Reply Filtering: Refactor.
---
test/web/activity_pub/activity_pub_test.exs | 13 ++++++++++---
1 file changed, 10 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 8a1638a23..edd7dfb22 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -1936,7 +1936,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
|> Map.put("local_only", false)
|> Map.put("blocking_user", user)
|> Map.put("muting_user", user)
- |> Map.put("user", user)
+ |> Map.put("reply_filtering_user", user)
|> ActivityPub.fetch_public_activities()
|> Enum.map(& &1.id)
@@ -1958,7 +1958,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
|> Map.put("blocking_user", user)
|> Map.put("muting_user", user)
|> Map.put("reply_visibility", "following")
- |> Map.put("user", user)
+ |> Map.put("reply_filtering_user", user)
|> ActivityPub.fetch_public_activities()
|> Enum.map(& &1.id)
@@ -1985,7 +1985,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
|> Map.put("blocking_user", user)
|> Map.put("muting_user", user)
|> Map.put("reply_visibility", "self")
- |> Map.put("user", user)
+ |> Map.put("reply_filtering_user", user)
|> ActivityPub.fetch_public_activities()
|> Enum.map(& &1.id)
@@ -2008,6 +2008,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
|> Map.put("blocking_user", user)
|> Map.put("muting_user", user)
|> Map.put("user", user)
+ |> Map.put("reply_filtering_user", user)
activities_ids =
ActivityPub.fetch_activities([user.ap_id | User.following(user)], params)
@@ -2046,6 +2047,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
|> Map.put("muting_user", user)
|> Map.put("user", user)
|> Map.put("reply_visibility", "following")
+ |> Map.put("reply_filtering_user", user)
activities_ids =
ActivityPub.fetch_activities([user.ap_id | User.following(user)], params)
@@ -2084,6 +2086,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
|> Map.put("muting_user", user)
|> Map.put("user", user)
|> Map.put("reply_visibility", "self")
+ |> Map.put("reply_filtering_user", user)
activities_ids =
ActivityPub.fetch_activities([user.ap_id | User.following(user)], params)
@@ -2131,6 +2134,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
|> Map.put("blocking_user", user)
|> Map.put("muting_user", user)
|> Map.put("reply_visibility", "following")
+ |> Map.put("reply_filtering_user", user)
|> Map.put("user", user)
|> ActivityPub.fetch_public_activities()
|> Enum.map(& &1.id)
@@ -2146,6 +2150,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
|> Map.put("blocking_user", user)
|> Map.put("muting_user", user)
|> Map.put("reply_visibility", "self")
+ |> Map.put("reply_filtering_user", user)
|> Map.put("user", user)
|> ActivityPub.fetch_public_activities()
|> Enum.map(& &1.id)
@@ -2176,6 +2181,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
|> Map.put("muting_user", user)
|> Map.put("user", user)
|> Map.put("reply_visibility", "following")
+ |> Map.put("reply_filtering_user", user)
activities_ids =
ActivityPub.fetch_activities([user.ap_id | User.following(user)], params)
@@ -2199,6 +2205,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
|> Map.put("muting_user", user)
|> Map.put("user", user)
|> Map.put("reply_visibility", "self")
+ |> Map.put("reply_filtering_user", user)
activities_ids =
ActivityPub.fetch_activities([user.ap_id | User.following(user)], params)
--
cgit v1.2.3
From b4139cc5472079a34f0256ac9991a0222844d44c Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Fri, 24 Apr 2020 22:25:27 +0300
Subject: [#2409] Made `GET /api/v1/accounts/:id/favourites` auth-optional,
adjusted tests.
---
.../controllers/account_controller_test.exs | 20 +++++++++++++-------
1 file changed, 13 insertions(+), 7 deletions(-)
(limited to 'test')
diff --git a/test/web/pleroma_api/controllers/account_controller_test.exs b/test/web/pleroma_api/controllers/account_controller_test.exs
index ae5334015..6b671a667 100644
--- a/test/web/pleroma_api/controllers/account_controller_test.exs
+++ b/test/web/pleroma_api/controllers/account_controller_test.exs
@@ -151,15 +151,18 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
assert like["id"] == activity.id
end
- test "does not return favorites for specified user_id when user is not logged in", %{
+ test "returns favorites for specified user_id when requester is not logged in", %{
user: user
} do
activity = insert(:note_activity)
CommonAPI.favorite(user, activity.id)
- build_conn()
- |> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
- |> json_response(403)
+ response =
+ build_conn()
+ |> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
+ |> json_response(200)
+
+ assert length(response) == 1
end
test "returns favorited DM only when user is logged in and he is one of recipients", %{
@@ -185,9 +188,12 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
assert length(response) == 1
end
- build_conn()
- |> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
- |> json_response(403)
+ response =
+ build_conn()
+ |> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
+ |> json_response(200)
+
+ assert length(response) == 0
end
test "does not return others' favorited DM when user is not one of recipients", %{
--
cgit v1.2.3
From 3635a9c9c25db16be292c5f56c27ab5d5f5affb5 Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 27 Apr 2020 14:28:08 +0200
Subject: InstanceController: Add extensions to `/api/v1/instance`
---
test/web/mastodon_api/controllers/instance_controller_test.exs | 4 ++++
1 file changed, 4 insertions(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/instance_controller_test.exs b/test/web/mastodon_api/controllers/instance_controller_test.exs
index 2737dcaba..2c7fd9fd0 100644
--- a/test/web/mastodon_api/controllers/instance_controller_test.exs
+++ b/test/web/mastodon_api/controllers/instance_controller_test.exs
@@ -34,6 +34,10 @@ defmodule Pleroma.Web.MastodonAPI.InstanceControllerTest do
"banner_upload_limit" => _
} = result
+ assert result["pleroma"]["metadata"]["features"]
+ assert result["pleroma"]["metadata"]["federation"]
+ assert result["pleroma"]["vapid_public_key"]
+
assert email == from_config_email
end
--
cgit v1.2.3
From 5c7cc109172c84b991fad7eebbdd51e75f0c5382 Mon Sep 17 00:00:00 2001
From: fence
Date: Mon, 27 Apr 2020 18:31:00 +0200
Subject: add tests for deactivated users for mongoose auth
---
test/web/mongooseim/mongoose_im_controller_test.exs | 9 +++++++++
1 file changed, 9 insertions(+)
(limited to 'test')
diff --git a/test/web/mongooseim/mongoose_im_controller_test.exs b/test/web/mongooseim/mongoose_im_controller_test.exs
index 291ae54fc..5987111e5 100644
--- a/test/web/mongooseim/mongoose_im_controller_test.exs
+++ b/test/web/mongooseim/mongoose_im_controller_test.exs
@@ -34,6 +34,7 @@ defmodule Pleroma.Web.MongooseIMController do
test "/check_password", %{conn: conn} do
user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("cool"))
+ _deactivated_user = insert(:user, nickname: "konata", local: false, deactivated: true)
res =
conn
@@ -49,6 +50,14 @@ defmodule Pleroma.Web.MongooseIMController do
assert res == false
+ res =
+ conn
+ |> get(mongoose_im_path(conn, :check_password), user: "konata", pass: "1337")
+ |> json_response(404)
+
+ assert res == false
+
+
res =
conn
|> get(mongoose_im_path(conn, :check_password), user: "nobody", pass: "cool")
--
cgit v1.2.3
From 2efc00b3cf5413ae7f8e8411ee1372343ee2618a Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 27 Apr 2020 20:46:52 +0400
Subject: Use `json_response_and_validate_schema/2` in tests to validate
OpenAPI schema
---
test/support/conn_case.ex | 21 +-
.../account_controller/update_credentials_test.exs | 60 +--
.../controllers/account_controller_test.exs | 569 ++++++++++-----------
3 files changed, 304 insertions(+), 346 deletions(-)
(limited to 'test')
diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex
index 8099461cc..fa30a0c41 100644
--- a/test/support/conn_case.ex
+++ b/test/support/conn_case.ex
@@ -56,7 +56,14 @@ defmodule Pleroma.Web.ConnCase do
[conn: conn]
end
- defp json_response_and_validate_schema(conn, status \\ nil) do
+ defp json_response_and_validate_schema(
+ %{
+ private: %{
+ open_api_spex: %{operation_id: op_id, operation_lookup: lookup, spec: spec}
+ }
+ } = conn,
+ status
+ ) do
content_type =
conn
|> Plug.Conn.get_resp_header("content-type")
@@ -64,10 +71,12 @@ defmodule Pleroma.Web.ConnCase do
|> String.split(";")
|> List.first()
- status = status || conn.status
+ status = Plug.Conn.Status.code(status)
- %{private: %{open_api_spex: %{operation_id: op_id, operation_lookup: lookup, spec: spec}}} =
- conn
+ unless lookup[op_id].responses[status] do
+ err = "Response schema not found for #{conn.status} #{conn.method} #{conn.request_path}"
+ flunk(err)
+ end
schema = lookup[op_id].responses[status].content[content_type].schema
json = json_response(conn, status)
@@ -92,6 +101,10 @@ defmodule Pleroma.Web.ConnCase do
end
end
+ defp json_response_and_validate_schema(conn, _status) do
+ flunk("Response schema not found for #{conn.method} #{conn.request_path} #{conn.status}")
+ end
+
defp ensure_federating_or_authenticated(conn, url, user) do
initial_setting = Config.get([:instance, :federating])
on_exit(fn -> Config.put([:instance, :federating], initial_setting) end)
diff --git a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
index a3356c12f..fdb6d4c5d 100644
--- a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
@@ -26,7 +26,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
}
})
- assert user_data = json_response(res_conn, 200)
+ assert user_data = json_response_and_validate_schema(res_conn, 200)
assert user_data["pleroma"]["settings_store"] == %{"pleroma_fe" => %{"theme" => "bla"}}
user = Repo.get(User, user_data["id"])
@@ -42,7 +42,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
}
})
- assert user_data = json_response(res_conn, 200)
+ assert user_data = json_response_and_validate_schema(res_conn, 200)
assert user_data["pleroma"]["settings_store"] ==
%{
@@ -63,7 +63,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
}
})
- assert user_data = json_response(res_conn, 200)
+ assert user_data = json_response_and_validate_schema(res_conn, 200)
assert user_data["pleroma"]["settings_store"] ==
%{
@@ -80,7 +80,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
"note" => "I drink #cofe with @#{user2.nickname}\n\nsuya.."
})
- assert user_data = json_response(conn, 200)
+ assert user_data = json_response_and_validate_schema(conn, 200)
assert user_data["note"] ==
~s(I drink #cofe with %{"pleroma" => %{"discoverable" => true}}} =
conn
|> patch("/api/v1/accounts/update_credentials", %{discoverable: "true"})
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert %{"source" => %{"pleroma" => %{"discoverable" => false}}} =
conn
|> patch("/api/v1/accounts/update_credentials", %{discoverable: "false"})
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
end
test "updates the user's hide_followers_count and hide_follows_count", %{conn: conn} do
@@ -138,7 +138,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
hide_follows_count: "true"
})
- assert user_data = json_response(conn, 200)
+ assert user_data = json_response_and_validate_schema(conn, 200)
assert user_data["pleroma"]["hide_followers_count"] == true
assert user_data["pleroma"]["hide_follows_count"] == true
end
@@ -147,7 +147,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
response =
conn
|> patch("/api/v1/accounts/update_credentials", %{skip_thread_containment: "true"})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert response["pleroma"]["skip_thread_containment"] == true
assert refresh_record(user).skip_thread_containment
@@ -156,28 +156,28 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
test "updates the user's hide_follows status", %{conn: conn} do
conn = patch(conn, "/api/v1/accounts/update_credentials", %{hide_follows: "true"})
- assert user_data = json_response(conn, 200)
+ assert user_data = json_response_and_validate_schema(conn, 200)
assert user_data["pleroma"]["hide_follows"] == true
end
test "updates the user's hide_favorites status", %{conn: conn} do
conn = patch(conn, "/api/v1/accounts/update_credentials", %{hide_favorites: "true"})
- assert user_data = json_response(conn, 200)
+ assert user_data = json_response_and_validate_schema(conn, 200)
assert user_data["pleroma"]["hide_favorites"] == true
end
test "updates the user's show_role status", %{conn: conn} do
conn = patch(conn, "/api/v1/accounts/update_credentials", %{show_role: "false"})
- assert user_data = json_response(conn, 200)
+ assert user_data = json_response_and_validate_schema(conn, 200)
assert user_data["source"]["pleroma"]["show_role"] == false
end
test "updates the user's no_rich_text status", %{conn: conn} do
conn = patch(conn, "/api/v1/accounts/update_credentials", %{no_rich_text: "true"})
- assert user_data = json_response(conn, 200)
+ assert user_data = json_response_and_validate_schema(conn, 200)
assert user_data["source"]["pleroma"]["no_rich_text"] == true
end
@@ -185,7 +185,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
conn =
patch(conn, "/api/v1/accounts/update_credentials", %{"display_name" => "markorepairs"})
- assert user_data = json_response(conn, 200)
+ assert user_data = json_response_and_validate_schema(conn, 200)
assert user_data["display_name"] == "markorepairs"
end
@@ -198,7 +198,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
conn = patch(conn, "/api/v1/accounts/update_credentials", %{"avatar" => new_avatar})
- assert user_response = json_response(conn, 200)
+ assert user_response = json_response_and_validate_schema(conn, 200)
assert user_response["avatar"] != User.avatar_url(user)
end
@@ -211,7 +211,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
conn = patch(conn, "/api/v1/accounts/update_credentials", %{"header" => new_header})
- assert user_response = json_response(conn, 200)
+ assert user_response = json_response_and_validate_schema(conn, 200)
assert user_response["header"] != User.banner_url(user)
end
@@ -227,7 +227,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
"pleroma_background_image" => new_header
})
- assert user_response = json_response(conn, 200)
+ assert user_response = json_response_and_validate_schema(conn, 200)
assert user_response["pleroma"]["background_image"]
end
@@ -244,9 +244,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
if token == token1 do
assert %{"error" => "Insufficient permissions: write:accounts."} ==
- json_response(conn, 403)
+ json_response_and_validate_schema(conn, 403)
else
- assert json_response(conn, 200)
+ assert json_response_and_validate_schema(conn, 200)
end
end
end
@@ -261,11 +261,11 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
"display_name" => name
})
- assert json_response(ret_conn, 200)
+ assert json_response_and_validate_schema(ret_conn, 200)
conn = get(conn, "/api/v1/accounts/#{user.id}")
- assert user_data = json_response(conn, 200)
+ assert user_data = json_response_and_validate_schema(conn, 200)
assert user_data["note"] == note
assert user_data["display_name"] == name
@@ -281,7 +281,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
account_data =
conn
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert account_data["fields"] == [
%{"name" => "foo", "value" => "bar"},
@@ -314,7 +314,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
conn
|> put_req_header("content-type", "application/x-www-form-urlencoded")
|> patch("/api/v1/accounts/update_credentials", fields)
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert account["fields"] == [
%{"name" => "foo", "value" => "bar"},
@@ -339,7 +339,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
account =
conn
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert account["fields"] == [
%{"name" => "foo", "value" => ""}
@@ -358,14 +358,14 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
assert %{"error" => "Invalid request"} ==
conn
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
- |> json_response(403)
+ |> json_response_and_validate_schema(403)
fields = [%{"name" => long_name, "value" => "bar"}]
assert %{"error" => "Invalid request"} ==
conn
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
- |> json_response(403)
+ |> json_response_and_validate_schema(403)
Pleroma.Config.put([:instance, :max_account_fields], 1)
@@ -377,7 +377,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
assert %{"error" => "Invalid request"} ==
conn
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
- |> json_response(403)
+ |> json_response_and_validate_schema(403)
end
end
end
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index d885b5e08..ba70ba66c 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -10,54 +10,46 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.InternalFetchActor
- alias Pleroma.Web.ApiSpec
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.OAuth.Token
- import OpenApiSpex.TestAssertions
import Pleroma.Factory
describe "account fetching" do
setup do: clear_config([:instance, :limit_to_local_content])
test "works by id" do
- user = insert(:user)
+ %User{id: user_id} = insert(:user)
- conn =
- build_conn()
- |> get("/api/v1/accounts/#{user.id}")
-
- assert %{"id" => id} = json_response(conn, 200)
- assert id == to_string(user.id)
+ assert %{"id" => ^user_id} =
+ build_conn()
+ |> get("/api/v1/accounts/#{user_id}")
+ |> json_response_and_validate_schema(200)
- conn =
- build_conn()
- |> get("/api/v1/accounts/-1")
-
- assert %{"error" => "Can't find user"} = json_response(conn, 404)
+ assert %{"error" => "Can't find user"} =
+ build_conn()
+ |> get("/api/v1/accounts/-1")
+ |> json_response_and_validate_schema(404)
end
test "works by nickname" do
user = insert(:user)
- conn =
- build_conn()
- |> get("/api/v1/accounts/#{user.nickname}")
-
- assert %{"id" => id} = json_response(conn, 200)
- assert id == user.id
+ assert %{"id" => user_id} =
+ build_conn()
+ |> get("/api/v1/accounts/#{user.nickname}")
+ |> json_response_and_validate_schema(200)
end
test "works by nickname for remote users" do
Config.put([:instance, :limit_to_local_content], false)
- user = insert(:user, nickname: "user@example.com", local: false)
- conn =
- build_conn()
- |> get("/api/v1/accounts/#{user.nickname}")
+ user = insert(:user, nickname: "user@example.com", local: false)
- assert %{"id" => id} = json_response(conn, 200)
- assert id == user.id
+ assert %{"id" => user_id} =
+ build_conn()
+ |> get("/api/v1/accounts/#{user.nickname}")
+ |> json_response_and_validate_schema(200)
end
test "respects limit_to_local_content == :all for remote user nicknames" do
@@ -65,11 +57,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
user = insert(:user, nickname: "user@example.com", local: false)
- conn =
- build_conn()
- |> get("/api/v1/accounts/#{user.nickname}")
-
- assert json_response(conn, 404)
+ assert build_conn()
+ |> get("/api/v1/accounts/#{user.nickname}")
+ |> json_response_and_validate_schema(404)
end
test "respects limit_to_local_content == :unauthenticated for remote user nicknames" do
@@ -82,7 +72,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
build_conn()
|> get("/api/v1/accounts/#{user.nickname}")
- assert json_response(conn, 404)
+ assert json_response_and_validate_schema(conn, 404)
conn =
build_conn()
@@ -90,7 +80,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> assign(:token, insert(:oauth_token, user: reading_user, scopes: ["read:accounts"]))
|> get("/api/v1/accounts/#{user.nickname}")
- assert %{"id" => id} = json_response(conn, 200)
+ assert %{"id" => id} = json_response_and_validate_schema(conn, 200)
assert id == user.id
end
@@ -101,21 +91,21 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
user_one = insert(:user, %{id: 1212})
user_two = insert(:user, %{nickname: "#{user_one.id}garbage"})
- resp_one =
+ acc_one =
conn
|> get("/api/v1/accounts/#{user_one.id}")
+ |> json_response_and_validate_schema(:ok)
- resp_two =
+ acc_two =
conn
|> get("/api/v1/accounts/#{user_two.nickname}")
+ |> json_response_and_validate_schema(:ok)
- resp_three =
+ acc_three =
conn
|> get("/api/v1/accounts/#{user_two.id}")
+ |> json_response_and_validate_schema(:ok)
- acc_one = json_response(resp_one, 200)
- acc_two = json_response(resp_two, 200)
- acc_three = json_response(resp_three, 200)
refute acc_one == acc_two
assert acc_two == acc_three
end
@@ -123,23 +113,19 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "returns 404 when user is invisible", %{conn: conn} do
user = insert(:user, %{invisible: true})
- resp =
- conn
- |> get("/api/v1/accounts/#{user.nickname}")
- |> json_response(404)
-
- assert %{"error" => "Can't find user"} = resp
+ assert %{"error" => "Can't find user"} =
+ conn
+ |> get("/api/v1/accounts/#{user.nickname}")
+ |> json_response_and_validate_schema(404)
end
test "returns 404 for internal.fetch actor", %{conn: conn} do
%User{nickname: "internal.fetch"} = InternalFetchActor.get_actor()
- resp =
- conn
- |> get("/api/v1/accounts/internal.fetch")
- |> json_response(404)
-
- assert %{"error" => "Can't find user"} = resp
+ assert %{"error" => "Can't find user"} =
+ conn
+ |> get("/api/v1/accounts/internal.fetch")
+ |> json_response_and_validate_schema(404)
end
end
@@ -157,27 +143,25 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
setup do: clear_config([:restrict_unauthenticated, :profiles, :remote], true)
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
- res_conn = get(conn, "/api/v1/accounts/#{local.id}")
-
- assert json_response(res_conn, :not_found) == %{
- "error" => "Can't find user"
- }
-
- res_conn = get(conn, "/api/v1/accounts/#{remote.id}")
+ assert %{"error" => "Can't find user"} ==
+ conn
+ |> get("/api/v1/accounts/#{local.id}")
+ |> json_response_and_validate_schema(:not_found)
- assert json_response(res_conn, :not_found) == %{
- "error" => "Can't find user"
- }
+ assert %{"error" => "Can't find user"} ==
+ conn
+ |> get("/api/v1/accounts/#{remote.id}")
+ |> json_response_and_validate_schema(:not_found)
end
test "if user is authenticated", %{local: local, remote: remote} do
%{conn: conn} = oauth_access(["read"])
res_conn = get(conn, "/api/v1/accounts/#{local.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
res_conn = get(conn, "/api/v1/accounts/#{remote.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
end
end
@@ -189,22 +173,22 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
res_conn = get(conn, "/api/v1/accounts/#{local.id}")
- assert json_response(res_conn, :not_found) == %{
+ assert json_response_and_validate_schema(res_conn, :not_found) == %{
"error" => "Can't find user"
}
res_conn = get(conn, "/api/v1/accounts/#{remote.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
end
test "if user is authenticated", %{local: local, remote: remote} do
%{conn: conn} = oauth_access(["read"])
res_conn = get(conn, "/api/v1/accounts/#{local.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
res_conn = get(conn, "/api/v1/accounts/#{remote.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
end
end
@@ -215,11 +199,11 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
res_conn = get(conn, "/api/v1/accounts/#{local.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
res_conn = get(conn, "/api/v1/accounts/#{remote.id}")
- assert json_response(res_conn, :not_found) == %{
+ assert json_response_and_validate_schema(res_conn, :not_found) == %{
"error" => "Can't find user"
}
end
@@ -228,10 +212,10 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
%{conn: conn} = oauth_access(["read"])
res_conn = get(conn, "/api/v1/accounts/#{local.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
res_conn = get(conn, "/api/v1/accounts/#{remote.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
end
end
@@ -247,28 +231,37 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
{:ok, activity} = CommonAPI.post(user_two, %{"status" => "User one sux0rz"})
{:ok, repeat, _} = CommonAPI.repeat(activity.id, user_three)
- assert resp = get(conn, "/api/v1/accounts/#{user_two.id}/statuses") |> json_response(200)
+ assert resp =
+ conn
+ |> get("/api/v1/accounts/#{user_two.id}/statuses")
+ |> json_response_and_validate_schema(200)
+
assert [%{"id" => id}] = resp
- assert_schema(resp, "StatusesResponse", ApiSpec.spec())
assert id == activity.id
# Even a blocked user will deliver the full user timeline, there would be
# no point in looking at a blocked users timeline otherwise
- assert resp = get(conn, "/api/v1/accounts/#{user_two.id}/statuses") |> json_response(200)
+ assert resp =
+ conn
+ |> get("/api/v1/accounts/#{user_two.id}/statuses")
+ |> json_response_and_validate_schema(200)
+
assert [%{"id" => id}] = resp
assert id == activity.id
- assert_schema(resp, "StatusesResponse", ApiSpec.spec())
# Third user's timeline includes the repeat when viewed by unauthenticated user
- resp = get(build_conn(), "/api/v1/accounts/#{user_three.id}/statuses") |> json_response(200)
+ resp =
+ build_conn()
+ |> get("/api/v1/accounts/#{user_three.id}/statuses")
+ |> json_response_and_validate_schema(200)
+
assert [%{"id" => id}] = resp
assert id == repeat.id
- assert_schema(resp, "StatusesResponse", ApiSpec.spec())
# When viewing a third user's timeline, the blocked users' statuses will NOT be shown
resp = get(conn, "/api/v1/accounts/#{user_three.id}/statuses")
- assert [] = json_response(resp, 200)
+ assert [] == json_response_and_validate_schema(resp, 200)
end
test "gets users statuses", %{conn: conn} do
@@ -289,34 +282,36 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
{:ok, private_activity} =
CommonAPI.post(user_one, %{"status" => "private", "visibility" => "private"})
- resp = get(conn, "/api/v1/accounts/#{user_one.id}/statuses") |> json_response(200)
+ # TODO!!!
+ resp =
+ conn
+ |> get("/api/v1/accounts/#{user_one.id}/statuses")
+ |> json_response_and_validate_schema(200)
+
assert [%{"id" => id}] = resp
assert id == to_string(activity.id)
- assert_schema(resp, "StatusesResponse", ApiSpec.spec())
resp =
conn
|> assign(:user, user_two)
|> assign(:token, insert(:oauth_token, user: user_two, scopes: ["read:statuses"]))
|> get("/api/v1/accounts/#{user_one.id}/statuses")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert [%{"id" => id_one}, %{"id" => id_two}] = resp
assert id_one == to_string(direct_activity.id)
assert id_two == to_string(activity.id)
- assert_schema(resp, "StatusesResponse", ApiSpec.spec())
resp =
conn
|> assign(:user, user_three)
|> assign(:token, insert(:oauth_token, user: user_three, scopes: ["read:statuses"]))
|> get("/api/v1/accounts/#{user_one.id}/statuses")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert [%{"id" => id_one}, %{"id" => id_two}] = resp
assert id_one == to_string(private_activity.id)
assert id_two == to_string(activity.id)
- assert_schema(resp, "StatusesResponse", ApiSpec.spec())
end
test "unimplemented pinned statuses feature", %{conn: conn} do
@@ -325,7 +320,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?pinned=true")
- assert json_response(conn, 200) == []
+ assert json_response_and_validate_schema(conn, 200) == []
end
test "gets an users media", %{conn: conn} do
@@ -340,61 +335,48 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
{:ok, %{id: media_id}} = ActivityPub.upload(file, actor: user.ap_id)
- {:ok, image_post} = CommonAPI.post(user, %{"status" => "cofe", "media_ids" => [media_id]})
+ {:ok, %{id: image_post_id}} =
+ CommonAPI.post(user, %{"status" => "cofe", "media_ids" => [media_id]})
conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?only_media=true")
- assert [%{"id" => id}] = json_response(conn, 200)
- assert id == to_string(image_post.id)
- assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert [%{"id" => ^image_post_id}] = json_response_and_validate_schema(conn, 200)
conn = get(build_conn(), "/api/v1/accounts/#{user.id}/statuses?only_media=1")
- assert [%{"id" => id}] = json_response(conn, 200)
- assert id == to_string(image_post.id)
- assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert [%{"id" => ^image_post_id}] = json_response_and_validate_schema(conn, 200)
end
test "gets a user's statuses without reblogs", %{user: user, conn: conn} do
- {:ok, post} = CommonAPI.post(user, %{"status" => "HI!!!"})
- {:ok, _, _} = CommonAPI.repeat(post.id, user)
+ {:ok, %{id: post_id}} = CommonAPI.post(user, %{"status" => "HI!!!"})
+ {:ok, _, _} = CommonAPI.repeat(post_id, user)
conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?exclude_reblogs=true")
-
- assert [%{"id" => id}] = json_response(conn, 200)
- assert id == to_string(post.id)
- assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert [%{"id" => ^post_id}] = json_response_and_validate_schema(conn, 200)
conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?exclude_reblogs=1")
-
- assert [%{"id" => id}] = json_response(conn, 200)
- assert id == to_string(post.id)
- assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert [%{"id" => ^post_id}] = json_response_and_validate_schema(conn, 200)
end
test "filters user's statuses by a hashtag", %{user: user, conn: conn} do
- {:ok, post} = CommonAPI.post(user, %{"status" => "#hashtag"})
+ {:ok, %{id: post_id}} = CommonAPI.post(user, %{"status" => "#hashtag"})
{:ok, _post} = CommonAPI.post(user, %{"status" => "hashtag"})
conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?tagged=hashtag")
-
- assert [%{"id" => id}] = json_response(conn, 200)
- assert id == to_string(post.id)
- assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert [%{"id" => ^post_id}] = json_response_and_validate_schema(conn, 200)
end
test "the user views their own timelines and excludes direct messages", %{
user: user,
conn: conn
} do
- {:ok, public_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "public"})
+ {:ok, %{id: public_activity_id}} =
+ CommonAPI.post(user, %{"status" => ".", "visibility" => "public"})
+
{:ok, _direct_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?exclude_visibilities[]=direct")
-
- assert [%{"id" => id}] = json_response(conn, 200)
- assert id == to_string(public_activity.id)
- assert_schema(json_response(conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert [%{"id" => ^public_activity_id}] = json_response_and_validate_schema(conn, 200)
end
end
@@ -414,29 +396,25 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
setup do: clear_config([:restrict_unauthenticated, :profiles, :remote], true)
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
- res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses")
-
- assert json_response(res_conn, :not_found) == %{
- "error" => "Can't find user"
- }
-
- res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses")
+ assert %{"error" => "Can't find user"} ==
+ conn
+ |> get("/api/v1/accounts/#{local.id}/statuses")
+ |> json_response_and_validate_schema(:not_found)
- assert json_response(res_conn, :not_found) == %{
- "error" => "Can't find user"
- }
+ assert %{"error" => "Can't find user"} ==
+ conn
+ |> get("/api/v1/accounts/#{remote.id}/statuses")
+ |> json_response_and_validate_schema(:not_found)
end
test "if user is authenticated", %{local: local, remote: remote} do
%{conn: conn} = oauth_access(["read"])
res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses")
- assert length(json_response(res_conn, 200)) == 1
- assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses")
- assert length(json_response(res_conn, 200)) == 1
- assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
end
end
@@ -447,27 +425,23 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
setup do: clear_config([:restrict_unauthenticated, :profiles, :local], true)
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
- res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses")
-
- assert json_response(res_conn, :not_found) == %{
- "error" => "Can't find user"
- }
+ assert %{"error" => "Can't find user"} ==
+ conn
+ |> get("/api/v1/accounts/#{local.id}/statuses")
+ |> json_response_and_validate_schema(:not_found)
res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses")
- assert length(json_response(res_conn, 200)) == 1
- assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
end
test "if user is authenticated", %{local: local, remote: remote} do
%{conn: conn} = oauth_access(["read"])
res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses")
- assert length(json_response(res_conn, 200)) == 1
- assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses")
- assert length(json_response(res_conn, 200)) == 1
- assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
end
end
@@ -479,26 +453,22 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses")
- assert length(json_response(res_conn, 200)) == 1
- assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
- res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses")
-
- assert json_response(res_conn, :not_found) == %{
- "error" => "Can't find user"
- }
+ assert %{"error" => "Can't find user"} ==
+ conn
+ |> get("/api/v1/accounts/#{remote.id}/statuses")
+ |> json_response_and_validate_schema(:not_found)
end
test "if user is authenticated", %{local: local, remote: remote} do
%{conn: conn} = oauth_access(["read"])
res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses")
- assert length(json_response(res_conn, 200)) == 1
- assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses")
- assert length(json_response(res_conn, 200)) == 1
- assert_schema(json_response(res_conn, 200), "StatusesResponse", ApiSpec.spec())
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
end
end
@@ -507,13 +477,11 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "getting followers", %{user: user, conn: conn} do
other_user = insert(:user)
- {:ok, user} = User.follow(user, other_user)
+ {:ok, %{id: user_id}} = User.follow(user, other_user)
conn = get(conn, "/api/v1/accounts/#{other_user.id}/followers")
- assert [%{"id" => id}] = json_response(conn, 200)
- assert id == to_string(user.id)
- assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
+ assert [%{"id" => ^user_id}] = json_response_and_validate_schema(conn, 200)
end
test "getting followers, hide_followers", %{user: user, conn: conn} do
@@ -522,7 +490,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
conn = get(conn, "/api/v1/accounts/#{other_user.id}/followers")
- assert [] == json_response(conn, 200)
+ assert [] == json_response_and_validate_schema(conn, 200)
end
test "getting followers, hide_followers, same user requesting" do
@@ -536,40 +504,31 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"]))
|> get("/api/v1/accounts/#{other_user.id}/followers")
- refute [] == json_response(conn, 200)
- assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
+ refute [] == json_response_and_validate_schema(conn, 200)
end
test "getting followers, pagination", %{user: user, conn: conn} do
- follower1 = insert(:user)
- follower2 = insert(:user)
- follower3 = insert(:user)
- {:ok, _} = User.follow(follower1, user)
- {:ok, _} = User.follow(follower2, user)
- {:ok, _} = User.follow(follower3, user)
-
- res_conn = get(conn, "/api/v1/accounts/#{user.id}/followers?since_id=#{follower1.id}")
+ {:ok, %User{id: follower1_id}} = :user |> insert() |> User.follow(user)
+ {:ok, %User{id: follower2_id}} = :user |> insert() |> User.follow(user)
+ {:ok, %User{id: follower3_id}} = :user |> insert() |> User.follow(user)
- assert [%{"id" => id3}, %{"id" => id2}] = json_response(res_conn, 200)
- assert id3 == follower3.id
- assert id2 == follower2.id
- assert_schema(json_response(res_conn, 200), "AccountsResponse", ApiSpec.spec())
-
- res_conn = get(conn, "/api/v1/accounts/#{user.id}/followers?max_id=#{follower3.id}")
+ assert [%{"id" => ^follower3_id}, %{"id" => ^follower2_id}] =
+ conn
+ |> get("/api/v1/accounts/#{user.id}/followers?since_id=#{follower1_id}")
+ |> json_response_and_validate_schema(200)
- assert [%{"id" => id2}, %{"id" => id1}] = json_response(res_conn, 200)
- assert id2 == follower2.id
- assert id1 == follower1.id
+ assert [%{"id" => ^follower2_id}, %{"id" => ^follower1_id}] =
+ conn
+ |> get("/api/v1/accounts/#{user.id}/followers?max_id=#{follower3_id}")
+ |> json_response_and_validate_schema(200)
- res_conn = get(conn, "/api/v1/accounts/#{user.id}/followers?limit=1&max_id=#{follower3.id}")
+ res_conn = get(conn, "/api/v1/accounts/#{user.id}/followers?limit=1&max_id=#{follower3_id}")
- assert [%{"id" => id2}] = json_response(res_conn, 200)
- assert id2 == follower2.id
+ assert [%{"id" => ^follower2_id}] = json_response_and_validate_schema(res_conn, 200)
assert [link_header] = get_resp_header(res_conn, "link")
- assert link_header =~ ~r/min_id=#{follower2.id}/
- assert link_header =~ ~r/max_id=#{follower2.id}/
- assert_schema(json_response(res_conn, 200), "AccountsResponse", ApiSpec.spec())
+ assert link_header =~ ~r/min_id=#{follower2_id}/
+ assert link_header =~ ~r/max_id=#{follower2_id}/
end
end
@@ -582,9 +541,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
conn = get(conn, "/api/v1/accounts/#{user.id}/following")
- assert [%{"id" => id}] = json_response(conn, 200)
+ assert [%{"id" => id}] = json_response_and_validate_schema(conn, 200)
assert id == to_string(other_user.id)
- assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
end
test "getting following, hide_follows, other user requesting" do
@@ -598,8 +556,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"]))
|> get("/api/v1/accounts/#{user.id}/following")
- assert [] == json_response(conn, 200)
- assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
+ assert [] == json_response_and_validate_schema(conn, 200)
end
test "getting following, hide_follows, same user requesting" do
@@ -613,7 +570,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> assign(:token, insert(:oauth_token, user: user, scopes: ["read:accounts"]))
|> get("/api/v1/accounts/#{user.id}/following")
- refute [] == json_response(conn, 200)
+ refute [] == json_response_and_validate_schema(conn, 200)
end
test "getting following, pagination", %{user: user, conn: conn} do
@@ -626,28 +583,25 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
res_conn = get(conn, "/api/v1/accounts/#{user.id}/following?since_id=#{following1.id}")
- assert [%{"id" => id3}, %{"id" => id2}] = json_response(res_conn, 200)
+ assert [%{"id" => id3}, %{"id" => id2}] = json_response_and_validate_schema(res_conn, 200)
assert id3 == following3.id
assert id2 == following2.id
- assert_schema(json_response(res_conn, 200), "AccountsResponse", ApiSpec.spec())
res_conn = get(conn, "/api/v1/accounts/#{user.id}/following?max_id=#{following3.id}")
- assert [%{"id" => id2}, %{"id" => id1}] = json_response(res_conn, 200)
+ assert [%{"id" => id2}, %{"id" => id1}] = json_response_and_validate_schema(res_conn, 200)
assert id2 == following2.id
assert id1 == following1.id
- assert_schema(json_response(res_conn, 200), "AccountsResponse", ApiSpec.spec())
res_conn =
get(conn, "/api/v1/accounts/#{user.id}/following?limit=1&max_id=#{following3.id}")
- assert [%{"id" => id2}] = json_response(res_conn, 200)
+ assert [%{"id" => id2}] = json_response_and_validate_schema(res_conn, 200)
assert id2 == following2.id
assert [link_header] = get_resp_header(res_conn, "link")
assert link_header =~ ~r/min_id=#{following2.id}/
assert link_header =~ ~r/max_id=#{following2.id}/
- assert_schema(json_response(res_conn, 200), "AccountsResponse", ApiSpec.spec())
end
end
@@ -655,40 +609,37 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
setup do: oauth_access(["follow"])
test "following / unfollowing a user", %{conn: conn} do
- other_user = insert(:user)
-
- ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/follow")
-
- assert %{"id" => _id, "following" => true} = json_response(ret_conn, 200)
- assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
+ %{id: other_user_id, nickname: other_user_nickname} = insert(:user)
- ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/unfollow")
-
- assert %{"id" => _id, "following" => false} = json_response(ret_conn, 200)
- assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
+ assert %{"id" => _id, "following" => true} =
+ conn
+ |> post("/api/v1/accounts/#{other_user_id}/follow")
+ |> json_response_and_validate_schema(200)
- conn =
- conn
- |> put_req_header("content-type", "application/json")
- |> post("/api/v1/follows", %{"uri" => other_user.nickname})
+ assert %{"id" => _id, "following" => false} =
+ conn
+ |> post("/api/v1/accounts/#{other_user_id}/unfollow")
+ |> json_response_and_validate_schema(200)
- assert %{"id" => id} = json_response(conn, 200)
- assert id == to_string(other_user.id)
- assert_schema(json_response(conn, 200), "Account", ApiSpec.spec())
+ assert %{"id" => ^other_user_id} =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/follows", %{"uri" => other_user_nickname})
+ |> json_response_and_validate_schema(200)
end
test "cancelling follow request", %{conn: conn} do
%{id: other_user_id} = insert(:user, %{locked: true})
- resp = conn |> post("/api/v1/accounts/#{other_user_id}/follow") |> json_response(:ok)
-
- assert %{"id" => ^other_user_id, "following" => false, "requested" => true} = resp
- assert_schema(resp, "AccountRelationship", ApiSpec.spec())
-
- resp = conn |> post("/api/v1/accounts/#{other_user_id}/unfollow") |> json_response(:ok)
+ assert %{"id" => ^other_user_id, "following" => false, "requested" => true} =
+ conn
+ |> post("/api/v1/accounts/#{other_user_id}/follow")
+ |> json_response_and_validate_schema(:ok)
- assert %{"id" => ^other_user_id, "following" => false, "requested" => false} = resp
- assert_schema(resp, "AccountRelationship", ApiSpec.spec())
+ assert %{"id" => ^other_user_id, "following" => false, "requested" => false} =
+ conn
+ |> post("/api/v1/accounts/#{other_user_id}/unfollow")
+ |> json_response_and_validate_schema(:ok)
end
test "following without reblogs" do
@@ -698,50 +649,53 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
ret_conn = post(conn, "/api/v1/accounts/#{followed.id}/follow?reblogs=false")
- assert %{"showing_reblogs" => false} = json_response(ret_conn, 200)
- assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
+ assert %{"showing_reblogs" => false} = json_response_and_validate_schema(ret_conn, 200)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "hey"})
- {:ok, reblog, _} = CommonAPI.repeat(activity.id, followed)
-
- ret_conn = get(conn, "/api/v1/timelines/home")
+ {:ok, %{id: reblog_id}, _} = CommonAPI.repeat(activity.id, followed)
- assert [] == json_response(ret_conn, 200)
-
- ret_conn = post(conn, "/api/v1/accounts/#{followed.id}/follow?reblogs=true")
-
- assert %{"showing_reblogs" => true} = json_response(ret_conn, 200)
- assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
+ assert [] ==
+ conn
+ |> get("/api/v1/timelines/home")
+ |> json_response(200)
- conn = get(conn, "/api/v1/timelines/home")
+ assert %{"showing_reblogs" => true} =
+ conn
+ |> post("/api/v1/accounts/#{followed.id}/follow?reblogs=true")
+ |> json_response_and_validate_schema(200)
- expected_activity_id = reblog.id
- assert [%{"id" => ^expected_activity_id}] = json_response(conn, 200)
+ assert [%{"id" => ^reblog_id}] =
+ conn
+ |> get("/api/v1/timelines/home")
+ |> json_response(200)
end
test "following / unfollowing errors", %{user: user, conn: conn} do
# self follow
conn_res = post(conn, "/api/v1/accounts/#{user.id}/follow")
- assert %{"error" => "Can not follow yourself"} = json_response(conn_res, 400)
+
+ assert %{"error" => "Can not follow yourself"} =
+ json_response_and_validate_schema(conn_res, 400)
# self unfollow
user = User.get_cached_by_id(user.id)
conn_res = post(conn, "/api/v1/accounts/#{user.id}/unfollow")
- assert %{"error" => "Can not unfollow yourself"} = json_response(conn_res, 400)
+
+ assert %{"error" => "Can not unfollow yourself"} =
+ json_response_and_validate_schema(conn_res, 400)
# self follow via uri
user = User.get_cached_by_id(user.id)
- conn_res =
- conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/v1/follows", %{"uri" => user.nickname})
-
- assert %{"error" => "Can not follow yourself"} = json_response(conn_res, 400)
+ assert %{"error" => "Can not follow yourself"} =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/v1/follows", %{"uri" => user.nickname})
+ |> json_response_and_validate_schema(400)
# follow non existing user
conn_res = post(conn, "/api/v1/accounts/doesntexist/follow")
- assert %{"error" => "Record not found"} = json_response(conn_res, 404)
+ assert %{"error" => "Record not found"} = json_response_and_validate_schema(conn_res, 404)
# follow non existing user via uri
conn_res =
@@ -749,11 +703,11 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> put_req_header("content-type", "multipart/form-data")
|> post("/api/v1/follows", %{"uri" => "doesntexist"})
- assert %{"error" => "Record not found"} = json_response(conn_res, 404)
+ assert %{"error" => "Record not found"} = json_response_and_validate_schema(conn_res, 404)
# unfollow non existing user
conn_res = post(conn, "/api/v1/accounts/doesntexist/unfollow")
- assert %{"error" => "Record not found"} = json_response(conn_res, 404)
+ assert %{"error" => "Record not found"} = json_response_and_validate_schema(conn_res, 404)
end
end
@@ -763,21 +717,16 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "with notifications", %{conn: conn} do
other_user = insert(:user)
- ret_conn =
- conn
- |> put_req_header("content-type", "application/json")
- |> post("/api/v1/accounts/#{other_user.id}/mute")
-
- response = json_response(ret_conn, 200)
-
- assert %{"id" => _id, "muting" => true, "muting_notifications" => true} = response
- assert_schema(response, "AccountRelationship", ApiSpec.spec())
+ assert %{"id" => _id, "muting" => true, "muting_notifications" => true} =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/accounts/#{other_user.id}/mute")
+ |> json_response_and_validate_schema(200)
conn = post(conn, "/api/v1/accounts/#{other_user.id}/unmute")
- response = json_response(conn, 200)
- assert %{"id" => _id, "muting" => false, "muting_notifications" => false} = response
- assert_schema(response, "AccountRelationship", ApiSpec.spec())
+ assert %{"id" => _id, "muting" => false, "muting_notifications" => false} =
+ json_response_and_validate_schema(conn, 200)
end
test "without notifications", %{conn: conn} do
@@ -788,16 +737,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> put_req_header("content-type", "multipart/form-data")
|> post("/api/v1/accounts/#{other_user.id}/mute", %{"notifications" => "false"})
- response = json_response(ret_conn, 200)
-
- assert %{"id" => _id, "muting" => true, "muting_notifications" => false} = response
- assert_schema(response, "AccountRelationship", ApiSpec.spec())
+ assert %{"id" => _id, "muting" => true, "muting_notifications" => false} =
+ json_response_and_validate_schema(ret_conn, 200)
conn = post(conn, "/api/v1/accounts/#{other_user.id}/unmute")
- response = json_response(conn, 200)
- assert %{"id" => _id, "muting" => false, "muting_notifications" => false} = response
- assert_schema(response, "AccountRelationship", ApiSpec.spec())
+ assert %{"id" => _id, "muting" => false, "muting_notifications" => false} =
+ json_response_and_validate_schema(conn, 200)
end
end
@@ -810,17 +756,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
[conn: conn, user: user, activity: activity]
end
- test "returns pinned statuses", %{conn: conn, user: user, activity: activity} do
- {:ok, _} = CommonAPI.pin(activity.id, user)
+ test "returns pinned statuses", %{conn: conn, user: user, activity: %{id: activity_id}} do
+ {:ok, _} = CommonAPI.pin(activity_id, user)
- result =
- conn
- |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true")
- |> json_response(200)
-
- id_str = to_string(activity.id)
-
- assert [%{"id" => ^id_str, "pinned" => true}] = result
+ assert [%{"id" => ^activity_id, "pinned" => true}] =
+ conn
+ |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true")
+ |> json_response_and_validate_schema(200)
end
end
@@ -830,13 +772,11 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/block")
- assert %{"id" => _id, "blocking" => true} = json_response(ret_conn, 200)
- assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
+ assert %{"id" => _id, "blocking" => true} = json_response_and_validate_schema(ret_conn, 200)
conn = post(conn, "/api/v1/accounts/#{other_user.id}/unblock")
- assert %{"id" => _id, "blocking" => false} = json_response(conn, 200)
- assert_schema(json_response(ret_conn, 200), "AccountRelationship", ApiSpec.spec())
+ assert %{"id" => _id, "blocking" => false} = json_response_and_validate_schema(conn, 200)
end
describe "create account by app" do
@@ -863,15 +803,15 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
scopes: "read, write, follow"
})
- %{
- "client_id" => client_id,
- "client_secret" => client_secret,
- "id" => _,
- "name" => "client_name",
- "redirect_uri" => "urn:ietf:wg:oauth:2.0:oob",
- "vapid_key" => _,
- "website" => nil
- } = json_response(conn, 200)
+ assert %{
+ "client_id" => client_id,
+ "client_secret" => client_secret,
+ "id" => _,
+ "name" => "client_name",
+ "redirect_uri" => "urn:ietf:wg:oauth:2.0:oob",
+ "vapid_key" => _,
+ "website" => nil
+ } = json_response_and_validate_schema(conn, 200)
conn =
post(conn, "/oauth/token", %{
@@ -906,7 +846,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
"created_at" => _created_at,
"scope" => _scope,
"token_type" => "Bearer"
- } = json_response(conn, 200)
+ } = json_response_and_validate_schema(conn, 200)
token_from_db = Repo.get_by(Token, token: token)
assert token_from_db
@@ -926,7 +866,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> put_req_header("content-type", "application/json")
|> post("/api/v1/accounts", valid_params)
- assert json_response(res, 400) == %{"error" => "{\"email\":[\"has already been taken\"]}"}
+ assert json_response_and_validate_schema(res, 400) == %{
+ "error" => "{\"email\":[\"has already been taken\"]}"
+ }
end
test "returns bad_request if missing required params", %{
@@ -941,7 +883,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> put_req_header("content-type", "application/json")
res = post(conn, "/api/v1/accounts", valid_params)
- assert json_response(res, 200)
+ assert json_response_and_validate_schema(res, 200)
[{127, 0, 0, 1}, {127, 0, 0, 2}, {127, 0, 0, 3}, {127, 0, 0, 4}]
|> Stream.zip(Map.delete(valid_params, :email))
@@ -950,7 +892,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
conn
|> Map.put(:remote_ip, ip)
|> post("/api/v1/accounts", Map.delete(valid_params, attr))
- |> json_response(400)
+ |> json_response_and_validate_schema(400)
assert res == %{
"error" => "Missing field: #{attr}.",
@@ -983,14 +925,16 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> Map.put(:remote_ip, {127, 0, 0, 5})
|> post("/api/v1/accounts", Map.delete(valid_params, :email))
- assert json_response(res, 400) == %{"error" => "Missing parameters"}
+ assert json_response_and_validate_schema(res, 400) == %{"error" => "Missing parameters"}
res =
conn
|> Map.put(:remote_ip, {127, 0, 0, 6})
|> post("/api/v1/accounts", Map.put(valid_params, :email, ""))
- assert json_response(res, 400) == %{"error" => "{\"email\":[\"can't be blank\"]}"}
+ assert json_response_and_validate_schema(res, 400) == %{
+ "error" => "{\"email\":[\"can't be blank\"]}"
+ }
end
test "allow registration without an email", %{conn: conn, valid_params: valid_params} do
@@ -1003,7 +947,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> Map.put(:remote_ip, {127, 0, 0, 7})
|> post("/api/v1/accounts", Map.delete(valid_params, :email))
- assert json_response(res, 200)
+ assert json_response_and_validate_schema(res, 200)
end
test "allow registration with an empty email", %{conn: conn, valid_params: valid_params} do
@@ -1016,7 +960,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> Map.put(:remote_ip, {127, 0, 0, 8})
|> post("/api/v1/accounts", Map.put(valid_params, :email, ""))
- assert json_response(res, 200)
+ assert json_response_and_validate_schema(res, 200)
end
test "returns forbidden if token is invalid", %{conn: conn, valid_params: valid_params} do
@@ -1026,7 +970,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> put_req_header("content-type", "multipart/form-data")
|> post("/api/v1/accounts", valid_params)
- assert json_response(res, 403) == %{"error" => "Invalid credentials"}
+ assert json_response_and_validate_schema(res, 403) == %{"error" => "Invalid credentials"}
end
test "registration from trusted app" do
@@ -1056,7 +1000,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
password: "some_password",
confirm: "some_password"
})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert %{
"access_token" => access_token,
@@ -1069,7 +1013,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
build_conn()
|> Plug.Conn.put_req_header("authorization", "Bearer " <> access_token)
|> get("/api/v1/accounts/verify_credentials")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert %{
"acct" => "Lain",
@@ -1125,7 +1069,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
"created_at" => _created_at,
"scope" => _scope,
"token_type" => "Bearer"
- } = json_response(conn, 200)
+ } = json_response_and_validate_schema(conn, 200)
token_from_db = Repo.get_by(Token, token: token)
assert token_from_db
@@ -1143,7 +1087,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
agreement: true
})
- assert json_response(conn, :too_many_requests) == %{"error" => "Throttled"}
+ assert json_response_and_validate_schema(conn, :too_many_requests) == %{
+ "error" => "Throttled"
+ }
end
end
@@ -1151,16 +1097,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "returns lists to which the account belongs" do
%{user: user, conn: conn} = oauth_access(["read:lists"])
other_user = insert(:user)
- assert {:ok, %Pleroma.List{} = list} = Pleroma.List.create("Test List", user)
+ assert {:ok, %Pleroma.List{id: list_id} = list} = Pleroma.List.create("Test List", user)
{:ok, %{following: _following}} = Pleroma.List.follow(list, other_user)
- res =
- conn
- |> get("/api/v1/accounts/#{other_user.id}/lists")
- |> json_response(200)
-
- assert res == [%{"id" => to_string(list.id), "title" => "Test List"}]
- assert_schema(res, "ListsResponse", ApiSpec.spec())
+ assert [%{"id" => list_id, "title" => "Test List"}] =
+ conn
+ |> get("/api/v1/accounts/#{other_user.id}/lists")
+ |> json_response_and_validate_schema(200)
end
end
@@ -1169,7 +1112,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
%{user: user, conn: conn} = oauth_access(["read:accounts"])
conn = get(conn, "/api/v1/accounts/verify_credentials")
- response = json_response(conn, 200)
+ response = json_response_and_validate_schema(conn, 200)
assert %{"id" => id, "source" => %{"privacy" => "public"}} = response
assert response["pleroma"]["chat_token"]
@@ -1182,7 +1125,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
conn = get(conn, "/api/v1/accounts/verify_credentials")
- assert %{"id" => id, "source" => %{"privacy" => "unlisted"}} = json_response(conn, 200)
+ assert %{"id" => id, "source" => %{"privacy" => "unlisted"}} =
+ json_response_and_validate_schema(conn, 200)
+
assert id == to_string(user.id)
end
@@ -1192,7 +1137,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
conn = get(conn, "/api/v1/accounts/verify_credentials")
- assert %{"id" => id, "source" => %{"privacy" => "private"}} = json_response(conn, 200)
+ assert %{"id" => id, "source" => %{"privacy" => "private"}} =
+ json_response_and_validate_schema(conn, 200)
+
assert id == to_string(user.id)
end
end
@@ -1207,18 +1154,18 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert [%{"id" => ^other_user_id}] =
conn
|> get("/api/v1/accounts/relationships?id=#{other_user.id}")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert [%{"id" => ^other_user_id}] =
conn
|> get("/api/v1/accounts/relationships?id[]=#{other_user.id}")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
end
test "returns an empty list on a bad request", %{conn: conn} do
conn = get(conn, "/api/v1/accounts/relationships", %{})
- assert [] = json_response(conn, 200)
+ assert [] = json_response_and_validate_schema(conn, 200)
end
end
@@ -1231,8 +1178,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
conn = get(conn, "/api/v1/mutes")
other_user_id = to_string(other_user.id)
- assert [%{"id" => ^other_user_id}] = json_response(conn, 200)
- assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
+ assert [%{"id" => ^other_user_id}] = json_response_and_validate_schema(conn, 200)
end
test "getting a list of blocks" do
@@ -1247,7 +1193,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> get("/api/v1/blocks")
other_user_id = to_string(other_user.id)
- assert [%{"id" => ^other_user_id}] = json_response(conn, 200)
- assert_schema(json_response(conn, 200), "AccountsResponse", ApiSpec.spec())
+ assert [%{"id" => ^other_user_id}] = json_response_and_validate_schema(conn, 200)
end
end
--
cgit v1.2.3
From 935ca2c1329fd4b4f2b40a5ed7f2c1fa5f95b9bd Mon Sep 17 00:00:00 2001
From: fence
Date: Mon, 27 Apr 2020 19:16:05 +0200
Subject: requested changes to mongoose test
---
test/web/mongooseim/mongoose_im_controller_test.exs | 12 ++++++++++--
1 file changed, 10 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/mongooseim/mongoose_im_controller_test.exs b/test/web/mongooseim/mongoose_im_controller_test.exs
index 5987111e5..2b4d124af 100644
--- a/test/web/mongooseim/mongoose_im_controller_test.exs
+++ b/test/web/mongooseim/mongoose_im_controller_test.exs
@@ -9,6 +9,7 @@ defmodule Pleroma.Web.MongooseIMController do
test "/user_exists", %{conn: conn} do
_user = insert(:user, nickname: "lain")
_remote_user = insert(:user, nickname: "alice", local: false)
+ _deactivated_user = insert(:user, nickname: "konata", deactivated: true)
res =
conn
@@ -30,11 +31,18 @@ defmodule Pleroma.Web.MongooseIMController do
|> json_response(404)
assert res == false
+
+ res =
+ conn
+ |> get(mongoose_im_path(conn, :user_exists), user: "konata")
+ |> json_response(404)
+
+ assert res == false
end
test "/check_password", %{conn: conn} do
user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("cool"))
- _deactivated_user = insert(:user, nickname: "konata", local: false, deactivated: true)
+ _deactivated_user = insert(:user, nickname: "konata", deactivated: true)
res =
conn
@@ -52,7 +60,7 @@ defmodule Pleroma.Web.MongooseIMController do
res =
conn
- |> get(mongoose_im_path(conn, :check_password), user: "konata", pass: "1337")
+ |> get(mongoose_im_path(conn, :check_password), user: "konata", pass: "cool")
|> json_response(404)
assert res == false
--
cgit v1.2.3
From d607b4d84002ff14f51713f1ac74a4971e2dffac Mon Sep 17 00:00:00 2001
From: fence
Date: Mon, 27 Apr 2020 19:32:58 +0200
Subject: mongooseim test: explicitly set password for the deactivated used
---
test/web/mongooseim/mongoose_im_controller_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/mongooseim/mongoose_im_controller_test.exs b/test/web/mongooseim/mongoose_im_controller_test.exs
index 2b4d124af..d17f8dbb4 100644
--- a/test/web/mongooseim/mongoose_im_controller_test.exs
+++ b/test/web/mongooseim/mongoose_im_controller_test.exs
@@ -42,7 +42,7 @@ defmodule Pleroma.Web.MongooseIMController do
test "/check_password", %{conn: conn} do
user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("cool"))
- _deactivated_user = insert(:user, nickname: "konata", deactivated: true)
+ _deactivated_user = insert(:user, nickname: "konata", deactivated: true, password_hash: Comeonin.Pbkdf2.hashpwsalt("cool"))
res =
conn
--
cgit v1.2.3
From dda65f7799e9dfa2e7b87389848eeee10993a858 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 27 Apr 2020 22:55:05 +0400
Subject: Move single used schemas to operation schema
---
test/web/api_spec/account_operation_test.exs | 141 ---------------------
.../controllers/custom_emoji_controller_test.exs | 3 -
2 files changed, 144 deletions(-)
delete mode 100644 test/web/api_spec/account_operation_test.exs
(limited to 'test')
diff --git a/test/web/api_spec/account_operation_test.exs b/test/web/api_spec/account_operation_test.exs
deleted file mode 100644
index 892ade71c..000000000
--- a/test/web/api_spec/account_operation_test.exs
+++ /dev/null
@@ -1,141 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Web.ApiSpec.AccountOperationTest do
- use Pleroma.Web.ConnCase
-
- alias Pleroma.Web.ApiSpec
- alias Pleroma.Web.ApiSpec.Schemas.Account
- alias Pleroma.Web.ApiSpec.Schemas.AccountCreateRequest
- alias Pleroma.Web.ApiSpec.Schemas.AccountCreateResponse
- alias Pleroma.Web.ApiSpec.Schemas.AccountRelationshipsResponse
- alias Pleroma.Web.ApiSpec.Schemas.AccountUpdateCredentialsRequest
-
- import OpenApiSpex.TestAssertions
- import Pleroma.Factory
-
- test "Account example matches schema" do
- api_spec = ApiSpec.spec()
- schema = Account.schema()
- assert_schema(schema.example, "Account", api_spec)
- end
-
- test "AccountCreateRequest example matches schema" do
- api_spec = ApiSpec.spec()
- schema = AccountCreateRequest.schema()
- assert_schema(schema.example, "AccountCreateRequest", api_spec)
- end
-
- test "AccountCreateResponse example matches schema" do
- api_spec = ApiSpec.spec()
- schema = AccountCreateResponse.schema()
- assert_schema(schema.example, "AccountCreateResponse", api_spec)
- end
-
- test "AccountUpdateCredentialsRequest example matches schema" do
- api_spec = ApiSpec.spec()
- schema = AccountUpdateCredentialsRequest.schema()
- assert_schema(schema.example, "AccountUpdateCredentialsRequest", api_spec)
- end
-
- test "AccountController produces a AccountCreateResponse", %{conn: conn} do
- api_spec = ApiSpec.spec()
- app_token = insert(:oauth_token, user: nil)
-
- json =
- conn
- |> put_req_header("authorization", "Bearer " <> app_token.token)
- |> put_req_header("content-type", "application/json")
- |> post(
- "/api/v1/accounts",
- %{
- username: "foo",
- email: "bar@example.org",
- password: "qwerty",
- agreement: true
- }
- )
- |> json_response(200)
-
- assert_schema(json, "AccountCreateResponse", api_spec)
- end
-
- test "AccountUpdateCredentialsRequest produces an Account", %{conn: conn} do
- api_spec = ApiSpec.spec()
- token = insert(:oauth_token, scopes: ["read", "write"])
-
- json =
- conn
- |> put_req_header("authorization", "Bearer " <> token.token)
- |> put_req_header("content-type", "application/json")
- |> patch(
- "/api/v1/accounts/update_credentials",
- %{
- hide_followers_count: "true",
- hide_follows_count: "true",
- skip_thread_containment: "true",
- hide_follows: "true",
- pleroma_settings_store: %{"pleroma-fe" => %{"key" => "val"}},
- note: "foobar",
- fields_attributes: [%{name: "foo", value: "bar"}]
- }
- )
- |> json_response(200)
-
- assert_schema(json, "Account", api_spec)
- end
-
- test "AccountRelationshipsResponse example matches schema" do
- api_spec = ApiSpec.spec()
- schema = AccountRelationshipsResponse.schema()
- assert_schema(schema.example, "AccountRelationshipsResponse", api_spec)
- end
-
- test "/api/v1/accounts/relationships produces AccountRelationshipsResponse", %{
- conn: conn
- } do
- token = insert(:oauth_token, scopes: ["read", "write"])
- other_user = insert(:user)
- {:ok, _user} = Pleroma.User.follow(token.user, other_user)
- api_spec = ApiSpec.spec()
-
- assert [relationship] =
- conn
- |> put_req_header("authorization", "Bearer " <> token.token)
- |> get("/api/v1/accounts/relationships?id=#{other_user.id}")
- |> json_response(:ok)
-
- assert_schema([relationship], "AccountRelationshipsResponse", api_spec)
- end
-
- test "/api/v1/accounts/:id produces Account", %{
- conn: conn
- } do
- user = insert(:user)
- api_spec = ApiSpec.spec()
-
- assert resp =
- conn
- |> get("/api/v1/accounts/#{user.id}")
- |> json_response(:ok)
-
- assert_schema(resp, "Account", api_spec)
- end
-
- test "/api/v1/accounts/:id/statuses produces StatusesResponse", %{
- conn: conn
- } do
- user = insert(:user)
- Pleroma.Web.CommonAPI.post(user, %{"status" => "foobar"})
-
- api_spec = ApiSpec.spec()
-
- assert resp =
- conn
- |> get("/api/v1/accounts/#{user.id}/statuses")
- |> json_response(:ok)
-
- assert_schema(resp, "StatusesResponse", api_spec)
- end
-end
diff --git a/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs b/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs
index 4222556a4..ab0027f90 100644
--- a/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs
+++ b/test/web/mastodon_api/controllers/custom_emoji_controller_test.exs
@@ -4,8 +4,6 @@
defmodule Pleroma.Web.MastodonAPI.CustomEmojiControllerTest do
use Pleroma.Web.ConnCase, async: true
- alias Pleroma.Web.ApiSpec
- import OpenApiSpex.TestAssertions
test "with tags", %{conn: conn} do
assert resp =
@@ -21,6 +19,5 @@ defmodule Pleroma.Web.MastodonAPI.CustomEmojiControllerTest do
assert Map.has_key?(emoji, "category")
assert Map.has_key?(emoji, "url")
assert Map.has_key?(emoji, "visible_in_picker")
- assert_schema(emoji, "CustomEmoji", ApiSpec.spec())
end
end
--
cgit v1.2.3
From 5ff20793e739daa962cdc1623c01dc6ec1ff8a61 Mon Sep 17 00:00:00 2001
From: fence
Date: Tue, 28 Apr 2020 01:29:31 +0200
Subject: formating
---
test/web/mongooseim/mongoose_im_controller_test.exs | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/mongooseim/mongoose_im_controller_test.exs b/test/web/mongooseim/mongoose_im_controller_test.exs
index d17f8dbb4..1ac2f2c27 100644
--- a/test/web/mongooseim/mongoose_im_controller_test.exs
+++ b/test/web/mongooseim/mongoose_im_controller_test.exs
@@ -42,7 +42,13 @@ defmodule Pleroma.Web.MongooseIMController do
test "/check_password", %{conn: conn} do
user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("cool"))
- _deactivated_user = insert(:user, nickname: "konata", deactivated: true, password_hash: Comeonin.Pbkdf2.hashpwsalt("cool"))
+
+ _deactivated_user =
+ insert(:user,
+ nickname: "konata",
+ deactivated: true,
+ password_hash: Comeonin.Pbkdf2.hashpwsalt("cool")
+ )
res =
conn
@@ -65,7 +71,6 @@ defmodule Pleroma.Web.MongooseIMController do
assert res == false
-
res =
conn
|> get(mongoose_im_path(conn, :check_password), user: "nobody", pass: "cool")
--
cgit v1.2.3
From ea5142b94bcd1a02571776440dc828dd08a2c3d6 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Tue, 28 Apr 2020 09:32:43 +0300
Subject: convert markdown content to html
---
test/fixtures/tesla_mock/bittube-video.json | 1 -
test/fixtures/tesla_mock/craigmaloney.json | 112 ++++++++++++
test/fixtures/tesla_mock/hanimated.json | 1 -
test/fixtures/tesla_mock/peertube-social.json | 234 ++++++++++++++++++++++++++
test/support/http_request_mock.ex | 8 +-
test/web/activity_pub/transmogrifier_test.exs | 19 ++-
6 files changed, 364 insertions(+), 11 deletions(-)
delete mode 100644 test/fixtures/tesla_mock/bittube-video.json
create mode 100644 test/fixtures/tesla_mock/craigmaloney.json
delete mode 100644 test/fixtures/tesla_mock/hanimated.json
create mode 100644 test/fixtures/tesla_mock/peertube-social.json
(limited to 'test')
diff --git a/test/fixtures/tesla_mock/bittube-video.json b/test/fixtures/tesla_mock/bittube-video.json
deleted file mode 100644
index be839862f..000000000
--- a/test/fixtures/tesla_mock/bittube-video.json
+++ /dev/null
@@ -1 +0,0 @@
-{"type":"Video","id":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b","name":"Implications of 5G Rollout Simply Explained","duration":"PT428S","uuid":"2aad7dfb-5c75-4ee6-a9ed-08436af0558b","tag":[{"type":"Hashtag","name":"5g"},{"type":"Hashtag","name":"big brother"},{"type":"Hashtag","name":"facial recognition"},{"type":"Hashtag","name":"smart device"}],"category":{"identifier":"15","name":"Science & Technology"},"language":{"identifier":"en","name":"English"},"views":5,"sensitive":false,"waitTranscoding":true,"state":1,"commentsEnabled":true,"downloadEnabled":true,"published":"2020-04-12T11:55:44.805Z","originallyPublishedAt":null,"updated":"2020-04-13T02:01:24.279Z","mediaType":"text/markdown","content":null,"support":null,"subtitleLanguage":[],"icon":{"type":"Image","url":"https://bittube.video/static/thumbnails/2aad7dfb-5c75-4ee6-a9ed-08436af0558b.jpg","mediaType":"image/jpeg","width":223,"height":122},"url":[{"type":"Link","mediaType":"text/html","href":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b"},{"type":"Link","mediaType":"video/mp4","href":"https://bittube.video/static/webseed/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-240.mp4","height":240,"size":17158094,"fps":30},{"type":"Link","mediaType":"application/x-bittorrent","href":"https://bittube.video/static/torrents/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-240.torrent","height":240},{"type":"Link","mediaType":"application/x-bittorrent;x-scheme-handler/magnet","href":"magnet:?xs=https%3A%2F%2Fbittube.video%2Fstatic%2Ftorrents%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-240.torrent&xt=urn:btih:16c8f60d788a29e7ff195de44b4a1558b41dc6c3&dn=Implications+of+5G+Rollout+Simply+Explained&tr=wss%3A%2F%2Fbittube.video%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fbittube.video%2Ftracker%2Fannounce&ws=https%3A%2F%2Fbittube.video%2Fstatic%2Fwebseed%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-240.mp4","height":240},{"type":"Link","mediaType":"video/mp4","href":"https://bittube.video/static/webseed/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-0.mp4","height":0,"size":5215186,"fps":0},{"type":"Link","mediaType":"application/x-bittorrent","href":"https://bittube.video/static/torrents/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-0.torrent","height":0},{"type":"Link","mediaType":"application/x-bittorrent;x-scheme-handler/magnet","href":"magnet:?xs=https%3A%2F%2Fbittube.video%2Fstatic%2Ftorrents%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-0.torrent&xt=urn:btih:8a043b09291f2947423ce96d1cd0e977662d6de8&dn=Implications+of+5G+Rollout+Simply+Explained&tr=wss%3A%2F%2Fbittube.video%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fbittube.video%2Ftracker%2Fannounce&ws=https%3A%2F%2Fbittube.video%2Fstatic%2Fwebseed%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-0.mp4","height":0},{"type":"Link","mediaType":"video/mp4","href":"https://bittube.video/static/webseed/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-360.mp4","height":360,"size":22813140,"fps":30},{"type":"Link","mediaType":"application/x-bittorrent","href":"https://bittube.video/static/torrents/2aad7dfb-5c75-4ee6-a9ed-08436af0558b-360.torrent","height":360},{"type":"Link","mediaType":"application/x-bittorrent;x-scheme-handler/magnet","href":"magnet:?xs=https%3A%2F%2Fbittube.video%2Fstatic%2Ftorrents%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-360.torrent&xt=urn:btih:d121f7493998d4204b3d33d00da7fea1c9a42484&dn=Implications+of+5G+Rollout+Simply+Explained&tr=wss%3A%2F%2Fbittube.video%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fbittube.video%2Ftracker%2Fannounce&ws=https%3A%2F%2Fbittube.video%2Fstatic%2Fwebseed%2F2aad7dfb-5c75-4ee6-a9ed-08436af0558b-360.mp4","height":360}],"likes":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b/likes","dislikes":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b/dislikes","shares":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b/announces","comments":"https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b/comments","attributedTo":[{"type":"Person","id":"https://bittube.video/accounts/hanimated.moh"},{"type":"Group","id":"https://bittube.video/video-channels/hanimated.moh_channel"}],"to":["https://www.w3.org/ns/activitystreams#Public"],"cc":["https://bittube.video/accounts/hanimated.moh/followers"],"@context":["https://www.w3.org/ns/activitystreams","https://w3id.org/security/v1",{"RsaSignature2017":"https://w3id.org/security#RsaSignature2017","pt":"https://joinpeertube.org/ns#","sc":"http://schema.org#","Hashtag":"as:Hashtag","uuid":"sc:identifier","category":"sc:category","licence":"sc:license","subtitleLanguage":"sc:subtitleLanguage","sensitive":"as:sensitive","language":"sc:inLanguage","expires":"sc:expires","CacheFile":"pt:CacheFile","Infohash":"pt:Infohash","originallyPublishedAt":"sc:datePublished","views":{"@type":"sc:Number","@id":"pt:views"},"state":{"@type":"sc:Number","@id":"pt:state"},"size":{"@type":"sc:Number","@id":"pt:size"},"fps":{"@type":"sc:Number","@id":"pt:fps"},"startTimestamp":{"@type":"sc:Number","@id":"pt:startTimestamp"},"stopTimestamp":{"@type":"sc:Number","@id":"pt:stopTimestamp"},"position":{"@type":"sc:Number","@id":"pt:position"},"commentsEnabled":{"@type":"sc:Boolean","@id":"pt:commentsEnabled"},"downloadEnabled":{"@type":"sc:Boolean","@id":"pt:downloadEnabled"},"waitTranscoding":{"@type":"sc:Boolean","@id":"pt:waitTranscoding"},"support":{"@type":"sc:Text","@id":"pt:support"}},{"likes":{"@id":"as:likes","@type":"@id"},"dislikes":{"@id":"as:dislikes","@type":"@id"},"playlists":{"@id":"pt:playlists","@type":"@id"},"shares":{"@id":"as:shares","@type":"@id"},"comments":{"@id":"as:comments","@type":"@id"}}]}
diff --git a/test/fixtures/tesla_mock/craigmaloney.json b/test/fixtures/tesla_mock/craigmaloney.json
new file mode 100644
index 000000000..56ea9c7c3
--- /dev/null
+++ b/test/fixtures/tesla_mock/craigmaloney.json
@@ -0,0 +1,112 @@
+{
+ "@context": [
+ "https://www.w3.org/ns/activitystreams",
+ "https://w3id.org/security/v1",
+ {
+ "CacheFile": "pt:CacheFile",
+ "Hashtag": "as:Hashtag",
+ "Infohash": "pt:Infohash",
+ "RsaSignature2017": "https://w3id.org/security#RsaSignature2017",
+ "category": "sc:category",
+ "commentsEnabled": {
+ "@id": "pt:commentsEnabled",
+ "@type": "sc:Boolean"
+ },
+ "downloadEnabled": {
+ "@id": "pt:downloadEnabled",
+ "@type": "sc:Boolean"
+ },
+ "expires": "sc:expires",
+ "fps": {
+ "@id": "pt:fps",
+ "@type": "sc:Number"
+ },
+ "language": "sc:inLanguage",
+ "licence": "sc:license",
+ "originallyPublishedAt": "sc:datePublished",
+ "position": {
+ "@id": "pt:position",
+ "@type": "sc:Number"
+ },
+ "pt": "https://joinpeertube.org/ns#",
+ "sc": "http://schema.org#",
+ "sensitive": "as:sensitive",
+ "size": {
+ "@id": "pt:size",
+ "@type": "sc:Number"
+ },
+ "startTimestamp": {
+ "@id": "pt:startTimestamp",
+ "@type": "sc:Number"
+ },
+ "state": {
+ "@id": "pt:state",
+ "@type": "sc:Number"
+ },
+ "stopTimestamp": {
+ "@id": "pt:stopTimestamp",
+ "@type": "sc:Number"
+ },
+ "subtitleLanguage": "sc:subtitleLanguage",
+ "support": {
+ "@id": "pt:support",
+ "@type": "sc:Text"
+ },
+ "uuid": "sc:identifier",
+ "views": {
+ "@id": "pt:views",
+ "@type": "sc:Number"
+ },
+ "waitTranscoding": {
+ "@id": "pt:waitTranscoding",
+ "@type": "sc:Boolean"
+ }
+ },
+ {
+ "comments": {
+ "@id": "as:comments",
+ "@type": "@id"
+ },
+ "dislikes": {
+ "@id": "as:dislikes",
+ "@type": "@id"
+ },
+ "likes": {
+ "@id": "as:likes",
+ "@type": "@id"
+ },
+ "playlists": {
+ "@id": "pt:playlists",
+ "@type": "@id"
+ },
+ "shares": {
+ "@id": "as:shares",
+ "@type": "@id"
+ }
+ }
+ ],
+ "endpoints": {
+ "sharedInbox": "https://peertube.social/inbox"
+ },
+ "followers": "https://peertube.social/accounts/craigmaloney/followers",
+ "following": "https://peertube.social/accounts/craigmaloney/following",
+ "icon": {
+ "mediaType": "image/png",
+ "type": "Image",
+ "url": "https://peertube.social/lazy-static/avatars/87bd694b-95bc-4066-83f4-bddfcd2b9caa.png"
+ },
+ "id": "https://peertube.social/accounts/craigmaloney",
+ "inbox": "https://peertube.social/accounts/craigmaloney/inbox",
+ "name": "Craig Maloney",
+ "outbox": "https://peertube.social/accounts/craigmaloney/outbox",
+ "playlists": "https://peertube.social/accounts/craigmaloney/playlists",
+ "preferredUsername": "craigmaloney",
+ "publicKey": {
+ "id": "https://peertube.social/accounts/craigmaloney#main-key",
+ "owner": "https://peertube.social/accounts/craigmaloney",
+ "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA9qvGIYUW01yc8CCsrwxK\n5OXlV5s7EbNWY8tJr/p1oGuELZwAnG2XKxtdbvgcCT+YxL5uRXIdCFIIIKrzRFr/\nHfS0mOgNT9u3gu+SstCNgtatciT0RVP77yiC3b2NHq1NRRvvVhzQb4cpIWObIxqh\nb2ypDClTc7XaKtgmQCbwZlGyZMT+EKz/vustD6BlpGsglRkm7iES6s1PPGb1BU+n\nS94KhbS2DOFiLcXCVWt0QarokIIuKznp4+xP1axKyP+SkT5AHx08Nd5TYFb2C1Jl\nz0WD/1q0mAN62m7QrA3SQPUgB+wWD+S3Nzf7FwNPiP4srbBgxVEUnji/r9mQ6BXC\nrQIDAQAB\n-----END PUBLIC KEY-----"
+ },
+ "summary": null,
+ "type": "Person",
+ "url": "https://peertube.social/accounts/craigmaloney"
+}
diff --git a/test/fixtures/tesla_mock/hanimated.json b/test/fixtures/tesla_mock/hanimated.json
deleted file mode 100644
index 564deebd9..000000000
--- a/test/fixtures/tesla_mock/hanimated.json
+++ /dev/null
@@ -1 +0,0 @@
-{"type":"Person","id":"https://bittube.video/accounts/hanimated.moh","following":"https://bittube.video/accounts/hanimated.moh/following","followers":"https://bittube.video/accounts/hanimated.moh/followers","playlists":"https://bittube.video/accounts/hanimated.moh/playlists","inbox":"https://bittube.video/accounts/hanimated.moh/inbox","outbox":"https://bittube.video/accounts/hanimated.moh/outbox","preferredUsername":"hanimated.moh","url":"https://bittube.video/accounts/hanimated.moh","name":"Nosat","endpoints":{"sharedInbox":"https://bittube.video/inbox"},"publicKey":{"id":"https://bittube.video/accounts/hanimated.moh#main-key","owner":"https://bittube.video/accounts/hanimated.moh","publicKeyPem":"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwuoQT+4uyAboQcf/okCM\nFqUS/LuqFc2888OSKZFAz00Op/dyOB/pkr1+QLxbl8ZGiUWhmnmhNwmmd3tbhSsC\nvLv9Mz/YaWQPYLfRS/s/7iIxdniC4lo/YgicOrzcvetHmk1feOg5vb5/yc+bgUSm\nOk+L4azqXP9GmZyofzvufT65bUmzQRFXP19eL55YZWvZDaC81QAfRXsqtCqbehtF\nQNOjGhnl6a7Kfe8KprRDPV/3WvvFjftnNO2qenIIOFLLeznkQ0ELP6lyb9pvv/1C\n2/GRh2BwmgVlCTw1kTxLSdj80BFX5P8AudSiIx079lVkhamEhzsNLkMpQFqWAAlg\nrQIDAQAB\n-----END PUBLIC KEY-----"},"icon":{"type":"Image","mediaType":"image/jpeg","url":"https://bittube.video/lazy-static/avatars/84b8acc3-e48b-4642-a9f4-360a4499579b.jpg"},"@context":["https://www.w3.org/ns/activitystreams","https://w3id.org/security/v1",{"RsaSignature2017":"https://w3id.org/security#RsaSignature2017","pt":"https://joinpeertube.org/ns#","sc":"http://schema.org#","Hashtag":"as:Hashtag","uuid":"sc:identifier","category":"sc:category","licence":"sc:license","subtitleLanguage":"sc:subtitleLanguage","sensitive":"as:sensitive","language":"sc:inLanguage","expires":"sc:expires","CacheFile":"pt:CacheFile","Infohash":"pt:Infohash","originallyPublishedAt":"sc:datePublished","views":{"@type":"sc:Number","@id":"pt:views"},"state":{"@type":"sc:Number","@id":"pt:state"},"size":{"@type":"sc:Number","@id":"pt:size"},"fps":{"@type":"sc:Number","@id":"pt:fps"},"startTimestamp":{"@type":"sc:Number","@id":"pt:startTimestamp"},"stopTimestamp":{"@type":"sc:Number","@id":"pt:stopTimestamp"},"position":{"@type":"sc:Number","@id":"pt:position"},"commentsEnabled":{"@type":"sc:Boolean","@id":"pt:commentsEnabled"},"downloadEnabled":{"@type":"sc:Boolean","@id":"pt:downloadEnabled"},"waitTranscoding":{"@type":"sc:Boolean","@id":"pt:waitTranscoding"},"support":{"@type":"sc:Text","@id":"pt:support"}},{"likes":{"@id":"as:likes","@type":"@id"},"dislikes":{"@id":"as:dislikes","@type":"@id"},"playlists":{"@id":"pt:playlists","@type":"@id"},"shares":{"@id":"as:shares","@type":"@id"},"comments":{"@id":"as:comments","@type":"@id"}}],"summary":null}
diff --git a/test/fixtures/tesla_mock/peertube-social.json b/test/fixtures/tesla_mock/peertube-social.json
new file mode 100644
index 000000000..0e996ba35
--- /dev/null
+++ b/test/fixtures/tesla_mock/peertube-social.json
@@ -0,0 +1,234 @@
+{
+ "@context": [
+ "https://www.w3.org/ns/activitystreams",
+ "https://w3id.org/security/v1",
+ {
+ "CacheFile": "pt:CacheFile",
+ "Hashtag": "as:Hashtag",
+ "Infohash": "pt:Infohash",
+ "RsaSignature2017": "https://w3id.org/security#RsaSignature2017",
+ "category": "sc:category",
+ "commentsEnabled": {
+ "@id": "pt:commentsEnabled",
+ "@type": "sc:Boolean"
+ },
+ "downloadEnabled": {
+ "@id": "pt:downloadEnabled",
+ "@type": "sc:Boolean"
+ },
+ "expires": "sc:expires",
+ "fps": {
+ "@id": "pt:fps",
+ "@type": "sc:Number"
+ },
+ "language": "sc:inLanguage",
+ "licence": "sc:license",
+ "originallyPublishedAt": "sc:datePublished",
+ "position": {
+ "@id": "pt:position",
+ "@type": "sc:Number"
+ },
+ "pt": "https://joinpeertube.org/ns#",
+ "sc": "http://schema.org#",
+ "sensitive": "as:sensitive",
+ "size": {
+ "@id": "pt:size",
+ "@type": "sc:Number"
+ },
+ "startTimestamp": {
+ "@id": "pt:startTimestamp",
+ "@type": "sc:Number"
+ },
+ "state": {
+ "@id": "pt:state",
+ "@type": "sc:Number"
+ },
+ "stopTimestamp": {
+ "@id": "pt:stopTimestamp",
+ "@type": "sc:Number"
+ },
+ "subtitleLanguage": "sc:subtitleLanguage",
+ "support": {
+ "@id": "pt:support",
+ "@type": "sc:Text"
+ },
+ "uuid": "sc:identifier",
+ "views": {
+ "@id": "pt:views",
+ "@type": "sc:Number"
+ },
+ "waitTranscoding": {
+ "@id": "pt:waitTranscoding",
+ "@type": "sc:Boolean"
+ }
+ },
+ {
+ "comments": {
+ "@id": "as:comments",
+ "@type": "@id"
+ },
+ "dislikes": {
+ "@id": "as:dislikes",
+ "@type": "@id"
+ },
+ "likes": {
+ "@id": "as:likes",
+ "@type": "@id"
+ },
+ "playlists": {
+ "@id": "pt:playlists",
+ "@type": "@id"
+ },
+ "shares": {
+ "@id": "as:shares",
+ "@type": "@id"
+ }
+ }
+ ],
+ "attributedTo": [
+ {
+ "id": "https://peertube.social/accounts/craigmaloney",
+ "type": "Person"
+ },
+ {
+ "id": "https://peertube.social/video-channels/9909c7d9-6b5b-4aae-9164-c1af7229c91c",
+ "type": "Group"
+ }
+ ],
+ "category": {
+ "identifier": "15",
+ "name": "Science & Technology"
+ },
+ "cc": [
+ "https://peertube.social/accounts/craigmaloney/followers"
+ ],
+ "comments": "https://peertube.social/videos/watch/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe/comments",
+ "commentsEnabled": true,
+ "content": "Support this and our other Michigan!/usr/group videos and meetings. Learn more at http://mug.org/membership\n\nTwenty Years in Jail: FreeBSD's Jails, Then and Now\n\nJails started as a limited virtualization system, but over the last two years they've...",
+ "dislikes": "https://peertube.social/videos/watch/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe/dislikes",
+ "downloadEnabled": true,
+ "duration": "PT5151S",
+ "icon": {
+ "height": 122,
+ "mediaType": "image/jpeg",
+ "type": "Image",
+ "url": "https://peertube.social/static/thumbnails/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe.jpg",
+ "width": 223
+ },
+ "id": "https://peertube.social/videos/watch/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe",
+ "language": {
+ "identifier": "en",
+ "name": "English"
+ },
+ "licence": {
+ "identifier": "1",
+ "name": "Attribution"
+ },
+ "likes": "https://peertube.social/videos/watch/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe/likes",
+ "mediaType": "text/markdown",
+ "name": "Twenty Years in Jail: FreeBSD's Jails, Then and Now",
+ "originallyPublishedAt": "2019-08-13T00:00:00.000Z",
+ "published": "2020-02-12T01:06:08.054Z",
+ "sensitive": false,
+ "shares": "https://peertube.social/videos/watch/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe/announces",
+ "state": 1,
+ "subtitleLanguage": [],
+ "support": "Learn more at http://mug.org",
+ "tag": [
+ {
+ "name": "linux",
+ "type": "Hashtag"
+ },
+ {
+ "name": "mug.org",
+ "type": "Hashtag"
+ },
+ {
+ "name": "open",
+ "type": "Hashtag"
+ },
+ {
+ "name": "oss",
+ "type": "Hashtag"
+ },
+ {
+ "name": "source",
+ "type": "Hashtag"
+ }
+ ],
+ "to": [
+ "https://www.w3.org/ns/activitystreams#Public"
+ ],
+ "type": "Video",
+ "updated": "2020-02-15T15:01:09.474Z",
+ "url": [
+ {
+ "href": "https://peertube.social/videos/watch/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe",
+ "mediaType": "text/html",
+ "type": "Link"
+ },
+ {
+ "fps": 30,
+ "height": 240,
+ "href": "https://peertube.social/static/webseed/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-240.mp4",
+ "mediaType": "video/mp4",
+ "size": 119465800,
+ "type": "Link"
+ },
+ {
+ "height": 240,
+ "href": "https://peertube.social/static/torrents/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-240.torrent",
+ "mediaType": "application/x-bittorrent",
+ "type": "Link"
+ },
+ {
+ "height": 240,
+ "href": "magnet:?xs=https%3A%2F%2Fpeertube.social%2Fstatic%2Ftorrents%2F278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-240.torrent&xt=urn:btih:b3365331a8543bf48d09add56d7fe4b1cbbb5659&dn=Twenty+Years+in+Jail%3A+FreeBSD's+Jails%2C+Then+and+Now&tr=wss%3A%2F%2Fpeertube.social%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube.social%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube.social%2Fstatic%2Fwebseed%2F278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-240.mp4",
+ "mediaType": "application/x-bittorrent;x-scheme-handler/magnet",
+ "type": "Link"
+ },
+ {
+ "fps": 30,
+ "height": 360,
+ "href": "https://peertube.social/static/webseed/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-360.mp4",
+ "mediaType": "video/mp4",
+ "size": 143930318,
+ "type": "Link"
+ },
+ {
+ "height": 360,
+ "href": "https://peertube.social/static/torrents/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-360.torrent",
+ "mediaType": "application/x-bittorrent",
+ "type": "Link"
+ },
+ {
+ "height": 360,
+ "href": "magnet:?xs=https%3A%2F%2Fpeertube.social%2Fstatic%2Ftorrents%2F278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-360.torrent&xt=urn:btih:0d37b23c98cb0d89e28b5dc8f49b3c97a041e569&dn=Twenty+Years+in+Jail%3A+FreeBSD's+Jails%2C+Then+and+Now&tr=wss%3A%2F%2Fpeertube.social%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube.social%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube.social%2Fstatic%2Fwebseed%2F278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-360.mp4",
+ "mediaType": "application/x-bittorrent;x-scheme-handler/magnet",
+ "type": "Link"
+ },
+ {
+ "fps": 30,
+ "height": 480,
+ "href": "https://peertube.social/static/webseed/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-480.mp4",
+ "mediaType": "video/mp4",
+ "size": 130530754,
+ "type": "Link"
+ },
+ {
+ "height": 480,
+ "href": "https://peertube.social/static/torrents/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-480.torrent",
+ "mediaType": "application/x-bittorrent",
+ "type": "Link"
+ },
+ {
+ "height": 480,
+ "href": "magnet:?xs=https%3A%2F%2Fpeertube.social%2Fstatic%2Ftorrents%2F278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-480.torrent&xt=urn:btih:3a13ff822ad9494165eff6167183ddaaabc1372a&dn=Twenty+Years+in+Jail%3A+FreeBSD's+Jails%2C+Then+and+Now&tr=wss%3A%2F%2Fpeertube.social%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube.social%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube.social%2Fstatic%2Fwebseed%2F278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe-480.mp4",
+ "mediaType": "application/x-bittorrent;x-scheme-handler/magnet",
+ "type": "Link"
+ }
+ ],
+ "uuid": "278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe",
+ "views": 2,
+ "waitTranscoding": false
+}
diff --git a/test/support/http_request_mock.ex b/test/support/http_request_mock.ex
index 54dde0432..9624cb0f7 100644
--- a/test/support/http_request_mock.ex
+++ b/test/support/http_request_mock.ex
@@ -308,19 +308,19 @@ defmodule HttpRequestMock do
}}
end
- def get("https://bittube.video/accounts/hanimated.moh", _, _, _) do
+ def get("https://peertube.social/accounts/craigmaloney", _, _, _) do
{:ok,
%Tesla.Env{
status: 200,
- body: File.read!("test/fixtures/tesla_mock/hanimated.json")
+ body: File.read!("test/fixtures/tesla_mock/craigmaloney.json")
}}
end
- def get("https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b", _, _, _) do
+ def get("https://peertube.social/videos/watch/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe", _, _, _) do
{:ok,
%Tesla.Env{
status: 200,
- body: File.read!("test/fixtures/tesla_mock/bittube-video.json")
+ body: File.read!("test/fixtures/tesla_mock/peertube-social.json")
}}
end
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index de9663fa9..0404aae6a 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -1221,11 +1221,20 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
:error = Transmogrifier.handle_incoming(data)
end
- test "it remaps mediaType of object" do
- {:ok, object} =
- Fetcher.fetch_object_from_id(
- "https://bittube.video/videos/watch/2aad7dfb-5c75-4ee6-a9ed-08436af0558b"
- )
+ test "it converts content of object to html" do
+ object_id = "https://peertube.social/videos/watch/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe"
+
+ {:ok, %{"content" => content_markdown}} =
+ Fetcher.fetch_and_contain_remote_object_from_id(object_id)
+
+ {:ok, %Pleroma.Object{data: %{"content" => content}} = object} =
+ Fetcher.fetch_object_from_id(object_id)
+
+ assert content_markdown ==
+ "Support this and our other Michigan!/usr/group videos and meetings. Learn more at http://mug.org/membership\n\nTwenty Years in Jail: FreeBSD's Jails, Then and Now\n\nJails started as a limited virtualization system, but over the last two years they've..."
+
+ assert content ==
+ "Support this and our other Michigan!/usr/group videos and meetings. Learn more at http://mug.org/membership
Twenty Years in Jail: FreeBSD’s Jails, Then and Now
Jails started as a limited virtualization system, but over the last two years they’ve…
"
assert object.data["mediaType"] == "text/html"
end
--
cgit v1.2.3
From 560f2c1979ca4d49f18abd6de6aac49875bfc771 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 28 Apr 2020 16:50:37 +0400
Subject: Add OpenAPI spec for ReportController
---
test/web/admin_api/admin_api_controller_test.exs | 40 +++++++++++-----------
test/web/admin_api/views/report_view_test.exs | 18 +++++-----
test/web/common_api/common_api_test.exs | 30 ++++++++--------
.../controllers/report_controller_test.exs | 24 ++++++++-----
4 files changed, 60 insertions(+), 52 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index f80dbf8dd..1862a9589 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -1347,9 +1347,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
{:ok, %{id: report_id}} =
CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "comment" => "I feel offended",
- "status_ids" => [activity.id]
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
})
response =
@@ -1374,16 +1374,16 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
{:ok, %{id: report_id}} =
CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "comment" => "I feel offended",
- "status_ids" => [activity.id]
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
})
{:ok, %{id: second_report_id}} =
CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "comment" => "I feel very offended",
- "status_ids" => [activity.id]
+ account_id: target_user.id,
+ comment: "I feel very offended",
+ status_ids: [activity.id]
})
%{
@@ -1523,9 +1523,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
{:ok, %{id: report_id}} =
CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "comment" => "I feel offended",
- "status_ids" => [activity.id]
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
})
response =
@@ -1547,15 +1547,15 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
{:ok, %{id: first_report_id}} =
CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "comment" => "I feel offended",
- "status_ids" => [activity.id]
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
})
{:ok, %{id: second_report_id}} =
CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "comment" => "I don't like this user"
+ account_id: target_user.id,
+ comment: "I don't like this user"
})
CommonAPI.update_report_state(second_report_id, "closed")
@@ -3431,9 +3431,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
{:ok, %{id: report_id}} =
CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "comment" => "I feel offended",
- "status_ids" => [activity.id]
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
})
post(conn, "/api/pleroma/admin/reports/#{report_id}/notes", %{
diff --git a/test/web/admin_api/views/report_view_test.exs b/test/web/admin_api/views/report_view_test.exs
index 5db6629f2..8cfa1dcfa 100644
--- a/test/web/admin_api/views/report_view_test.exs
+++ b/test/web/admin_api/views/report_view_test.exs
@@ -15,7 +15,7 @@ defmodule Pleroma.Web.AdminAPI.ReportViewTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.report(user, %{"account_id" => other_user.id})
+ {:ok, activity} = CommonAPI.report(user, %{account_id: other_user.id})
expected = %{
content: nil,
@@ -48,7 +48,7 @@ defmodule Pleroma.Web.AdminAPI.ReportViewTest do
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "toot"})
{:ok, report_activity} =
- CommonAPI.report(user, %{"account_id" => other_user.id, "status_ids" => [activity.id]})
+ CommonAPI.report(user, %{account_id: other_user.id, status_ids: [activity.id]})
other_user = Pleroma.User.get_by_id(other_user.id)
@@ -81,7 +81,7 @@ defmodule Pleroma.Web.AdminAPI.ReportViewTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.report(user, %{"account_id" => other_user.id})
+ {:ok, activity} = CommonAPI.report(user, %{account_id: other_user.id})
{:ok, activity} = CommonAPI.update_report_state(activity.id, "closed")
assert %{state: "closed"} =
@@ -94,8 +94,8 @@ defmodule Pleroma.Web.AdminAPI.ReportViewTest do
{:ok, activity} =
CommonAPI.report(user, %{
- "account_id" => other_user.id,
- "comment" => "posts are too good for this instance"
+ account_id: other_user.id,
+ comment: "posts are too good for this instance"
})
assert %{content: "posts are too good for this instance"} =
@@ -108,8 +108,8 @@ defmodule Pleroma.Web.AdminAPI.ReportViewTest do
{:ok, activity} =
CommonAPI.report(user, %{
- "account_id" => other_user.id,
- "comment" => ""
+ account_id: other_user.id,
+ comment: ""
})
data = Map.put(activity.data, "content", "")
@@ -125,8 +125,8 @@ defmodule Pleroma.Web.AdminAPI.ReportViewTest do
{:ok, activity} =
CommonAPI.report(user, %{
- "account_id" => other_user.id,
- "comment" => ""
+ account_id: other_user.id,
+ comment: ""
})
Pleroma.User.delete(other_user)
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index 1758662b0..c6ccc02c4 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -485,9 +485,9 @@ defmodule Pleroma.Web.CommonAPITest do
comment = "foobar"
report_data = %{
- "account_id" => target_user.id,
- "comment" => comment,
- "status_ids" => [activity.id]
+ account_id: target_user.id,
+ comment: comment,
+ status_ids: [activity.id]
}
note_obj = %{
@@ -517,9 +517,9 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, %Activity{id: report_id}} =
CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "comment" => "I feel offended",
- "status_ids" => [activity.id]
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
})
{:ok, report} = CommonAPI.update_report_state(report_id, "resolved")
@@ -538,9 +538,9 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, %Activity{id: report_id}} =
CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "comment" => "I feel offended",
- "status_ids" => [activity.id]
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
})
assert CommonAPI.update_report_state(report_id, "test") == {:error, "Unsupported state"}
@@ -552,16 +552,16 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, %Activity{id: first_report_id}} =
CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "comment" => "I feel offended",
- "status_ids" => [activity.id]
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
})
{:ok, %Activity{id: second_report_id}} =
CommonAPI.report(reporter, %{
- "account_id" => target_user.id,
- "comment" => "I feel very offended!",
- "status_ids" => [activity.id]
+ account_id: target_user.id,
+ comment: "I feel very offended!",
+ status_ids: [activity.id]
})
{:ok, report_ids} =
diff --git a/test/web/mastodon_api/controllers/report_controller_test.exs b/test/web/mastodon_api/controllers/report_controller_test.exs
index 34ec8119e..21b037237 100644
--- a/test/web/mastodon_api/controllers/report_controller_test.exs
+++ b/test/web/mastodon_api/controllers/report_controller_test.exs
@@ -22,8 +22,9 @@ defmodule Pleroma.Web.MastodonAPI.ReportControllerTest do
test "submit a basic report", %{conn: conn, target_user: target_user} do
assert %{"action_taken" => false, "id" => _} =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/reports", %{"account_id" => target_user.id})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
end
test "submit a report with statuses and comment", %{
@@ -33,23 +34,25 @@ defmodule Pleroma.Web.MastodonAPI.ReportControllerTest do
} do
assert %{"action_taken" => false, "id" => _} =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/reports", %{
"account_id" => target_user.id,
"status_ids" => [activity.id],
"comment" => "bad status!",
"forward" => "false"
})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
end
test "account_id is required", %{
conn: conn,
activity: activity
} do
- assert %{"error" => "Valid `account_id` required"} =
+ assert %{"error" => "Missing field: account_id."} =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/reports", %{"status_ids" => [activity.id]})
- |> json_response(400)
+ |> json_response_and_validate_schema(400)
end
test "comment must be up to the size specified in the config", %{
@@ -63,17 +66,21 @@ defmodule Pleroma.Web.MastodonAPI.ReportControllerTest do
assert ^error =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/reports", %{"account_id" => target_user.id, "comment" => comment})
- |> json_response(400)
+ |> json_response_and_validate_schema(400)
end
test "returns error when account is not exist", %{
conn: conn,
activity: activity
} do
- conn = post(conn, "/api/v1/reports", %{"status_ids" => [activity.id], "account_id" => "foo"})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/reports", %{"status_ids" => [activity.id], "account_id" => "foo"})
- assert json_response(conn, 400) == %{"error" => "Account not found"}
+ assert json_response_and_validate_schema(conn, 400) == %{"error" => "Account not found"}
end
test "doesn't fail if an admin has no email", %{conn: conn, target_user: target_user} do
@@ -81,7 +88,8 @@ defmodule Pleroma.Web.MastodonAPI.ReportControllerTest do
assert %{"action_taken" => false, "id" => _} =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/reports", %{"account_id" => target_user.id})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
end
end
--
cgit v1.2.3
From 5238ae3dd3bfba9ff84d5f47e2419227fc7c5d9a Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 28 Apr 2020 21:27:54 +0400
Subject: Add OpenAPI spec for NotificationController
---
.../controllers/notification_controller_test.exs | 181 +++++++++++----------
1 file changed, 92 insertions(+), 89 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs
index 8c815b415..db380f76a 100644
--- a/test/web/mastodon_api/controllers/notification_controller_test.exs
+++ b/test/web/mastodon_api/controllers/notification_controller_test.exs
@@ -25,7 +25,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
conn
|> assign(:user, user)
|> get("/api/v1/notifications")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert Enum.all?(response, fn n ->
get_in(n, ["account", "pleroma", "relationship"]) == %{}
@@ -50,7 +50,9 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
user.ap_id
}\" rel=\"ugc\">@#{user.nickname}"
- assert [%{"status" => %{"content" => response}} | _rest] = json_response(conn, 200)
+ assert [%{"status" => %{"content" => response}} | _rest] =
+ json_response_and_validate_schema(conn, 200)
+
assert response == expected_response
end
@@ -69,7 +71,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
user.ap_id
}\" rel=\"ugc\">@#{user.nickname}"
- assert %{"status" => %{"content" => response}} = json_response(conn, 200)
+ assert %{"status" => %{"content" => response}} = json_response_and_validate_schema(conn, 200)
assert response == expected_response
end
@@ -84,9 +86,10 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
conn =
conn
|> assign(:user, user)
- |> post("/api/v1/notifications/dismiss", %{"id" => notification.id})
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/notifications/dismiss", %{"id" => to_string(notification.id)})
- assert %{} = json_response(conn, 200)
+ assert %{} = json_response_and_validate_schema(conn, 200)
end
test "dismissing a single notification" do
@@ -102,7 +105,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
|> assign(:user, user)
|> post("/api/v1/notifications/#{notification.id}/dismiss")
- assert %{} = json_response(conn, 200)
+ assert %{} = json_response_and_validate_schema(conn, 200)
end
test "clearing all notifications" do
@@ -115,11 +118,11 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
ret_conn = post(conn, "/api/v1/notifications/clear")
- assert %{} = json_response(ret_conn, 200)
+ assert %{} = json_response_and_validate_schema(ret_conn, 200)
ret_conn = get(conn, "/api/v1/notifications")
- assert all = json_response(ret_conn, 200)
+ assert all = json_response_and_validate_schema(ret_conn, 200)
assert all == []
end
@@ -143,7 +146,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
result =
conn
|> get("/api/v1/notifications?limit=2&min_id=#{notification1_id}")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert [%{"id" => ^notification3_id}, %{"id" => ^notification2_id}] = result
@@ -151,7 +154,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
result =
conn
|> get("/api/v1/notifications?limit=2&since_id=#{notification1_id}")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert [%{"id" => ^notification4_id}, %{"id" => ^notification3_id}] = result
@@ -159,7 +162,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
result =
conn
|> get("/api/v1/notifications?limit=2&max_id=#{notification4_id}")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert [%{"id" => ^notification3_id}, %{"id" => ^notification2_id}] = result
end
@@ -181,36 +184,28 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
{:ok, private_activity} =
CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "private"})
- conn_res =
- get(conn, "/api/v1/notifications", %{
- exclude_visibilities: ["public", "unlisted", "private"]
- })
+ query = params_to_query(%{exclude_visibilities: ["public", "unlisted", "private"]})
+ conn_res = get(conn, "/api/v1/notifications?" <> query)
- assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200)
+ assert [%{"status" => %{"id" => id}}] = json_response_and_validate_schema(conn_res, 200)
assert id == direct_activity.id
- conn_res =
- get(conn, "/api/v1/notifications", %{
- exclude_visibilities: ["public", "unlisted", "direct"]
- })
+ query = params_to_query(%{exclude_visibilities: ["public", "unlisted", "direct"]})
+ conn_res = get(conn, "/api/v1/notifications?" <> query)
- assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200)
+ assert [%{"status" => %{"id" => id}}] = json_response_and_validate_schema(conn_res, 200)
assert id == private_activity.id
- conn_res =
- get(conn, "/api/v1/notifications", %{
- exclude_visibilities: ["public", "private", "direct"]
- })
+ query = params_to_query(%{exclude_visibilities: ["public", "private", "direct"]})
+ conn_res = get(conn, "/api/v1/notifications?" <> query)
- assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200)
+ assert [%{"status" => %{"id" => id}}] = json_response_and_validate_schema(conn_res, 200)
assert id == unlisted_activity.id
- conn_res =
- get(conn, "/api/v1/notifications", %{
- exclude_visibilities: ["unlisted", "private", "direct"]
- })
+ query = params_to_query(%{exclude_visibilities: ["unlisted", "private", "direct"]})
+ conn_res = get(conn, "/api/v1/notifications?" <> query)
- assert [%{"status" => %{"id" => id}}] = json_response(conn_res, 200)
+ assert [%{"status" => %{"id" => id}}] = json_response_and_validate_schema(conn_res, 200)
assert id == public_activity.id
end
@@ -237,8 +232,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
activity_ids =
conn
- |> get("/api/v1/notifications", %{exclude_visibilities: ["direct"]})
- |> json_response(200)
+ |> get("/api/v1/notifications?exclude_visibilities[]=direct")
+ |> json_response_and_validate_schema(200)
|> Enum.map(& &1["status"]["id"])
assert public_activity.id in activity_ids
@@ -248,8 +243,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
activity_ids =
conn
- |> get("/api/v1/notifications", %{exclude_visibilities: ["unlisted"]})
- |> json_response(200)
+ |> get("/api/v1/notifications?exclude_visibilities[]=unlisted")
+ |> json_response_and_validate_schema(200)
|> Enum.map(& &1["status"]["id"])
assert public_activity.id in activity_ids
@@ -259,8 +254,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
activity_ids =
conn
- |> get("/api/v1/notifications", %{exclude_visibilities: ["private"]})
- |> json_response(200)
+ |> get("/api/v1/notifications?exclude_visibilities[]=private")
+ |> json_response_and_validate_schema(200)
|> Enum.map(& &1["status"]["id"])
assert public_activity.id in activity_ids
@@ -270,8 +265,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
activity_ids =
conn
- |> get("/api/v1/notifications", %{exclude_visibilities: ["public"]})
- |> json_response(200)
+ |> get("/api/v1/notifications?exclude_visibilities[]=public")
+ |> json_response_and_validate_schema(200)
|> Enum.map(& &1["status"]["id"])
refute public_activity.id in activity_ids
@@ -295,8 +290,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
activity_ids =
conn
- |> get("/api/v1/notifications", %{exclude_visibilities: ["unlisted"]})
- |> json_response(200)
+ |> get("/api/v1/notifications?exclude_visibilities[]=unlisted")
+ |> json_response_and_validate_schema(200)
|> Enum.map(& &1["status"]["id"])
assert public_activity.id in activity_ids
@@ -319,25 +314,27 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
reblog_notification_id = get_notification_id_by_activity(reblog_activity)
follow_notification_id = get_notification_id_by_activity(follow_activity)
- conn_res =
- get(conn, "/api/v1/notifications", %{exclude_types: ["mention", "favourite", "reblog"]})
+ query = params_to_query(%{exclude_types: ["mention", "favourite", "reblog"]})
+ conn_res = get(conn, "/api/v1/notifications?" <> query)
- assert [%{"id" => ^follow_notification_id}] = json_response(conn_res, 200)
+ assert [%{"id" => ^follow_notification_id}] = json_response_and_validate_schema(conn_res, 200)
- conn_res =
- get(conn, "/api/v1/notifications", %{exclude_types: ["favourite", "reblog", "follow"]})
+ query = params_to_query(%{exclude_types: ["favourite", "reblog", "follow"]})
+ conn_res = get(conn, "/api/v1/notifications?" <> query)
- assert [%{"id" => ^mention_notification_id}] = json_response(conn_res, 200)
+ assert [%{"id" => ^mention_notification_id}] =
+ json_response_and_validate_schema(conn_res, 200)
- conn_res =
- get(conn, "/api/v1/notifications", %{exclude_types: ["reblog", "follow", "mention"]})
+ query = params_to_query(%{exclude_types: ["reblog", "follow", "mention"]})
+ conn_res = get(conn, "/api/v1/notifications?" <> query)
- assert [%{"id" => ^favorite_notification_id}] = json_response(conn_res, 200)
+ assert [%{"id" => ^favorite_notification_id}] =
+ json_response_and_validate_schema(conn_res, 200)
- conn_res =
- get(conn, "/api/v1/notifications", %{exclude_types: ["follow", "mention", "favourite"]})
+ query = params_to_query(%{exclude_types: ["follow", "mention", "favourite"]})
+ conn_res = get(conn, "/api/v1/notifications?" <> query)
- assert [%{"id" => ^reblog_notification_id}] = json_response(conn_res, 200)
+ assert [%{"id" => ^reblog_notification_id}] = json_response_and_validate_schema(conn_res, 200)
end
test "filters notifications using include_types" do
@@ -355,32 +352,34 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
reblog_notification_id = get_notification_id_by_activity(reblog_activity)
follow_notification_id = get_notification_id_by_activity(follow_activity)
- conn_res = get(conn, "/api/v1/notifications", %{include_types: ["follow"]})
+ conn_res = get(conn, "/api/v1/notifications?include_types[]=follow")
- assert [%{"id" => ^follow_notification_id}] = json_response(conn_res, 200)
+ assert [%{"id" => ^follow_notification_id}] = json_response_and_validate_schema(conn_res, 200)
- conn_res = get(conn, "/api/v1/notifications", %{include_types: ["mention"]})
+ conn_res = get(conn, "/api/v1/notifications?include_types[]=mention")
- assert [%{"id" => ^mention_notification_id}] = json_response(conn_res, 200)
+ assert [%{"id" => ^mention_notification_id}] =
+ json_response_and_validate_schema(conn_res, 200)
- conn_res = get(conn, "/api/v1/notifications", %{include_types: ["favourite"]})
+ conn_res = get(conn, "/api/v1/notifications?include_types[]=favourite")
- assert [%{"id" => ^favorite_notification_id}] = json_response(conn_res, 200)
+ assert [%{"id" => ^favorite_notification_id}] =
+ json_response_and_validate_schema(conn_res, 200)
- conn_res = get(conn, "/api/v1/notifications", %{include_types: ["reblog"]})
+ conn_res = get(conn, "/api/v1/notifications?include_types[]=reblog")
- assert [%{"id" => ^reblog_notification_id}] = json_response(conn_res, 200)
+ assert [%{"id" => ^reblog_notification_id}] = json_response_and_validate_schema(conn_res, 200)
- result = conn |> get("/api/v1/notifications") |> json_response(200)
+ result = conn |> get("/api/v1/notifications") |> json_response_and_validate_schema(200)
assert length(result) == 4
+ query = params_to_query(%{include_types: ["follow", "mention", "favourite", "reblog"]})
+
result =
conn
- |> get("/api/v1/notifications", %{
- include_types: ["follow", "mention", "favourite", "reblog"]
- })
- |> json_response(200)
+ |> get("/api/v1/notifications?" <> query)
+ |> json_response_and_validate_schema(200)
assert length(result) == 4
end
@@ -402,7 +401,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
result =
conn
|> get("/api/v1/notifications")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert [%{"id" => ^notification2_id}, %{"id" => ^notification1_id}] = result
@@ -414,22 +413,19 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
result =
conn2
|> get("/api/v1/notifications")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert [%{"id" => ^notification4_id}, %{"id" => ^notification3_id}] = result
- conn_destroy =
- conn
- |> delete("/api/v1/notifications/destroy_multiple", %{
- "ids" => [notification1_id, notification2_id]
- })
+ query = params_to_query(%{ids: [notification1_id, notification2_id]})
+ conn_destroy = delete(conn, "/api/v1/notifications/destroy_multiple?" <> query)
- assert json_response(conn_destroy, 200) == %{}
+ assert json_response_and_validate_schema(conn_destroy, 200) == %{}
result =
conn2
|> get("/api/v1/notifications")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert [%{"id" => ^notification4_id}, %{"id" => ^notification3_id}] = result
end
@@ -443,13 +439,13 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
ret_conn = get(conn, "/api/v1/notifications")
- assert length(json_response(ret_conn, 200)) == 1
+ assert length(json_response_and_validate_schema(ret_conn, 200)) == 1
{:ok, _user_relationships} = User.mute(user, user2)
conn = get(conn, "/api/v1/notifications")
- assert json_response(conn, 200) == []
+ assert json_response_and_validate_schema(conn, 200) == []
end
test "see notifications after muting user without notifications" do
@@ -461,13 +457,13 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
ret_conn = get(conn, "/api/v1/notifications")
- assert length(json_response(ret_conn, 200)) == 1
+ assert length(json_response_and_validate_schema(ret_conn, 200)) == 1
{:ok, _user_relationships} = User.mute(user, user2, false)
conn = get(conn, "/api/v1/notifications")
- assert length(json_response(conn, 200)) == 1
+ assert length(json_response_and_validate_schema(conn, 200)) == 1
end
test "see notifications after muting user with notifications and with_muted parameter" do
@@ -479,13 +475,13 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
ret_conn = get(conn, "/api/v1/notifications")
- assert length(json_response(ret_conn, 200)) == 1
+ assert length(json_response_and_validate_schema(ret_conn, 200)) == 1
{:ok, _user_relationships} = User.mute(user, user2)
- conn = get(conn, "/api/v1/notifications", %{"with_muted" => "true"})
+ conn = get(conn, "/api/v1/notifications?with_muted=true")
- assert length(json_response(conn, 200)) == 1
+ assert length(json_response_and_validate_schema(conn, 200)) == 1
end
@tag capture_log: true
@@ -512,7 +508,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
conn = get(conn, "/api/v1/notifications")
- assert length(json_response(conn, 200)) == 1
+ assert length(json_response_and_validate_schema(conn, 200)) == 1
end
describe "link headers" do
@@ -538,10 +534,10 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
conn =
conn
|> assign(:user, user)
- |> get("/api/v1/notifications", %{media_only: true})
+ |> get("/api/v1/notifications?limit=5")
assert [link_header] = get_resp_header(conn, "link")
- assert link_header =~ ~r/media_only=true/
+ assert link_header =~ ~r/limit=5/
assert link_header =~ ~r/min_id=#{notification2.id}/
assert link_header =~ ~r/max_id=#{notification1.id}/
end
@@ -560,14 +556,14 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
assert [%{"account" => %{"id" => ^account_id}}] =
conn
|> assign(:user, user)
- |> get("/api/v1/notifications", %{account_id: account_id})
- |> json_response(200)
+ |> get("/api/v1/notifications?account_id=#{account_id}")
+ |> json_response_and_validate_schema(200)
assert %{"error" => "Account is not found"} =
conn
|> assign(:user, user)
- |> get("/api/v1/notifications", %{account_id: "cofe"})
- |> json_response(404)
+ |> get("/api/v1/notifications?account_id=cofe")
+ |> json_response_and_validate_schema(404)
end
end
@@ -577,4 +573,11 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
|> Map.get(:id)
|> to_string()
end
+
+ defp params_to_query(%{} = params) do
+ Enum.map_join(params, "&", fn
+ {k, v} when is_list(v) -> Enum.map_join(v, "&", &"#{k}[]=#{&1}")
+ {k, v} -> k <> "=" <> v
+ end)
+ end
end
--
cgit v1.2.3
From 7bd187bc5e2e589f3ba639bbc0ab2feea905a9b0 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Wed, 29 Apr 2020 08:13:10 +0300
Subject: added test
---
test/web/activity_pub/transmogrifier_test.exs | 11 +++++++++++
1 file changed, 11 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 0404aae6a..0800305ce 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -1221,6 +1221,17 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
:error = Transmogrifier.handle_incoming(data)
end
+ test "skip converting the content when it is nil" do
+ object_id = "https://peertube.social/videos/watch/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe"
+
+ {:ok, object} = Fetcher.fetch_and_contain_remote_object_from_id(object_id)
+
+ result =
+ Pleroma.Web.ActivityPub.Transmogrifier.fix_object(Map.merge(object, %{"content" => nil}))
+
+ assert result["content"] == nil
+ end
+
test "it converts content of object to html" do
object_id = "https://peertube.social/videos/watch/278d2b7c-0f38-4aaa-afe6-9ecc0c4a34fe"
--
cgit v1.2.3
From b8056e69e0a2505fc466dd5742b0986b7c1895ae Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 29 Apr 2020 19:08:08 +0200
Subject: Object Validator Types: Add Recipients.
---
.../object_validators/types/recipients_test.exs | 27 ++++++++++++++++++++++
1 file changed, 27 insertions(+)
create mode 100644 test/web/activity_pub/object_validators/types/recipients_test.exs
(limited to 'test')
diff --git a/test/web/activity_pub/object_validators/types/recipients_test.exs b/test/web/activity_pub/object_validators/types/recipients_test.exs
new file mode 100644
index 000000000..f278f039b
--- /dev/null
+++ b/test/web/activity_pub/object_validators/types/recipients_test.exs
@@ -0,0 +1,27 @@
+defmodule Pleroma.Web.ObjectValidators.Types.RecipientsTest do
+ alias Pleroma.Web.ActivityPub.ObjectValidators.Types.Recipients
+ use Pleroma.DataCase
+
+ test "it asserts that all elements of the list are object ids" do
+ list = ["https://lain.com/users/lain", "invalid"]
+
+ assert :error == Recipients.cast(list)
+ end
+
+ test "it works with a list" do
+ list = ["https://lain.com/users/lain"]
+ assert {:ok, list} == Recipients.cast(list)
+ end
+
+ test "it works with a list with whole objects" do
+ list = ["https://lain.com/users/lain", %{"id" => "https://gensokyo.2hu/users/raymoo"}]
+ resulting_list = ["https://gensokyo.2hu/users/raymoo", "https://lain.com/users/lain"]
+ assert {:ok, resulting_list} == Recipients.cast(list)
+ end
+
+ test "it turns a single string into a list" do
+ recipient = "https://lain.com/users/lain"
+
+ assert {:ok, [recipient]} == Recipients.cast(recipient)
+ end
+end
--
cgit v1.2.3
From 503de4b8df0bfc34008c3c856edc488633290f0e Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 29 Apr 2020 19:09:51 +0200
Subject: ObjectValidator: Add validation for `Delete`s.
---
test/web/activity_pub/object_validator_test.exs | 67 +++++++++++++++++++++++++
1 file changed, 67 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 3c5c3696e..64b9ee1ec 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -1,6 +1,7 @@
defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
use Pleroma.DataCase
+ alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.ObjectValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator
alias Pleroma.Web.ActivityPub.Utils
@@ -8,6 +9,72 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
import Pleroma.Factory
+ describe "deletes" do
+ setup do
+ user = insert(:user)
+ {:ok, post_activity} = CommonAPI.post(user, %{"status" => "cancel me daddy"})
+
+ {:ok, valid_post_delete, _} = Builder.delete(user, post_activity.data["object"])
+
+ %{user: user, valid_post_delete: valid_post_delete}
+ end
+
+ test "it is valid for a post deletion", %{valid_post_delete: valid_post_delete} do
+ assert match?({:ok, _, _}, ObjectValidator.validate(valid_post_delete, []))
+ end
+
+ test "it's invalid if the id is missing", %{valid_post_delete: valid_post_delete} do
+ no_id =
+ valid_post_delete
+ |> Map.delete("id")
+
+ {:error, cng} = ObjectValidator.validate(no_id, [])
+
+ assert {:id, {"can't be blank", [validation: :required]}} in cng.errors
+ end
+
+ test "it's invalid if the object doesn't exist", %{valid_post_delete: valid_post_delete} do
+ missing_object =
+ valid_post_delete
+ |> Map.put("object", "http://does.not/exist")
+
+ {:error, cng} = ObjectValidator.validate(missing_object, [])
+
+ assert {:object, {"can't find object", []}} in cng.errors
+ end
+
+ test "it's invalid if the actor of the object and the actor of delete are from different domains",
+ %{valid_post_delete: valid_post_delete} do
+ valid_other_actor =
+ valid_post_delete
+ |> Map.put("actor", valid_post_delete["actor"] <> "1")
+
+ assert match?({:ok, _, _}, ObjectValidator.validate(valid_other_actor, []))
+
+ invalid_other_actor =
+ valid_post_delete
+ |> Map.put("actor", "https://gensokyo.2hu/users/raymoo")
+
+ {:error, cng} = ObjectValidator.validate(invalid_other_actor, [])
+
+ assert {:actor, {"is not allowed to delete object", []}} in cng.errors
+ end
+
+ test "it's invalid if all the recipient fields are empty", %{
+ valid_post_delete: valid_post_delete
+ } do
+ empty_recipients =
+ valid_post_delete
+ |> Map.put("to", [])
+ |> Map.put("cc", [])
+
+ {:error, cng} = ObjectValidator.validate(empty_recipients, [])
+
+ assert {:to, {"no recipients in any field", []}} in cng.errors
+ assert {:cc, {"no recipients in any field", []}} in cng.errors
+ end
+ end
+
describe "likes" do
setup do
user = insert(:user)
--
cgit v1.2.3
From 7b0c8f0fde495e50c5434575c452addeace39e60 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 29 Apr 2020 20:48:08 +0400
Subject: Add tests for account registration with captcha enabled and improve
errors
---
test/captcha_test.exs | 7 +-
test/support/captcha_mock.ex | 6 +-
.../controllers/account_controller_test.exs | 88 +++++++++++++++++++++-
test/web/twitter_api/twitter_api_test.exs | 41 +++++-----
4 files changed, 116 insertions(+), 26 deletions(-)
(limited to 'test')
diff --git a/test/captcha_test.exs b/test/captcha_test.exs
index ac1d846e8..1ab9019ab 100644
--- a/test/captcha_test.exs
+++ b/test/captcha_test.exs
@@ -61,7 +61,7 @@ defmodule Pleroma.CaptchaTest do
assert is_binary(answer)
assert :ok = Native.validate(token, answer, answer)
- assert {:error, "Invalid CAPTCHA"} == Native.validate(token, answer, answer <> "foobar")
+ assert {:error, :invalid} == Native.validate(token, answer, answer <> "foobar")
end
end
@@ -78,6 +78,7 @@ defmodule Pleroma.CaptchaTest do
assert is_binary(answer)
assert :ok = Captcha.validate(token, "63615261b77f5354fb8c4e4986477555", answer)
+ Cachex.del(:used_captcha_cache, token)
end
test "doesn't validate invalid answer" do
@@ -92,7 +93,7 @@ defmodule Pleroma.CaptchaTest do
assert is_binary(answer)
- assert {:error, "Invalid answer data"} =
+ assert {:error, :invalid_answer_data} =
Captcha.validate(token, "63615261b77f5354fb8c4e4986477555", answer <> "foobar")
end
@@ -108,7 +109,7 @@ defmodule Pleroma.CaptchaTest do
assert is_binary(answer)
- assert {:error, "Invalid answer data"} =
+ assert {:error, :invalid_answer_data} =
Captcha.validate(token, "63615261b77f5354fb8c4e4986477555", nil)
end
end
diff --git a/test/support/captcha_mock.ex b/test/support/captcha_mock.ex
index 6dae94edf..7b0c1d5af 100644
--- a/test/support/captcha_mock.ex
+++ b/test/support/captcha_mock.ex
@@ -6,12 +6,16 @@ defmodule Pleroma.Captcha.Mock do
alias Pleroma.Captcha.Service
@behaviour Service
+ @solution "63615261b77f5354fb8c4e4986477555"
+
+ def solution, do: @solution
+
@impl Service
def new,
do: %{
type: :mock,
token: "afa1815e14e29355e6c8f6b143a39fa2",
- answer_data: "63615261b77f5354fb8c4e4986477555",
+ answer_data: @solution,
url: "https://example.org/captcha.png"
}
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index ba70ba66c..b9da7e924 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -925,7 +925,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
|> Map.put(:remote_ip, {127, 0, 0, 5})
|> post("/api/v1/accounts", Map.delete(valid_params, :email))
- assert json_response_and_validate_schema(res, 400) == %{"error" => "Missing parameters"}
+ assert json_response_and_validate_schema(res, 400) ==
+ %{"error" => "Missing parameter: email"}
res =
conn
@@ -1093,6 +1094,91 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
end
end
+ describe "create account with enabled captcha" do
+ setup %{conn: conn} do
+ app_token = insert(:oauth_token, user: nil)
+
+ conn =
+ conn
+ |> put_req_header("authorization", "Bearer " <> app_token.token)
+ |> put_req_header("content-type", "multipart/form-data")
+
+ [conn: conn]
+ end
+
+ setup do: clear_config([Pleroma.Captcha, :enabled], true)
+
+ test "creates an account and returns 200 if captcha is valid", %{conn: conn} do
+ %{token: token, answer_data: answer_data} = Pleroma.Captcha.new()
+
+ params = %{
+ username: "lain",
+ email: "lain@example.org",
+ password: "PlzDontHackLain",
+ agreement: true,
+ captcha_solution: Pleroma.Captcha.Mock.solution(),
+ captcha_token: token,
+ captcha_answer_data: answer_data
+ }
+
+ assert %{
+ "access_token" => access_token,
+ "created_at" => _,
+ "scope" => ["read"],
+ "token_type" => "Bearer"
+ } =
+ conn
+ |> post("/api/v1/accounts", params)
+ |> json_response_and_validate_schema(:ok)
+
+ assert Token |> Repo.get_by(token: access_token) |> Repo.preload(:user) |> Map.get(:user)
+
+ Cachex.del(:used_captcha_cache, token)
+ end
+
+ test "returns 400 if any captcha field is not provided", %{conn: conn} do
+ captcha_fields = [:captcha_solution, :captcha_token, :captcha_answer_data]
+
+ valid_params = %{
+ username: "lain",
+ email: "lain@example.org",
+ password: "PlzDontHackLain",
+ agreement: true,
+ captcha_solution: "xx",
+ captcha_token: "xx",
+ captcha_answer_data: "xx"
+ }
+
+ for field <- captcha_fields do
+ expected = %{
+ "error" => "{\"captcha\":[\"Invalid CAPTCHA (Missing parameter: #{field})\"]}"
+ }
+
+ assert expected ==
+ conn
+ |> post("/api/v1/accounts", Map.delete(valid_params, field))
+ |> json_response_and_validate_schema(:bad_request)
+ end
+ end
+
+ test "returns an error if captcha is invalid", %{conn: conn} do
+ params = %{
+ username: "lain",
+ email: "lain@example.org",
+ password: "PlzDontHackLain",
+ agreement: true,
+ captcha_solution: "cofe",
+ captcha_token: "cofe",
+ captcha_answer_data: "cofe"
+ }
+
+ assert %{"error" => "{\"captcha\":[\"Invalid answer data\"]}"} ==
+ conn
+ |> post("/api/v1/accounts", params)
+ |> json_response_and_validate_schema(:bad_request)
+ end
+ end
+
describe "GET /api/v1/accounts/:id/lists - account_lists" do
test "returns lists to which the account belongs" do
%{user: user, conn: conn} = oauth_access(["read:lists"])
diff --git a/test/web/twitter_api/twitter_api_test.exs b/test/web/twitter_api/twitter_api_test.exs
index 7926a0757..368533292 100644
--- a/test/web/twitter_api/twitter_api_test.exs
+++ b/test/web/twitter_api/twitter_api_test.exs
@@ -18,7 +18,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
test "it registers a new user and returns the user." do
data = %{
- :nickname => "lain",
+ :username => "lain",
:email => "lain@wired.jp",
:fullname => "lain iwakura",
:password => "bear",
@@ -35,7 +35,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
test "it registers a new user with empty string in bio and returns the user." do
data = %{
- :nickname => "lain",
+ :username => "lain",
:email => "lain@wired.jp",
:fullname => "lain iwakura",
:bio => "",
@@ -60,7 +60,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
end
data = %{
- :nickname => "lain",
+ :username => "lain",
:email => "lain@wired.jp",
:fullname => "lain iwakura",
:bio => "",
@@ -87,7 +87,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
test "it registers a new user and parses mentions in the bio" do
data1 = %{
- :nickname => "john",
+ :username => "john",
:email => "john@gmail.com",
:fullname => "John Doe",
:bio => "test",
@@ -98,7 +98,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
{:ok, user1} = TwitterAPI.register_user(data1)
data2 = %{
- :nickname => "lain",
+ :username => "lain",
:email => "lain@wired.jp",
:fullname => "lain iwakura",
:bio => "@john test",
@@ -123,7 +123,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
{:ok, invite} = UserInviteToken.create_invite()
data = %{
- :nickname => "vinny",
+ :username => "vinny",
:email => "pasta@pizza.vs",
:fullname => "Vinny Vinesauce",
:bio => "streamer",
@@ -145,7 +145,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
test "returns error on invalid token" do
data = %{
- :nickname => "GrimReaper",
+ :username => "GrimReaper",
:email => "death@reapers.afterlife",
:fullname => "Reaper Grim",
:bio => "Your time has come",
@@ -165,7 +165,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
UserInviteToken.update_invite!(invite, used: true)
data = %{
- :nickname => "GrimReaper",
+ :username => "GrimReaper",
:email => "death@reapers.afterlife",
:fullname => "Reaper Grim",
:bio => "Your time has come",
@@ -186,7 +186,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
setup do
data = %{
- :nickname => "vinny",
+ :username => "vinny",
:email => "pasta@pizza.vs",
:fullname => "Vinny Vinesauce",
:bio => "streamer",
@@ -250,7 +250,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
UserInviteToken.update_invite!(invite, uses: 99)
data = %{
- :nickname => "vinny",
+ :username => "vinny",
:email => "pasta@pizza.vs",
:fullname => "Vinny Vinesauce",
:bio => "streamer",
@@ -269,7 +269,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
AccountView.render("show.json", %{user: fetched_user})
data = %{
- :nickname => "GrimReaper",
+ :username => "GrimReaper",
:email => "death@reapers.afterlife",
:fullname => "Reaper Grim",
:bio => "Your time has come",
@@ -292,7 +292,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
{:ok, invite} = UserInviteToken.create_invite(%{expires_at: Date.utc_today(), max_use: 100})
data = %{
- :nickname => "vinny",
+ :username => "vinny",
:email => "pasta@pizza.vs",
:fullname => "Vinny Vinesauce",
:bio => "streamer",
@@ -317,7 +317,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
UserInviteToken.update_invite!(invite, uses: 99)
data = %{
- :nickname => "vinny",
+ :username => "vinny",
:email => "pasta@pizza.vs",
:fullname => "Vinny Vinesauce",
:bio => "streamer",
@@ -335,7 +335,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
AccountView.render("show.json", %{user: fetched_user})
data = %{
- :nickname => "GrimReaper",
+ :username => "GrimReaper",
:email => "death@reapers.afterlife",
:fullname => "Reaper Grim",
:bio => "Your time has come",
@@ -355,7 +355,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
UserInviteToken.create_invite(%{expires_at: Date.add(Date.utc_today(), -1), max_use: 100})
data = %{
- :nickname => "GrimReaper",
+ :username => "GrimReaper",
:email => "death@reapers.afterlife",
:fullname => "Reaper Grim",
:bio => "Your time has come",
@@ -377,7 +377,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
UserInviteToken.update_invite!(invite, uses: 100)
data = %{
- :nickname => "GrimReaper",
+ :username => "GrimReaper",
:email => "death@reapers.afterlife",
:fullname => "Reaper Grim",
:bio => "Your time has come",
@@ -395,16 +395,15 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do
test "it returns the error on registration problems" do
data = %{
- :nickname => "lain",
+ :username => "lain",
:email => "lain@wired.jp",
:fullname => "lain iwakura",
- :bio => "close the world.",
- :password => "bear"
+ :bio => "close the world."
}
- {:error, error_object} = TwitterAPI.register_user(data)
+ {:error, error} = TwitterAPI.register_user(data)
- assert is_binary(error_object[:error])
+ assert is_binary(error)
refute User.get_cached_by_nickname("lain")
end
--
cgit v1.2.3
From bd219ba7e884d694cc1c8747f0b48cd646821222 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 14:14:00 +0200
Subject: Transmogrifier Tests: Extract deletion tests.
---
.../transmogrifier/delete_handling_test.exs | 106 +++++++++++++++++++++
test/web/activity_pub/transmogrifier_test.exs | 77 ---------------
2 files changed, 106 insertions(+), 77 deletions(-)
create mode 100644 test/web/activity_pub/transmogrifier/delete_handling_test.exs
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier/delete_handling_test.exs b/test/web/activity_pub/transmogrifier/delete_handling_test.exs
new file mode 100644
index 000000000..c15de5a95
--- /dev/null
+++ b/test/web/activity_pub/transmogrifier/delete_handling_test.exs
@@ -0,0 +1,106 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do
+ use Oban.Testing, repo: Pleroma.Repo
+ use Pleroma.DataCase
+
+ alias Pleroma.Activity
+ alias Pleroma.Object
+ alias Pleroma.Tests.ObanHelpers
+ alias Pleroma.User
+ alias Pleroma.Web.ActivityPub.Transmogrifier
+
+ import Pleroma.Factory
+ import ExUnit.CaptureLog
+
+ setup_all do
+ Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
+ :ok
+ end
+
+ test "it works for incoming deletes" do
+ activity = insert(:note_activity)
+ deleting_user = insert(:user)
+
+ data =
+ File.read!("test/fixtures/mastodon-delete.json")
+ |> Poison.decode!()
+
+ object =
+ data["object"]
+ |> Map.put("id", activity.data["object"])
+
+ data =
+ data
+ |> Map.put("object", object)
+ |> Map.put("actor", deleting_user.ap_id)
+
+ {:ok, %Activity{actor: actor, local: false, data: %{"id" => id}}} =
+ Transmogrifier.handle_incoming(data)
+
+ assert id == data["id"]
+
+ # We delete the Create activity because base our timelines on it.
+ # This should be changed after we unify objects and activities
+ refute Activity.get_by_id(activity.id)
+ assert actor == deleting_user.ap_id
+
+ # Objects are replaced by a tombstone object.
+ object = Object.normalize(activity.data["object"])
+ assert object.data["type"] == "Tombstone"
+ end
+
+ test "it fails for incoming deletes with spoofed origin" do
+ activity = insert(:note_activity)
+
+ data =
+ File.read!("test/fixtures/mastodon-delete.json")
+ |> Poison.decode!()
+
+ object =
+ data["object"]
+ |> Map.put("id", activity.data["object"])
+
+ data =
+ data
+ |> Map.put("object", object)
+
+ assert capture_log(fn ->
+ :error = Transmogrifier.handle_incoming(data)
+ end) =~
+ "[error] Could not decode user at fetch http://mastodon.example.org/users/gargron, {:error, :nxdomain}"
+
+ assert Activity.get_by_id(activity.id)
+ end
+
+ @tag capture_log: true
+ test "it works for incoming user deletes" do
+ %{ap_id: ap_id} = insert(:user, ap_id: "http://mastodon.example.org/users/admin")
+
+ data =
+ File.read!("test/fixtures/mastodon-delete-user.json")
+ |> Poison.decode!()
+
+ {:ok, _} = Transmogrifier.handle_incoming(data)
+ ObanHelpers.perform_all()
+
+ refute User.get_cached_by_ap_id(ap_id)
+ end
+
+ test "it fails for incoming user deletes with spoofed origin" do
+ %{ap_id: ap_id} = insert(:user)
+
+ data =
+ File.read!("test/fixtures/mastodon-delete-user.json")
+ |> Poison.decode!()
+ |> Map.put("actor", ap_id)
+
+ assert capture_log(fn ->
+ assert :error == Transmogrifier.handle_incoming(data)
+ end) =~ "Object containment failed"
+
+ assert User.get_cached_by_ap_id(ap_id)
+ end
+end
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 6057e360a..64e56d378 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -822,83 +822,6 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert user.locked == true
end
- test "it works for incoming deletes" do
- activity = insert(:note_activity)
- deleting_user = insert(:user)
-
- data =
- File.read!("test/fixtures/mastodon-delete.json")
- |> Poison.decode!()
-
- object =
- data["object"]
- |> Map.put("id", activity.data["object"])
-
- data =
- data
- |> Map.put("object", object)
- |> Map.put("actor", deleting_user.ap_id)
-
- {:ok, %Activity{actor: actor, local: false, data: %{"id" => id}}} =
- Transmogrifier.handle_incoming(data)
-
- assert id == data["id"]
- refute Activity.get_by_id(activity.id)
- assert actor == deleting_user.ap_id
- end
-
- test "it fails for incoming deletes with spoofed origin" do
- activity = insert(:note_activity)
-
- data =
- File.read!("test/fixtures/mastodon-delete.json")
- |> Poison.decode!()
-
- object =
- data["object"]
- |> Map.put("id", activity.data["object"])
-
- data =
- data
- |> Map.put("object", object)
-
- assert capture_log(fn ->
- :error = Transmogrifier.handle_incoming(data)
- end) =~
- "[error] Could not decode user at fetch http://mastodon.example.org/users/gargron, {:error, :nxdomain}"
-
- assert Activity.get_by_id(activity.id)
- end
-
- @tag capture_log: true
- test "it works for incoming user deletes" do
- %{ap_id: ap_id} = insert(:user, ap_id: "http://mastodon.example.org/users/admin")
-
- data =
- File.read!("test/fixtures/mastodon-delete-user.json")
- |> Poison.decode!()
-
- {:ok, _} = Transmogrifier.handle_incoming(data)
- ObanHelpers.perform_all()
-
- refute User.get_cached_by_ap_id(ap_id)
- end
-
- test "it fails for incoming user deletes with spoofed origin" do
- %{ap_id: ap_id} = insert(:user)
-
- data =
- File.read!("test/fixtures/mastodon-delete-user.json")
- |> Poison.decode!()
- |> Map.put("actor", ap_id)
-
- assert capture_log(fn ->
- assert :error == Transmogrifier.handle_incoming(data)
- end) =~ "Object containment failed"
-
- assert User.get_cached_by_ap_id(ap_id)
- end
-
test "it works for incoming unannounces with an existing notice" do
user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
--
cgit v1.2.3
From 5839e67eb86d6d14b21222247ce8e113c3b26637 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Thu, 6 Feb 2020 18:01:12 +0300
Subject: return data only for updated emoji
---
test/instance_static/add/shortcode.png | Bin 0 -> 95 bytes
.../controllers/emoji_api_controller_test.exs | 162 ++++++++++++---------
2 files changed, 91 insertions(+), 71 deletions(-)
create mode 100644 test/instance_static/add/shortcode.png
(limited to 'test')
diff --git a/test/instance_static/add/shortcode.png b/test/instance_static/add/shortcode.png
new file mode 100644
index 000000000..8f50fa023
Binary files /dev/null and b/test/instance_static/add/shortcode.png differ
diff --git a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
index 4246eb400..6844601d7 100644
--- a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
@@ -295,96 +295,116 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end
end
- test "updating pack files" do
- pack_file = "#{@emoji_dir_path}/test_pack/pack.json"
- original_content = File.read!(pack_file)
+ describe "update_file/2" do
+ setup do
+ pack_file = "#{@emoji_dir_path}/test_pack/pack.json"
+ original_content = File.read!(pack_file)
- on_exit(fn ->
- File.write!(pack_file, original_content)
+ on_exit(fn ->
+ File.write!(pack_file, original_content)
+ end)
- File.rm_rf!("#{@emoji_dir_path}/test_pack/blank_url.png")
- File.rm_rf!("#{@emoji_dir_path}/test_pack/dir")
- File.rm_rf!("#{@emoji_dir_path}/test_pack/dir_2")
- end)
+ admin = insert(:user, is_admin: true)
+ %{conn: conn} = oauth_access(["admin:write"], user: admin)
+ {:ok, conn: conn}
+ end
- admin = insert(:user, is_admin: true)
- %{conn: conn} = oauth_access(["admin:write"], user: admin)
+ test "update file without shortcode", %{conn: conn} do
+ on_exit(fn -> File.rm_rf!("#{@emoji_dir_path}/test_pack/shortcode.png") end)
+
+ assert conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "add",
+ "file" => %Plug.Upload{
+ filename: "shortcode.png",
+ path: "#{Pleroma.Config.get([:instance, :static_dir])}/add/shortcode.png"
+ }
+ })
+ |> json_response(200) == %{"shortcode" => "shortcode.png"}
+ end
+
+ test "updating pack files", %{conn: conn} do
+ on_exit(fn ->
+ File.rm_rf!("#{@emoji_dir_path}/test_pack/blank_url.png")
+ File.rm_rf!("#{@emoji_dir_path}/test_pack/dir")
+ File.rm_rf!("#{@emoji_dir_path}/test_pack/dir_2")
+ end)
- same_name = %{
- "action" => "add",
- "shortcode" => "blank",
- "filename" => "dir/blank.png",
- "file" => %Plug.Upload{
- filename: "blank.png",
- path: "#{@emoji_dir_path}/test_pack/blank.png"
+ same_name = %{
+ "action" => "add",
+ "shortcode" => "blank",
+ "filename" => "dir/blank.png",
+ "file" => %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_dir_path}/test_pack/blank.png"
+ }
}
- }
- different_name = %{same_name | "shortcode" => "blank_2"}
+ different_name = %{same_name | "shortcode" => "blank_2"}
- assert (conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), same_name)
- |> json_response(:conflict))["error"] =~ "already exists"
+ assert (conn
+ |> post(emoji_api_path(conn, :update_file, "test_pack"), same_name)
+ |> json_response(:conflict))["error"] =~ "already exists"
- assert conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), different_name)
- |> json_response(200) == %{"blank" => "blank.png", "blank_2" => "dir/blank.png"}
+ assert conn
+ |> post(emoji_api_path(conn, :update_file, "test_pack"), different_name)
+ |> json_response(200) == %{"blank_2" => "dir/blank.png"}
- assert File.exists?("#{@emoji_dir_path}/test_pack/dir/blank.png")
+ assert File.exists?("#{@emoji_dir_path}/test_pack/dir/blank.png")
- assert conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), %{
- "action" => "update",
- "shortcode" => "blank_2",
- "new_shortcode" => "blank_3",
- "new_filename" => "dir_2/blank_3.png"
- })
- |> json_response(200) == %{"blank" => "blank.png", "blank_3" => "dir_2/blank_3.png"}
+ assert conn
+ |> post(emoji_api_path(conn, :update_file, "test_pack"), %{
+ "action" => "update",
+ "shortcode" => "blank_2",
+ "new_shortcode" => "blank_3",
+ "new_filename" => "dir_2/blank_3.png"
+ })
+ |> json_response(200) == %{"blank_3" => "dir_2/blank_3.png"}
- refute File.exists?("#{@emoji_dir_path}/test_pack/dir/")
- assert File.exists?("#{@emoji_dir_path}/test_pack/dir_2/blank_3.png")
+ refute File.exists?("#{@emoji_dir_path}/test_pack/dir/")
+ assert File.exists?("#{@emoji_dir_path}/test_pack/dir_2/blank_3.png")
- assert conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), %{
- "action" => "remove",
- "shortcode" => "blank_3"
- })
- |> json_response(200) == %{"blank" => "blank.png"}
+ assert conn
+ |> post(emoji_api_path(conn, :update_file, "test_pack"), %{
+ "action" => "remove",
+ "shortcode" => "blank_3"
+ })
+ |> json_response(200) == %{"blank_3" => "dir_2/blank_3.png"}
- refute File.exists?("#{@emoji_dir_path}/test_pack/dir_2/")
+ refute File.exists?("#{@emoji_dir_path}/test_pack/dir_2/")
- mock(fn
- %{
- method: :get,
- url: "https://test-blank/blank_url.png"
- } ->
- text(File.read!("#{@emoji_dir_path}/test_pack/blank.png"))
- end)
+ mock(fn
+ %{
+ method: :get,
+ url: "https://test-blank/blank_url.png"
+ } ->
+ text(File.read!("#{@emoji_dir_path}/test_pack/blank.png"))
+ end)
- # The name should be inferred from the URL ending
- from_url = %{
- "action" => "add",
- "shortcode" => "blank_url",
- "file" => "https://test-blank/blank_url.png"
- }
+ # The name should be inferred from the URL ending
+ from_url = %{
+ "action" => "add",
+ "shortcode" => "blank_url",
+ "file" => "https://test-blank/blank_url.png"
+ }
- assert conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), from_url)
- |> json_response(200) == %{
- "blank" => "blank.png",
- "blank_url" => "blank_url.png"
- }
+ assert conn
+ |> post(emoji_api_path(conn, :update_file, "test_pack"), from_url)
+ |> json_response(200) == %{
+ "blank_url" => "blank_url.png"
+ }
- assert File.exists?("#{@emoji_dir_path}/test_pack/blank_url.png")
+ assert File.exists?("#{@emoji_dir_path}/test_pack/blank_url.png")
- assert conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), %{
- "action" => "remove",
- "shortcode" => "blank_url"
- })
- |> json_response(200) == %{"blank" => "blank.png"}
+ assert conn
+ |> post(emoji_api_path(conn, :update_file, "test_pack"), %{
+ "action" => "remove",
+ "shortcode" => "blank_url"
+ })
+ |> json_response(200) == %{"blank_url" => "blank_url.png"}
- refute File.exists?("#{@emoji_dir_path}/test_pack/blank_url.png")
+ refute File.exists?("#{@emoji_dir_path}/test_pack/blank_url.png")
+ end
end
test "creating and deleting a pack" do
--
cgit v1.2.3
From db184a8eb495865334f47a24f8c5b1fec65450b6 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 14:37:14 +0200
Subject: DeleteValidator: Mastodon sends unaddressed deletes.
---
test/web/activity_pub/object_validator_test.exs | 14 --------------
1 file changed, 14 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 64b9ee1ec..ab26d3501 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -59,20 +59,6 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
assert {:actor, {"is not allowed to delete object", []}} in cng.errors
end
-
- test "it's invalid if all the recipient fields are empty", %{
- valid_post_delete: valid_post_delete
- } do
- empty_recipients =
- valid_post_delete
- |> Map.put("to", [])
- |> Map.put("cc", [])
-
- {:error, cng} = ObjectValidator.validate(empty_recipients, [])
-
- assert {:to, {"no recipients in any field", []}} in cng.errors
- assert {:cc, {"no recipients in any field", []}} in cng.errors
- end
end
describe "likes" do
--
cgit v1.2.3
From 342f55fb92c723acf7f53de2dae390b72051c94b Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Sat, 28 Mar 2020 13:34:32 +0300
Subject: refactor emoji api with fixes
---
test/instance_static/emoji/pack_bad_sha/blank.png | Bin 0 -> 95 bytes
test/instance_static/emoji/pack_bad_sha/pack.json | 13 +
.../emoji/pack_bad_sha/pack_bad_sha.zip | Bin 0 -> 256 bytes
test/instance_static/emoji/test_pack/pack.json | 14 +-
.../emoji/test_pack_nonshared/pack.json | 5 +-
.../controllers/emoji_api_controller_test.exs | 866 ++++++++++++++-------
6 files changed, 608 insertions(+), 290 deletions(-)
create mode 100644 test/instance_static/emoji/pack_bad_sha/blank.png
create mode 100644 test/instance_static/emoji/pack_bad_sha/pack.json
create mode 100644 test/instance_static/emoji/pack_bad_sha/pack_bad_sha.zip
(limited to 'test')
diff --git a/test/instance_static/emoji/pack_bad_sha/blank.png b/test/instance_static/emoji/pack_bad_sha/blank.png
new file mode 100644
index 000000000..8f50fa023
Binary files /dev/null and b/test/instance_static/emoji/pack_bad_sha/blank.png differ
diff --git a/test/instance_static/emoji/pack_bad_sha/pack.json b/test/instance_static/emoji/pack_bad_sha/pack.json
new file mode 100644
index 000000000..35caf4298
--- /dev/null
+++ b/test/instance_static/emoji/pack_bad_sha/pack.json
@@ -0,0 +1,13 @@
+{
+ "pack": {
+ "license": "Test license",
+ "homepage": "https://pleroma.social",
+ "description": "Test description",
+ "can-download": true,
+ "share-files": true,
+ "download-sha256": "57482F30674FD3DE821FF48C81C00DA4D4AF1F300209253684ABA7075E5FC238"
+ },
+ "files": {
+ "blank": "blank.png"
+ }
+}
\ No newline at end of file
diff --git a/test/instance_static/emoji/pack_bad_sha/pack_bad_sha.zip b/test/instance_static/emoji/pack_bad_sha/pack_bad_sha.zip
new file mode 100644
index 000000000..148446c64
Binary files /dev/null and b/test/instance_static/emoji/pack_bad_sha/pack_bad_sha.zip differ
diff --git a/test/instance_static/emoji/test_pack/pack.json b/test/instance_static/emoji/test_pack/pack.json
index 5a8ee75f9..481891b08 100644
--- a/test/instance_static/emoji/test_pack/pack.json
+++ b/test/instance_static/emoji/test_pack/pack.json
@@ -1,13 +1,11 @@
{
+ "files": {
+ "blank": "blank.png"
+ },
"pack": {
- "license": "Test license",
- "homepage": "https://pleroma.social",
"description": "Test description",
-
+ "homepage": "https://pleroma.social",
+ "license": "Test license",
"share-files": true
- },
-
- "files": {
- "blank": "blank.png"
}
-}
+}
\ No newline at end of file
diff --git a/test/instance_static/emoji/test_pack_nonshared/pack.json b/test/instance_static/emoji/test_pack_nonshared/pack.json
index b96781f81..93d643a5f 100644
--- a/test/instance_static/emoji/test_pack_nonshared/pack.json
+++ b/test/instance_static/emoji/test_pack_nonshared/pack.json
@@ -3,14 +3,11 @@
"license": "Test license",
"homepage": "https://pleroma.social",
"description": "Test description",
-
"fallback-src": "https://nonshared-pack",
"fallback-src-sha256": "74409E2674DAA06C072729C6C8426C4CB3B7E0B85ED77792DB7A436E11D76DAF",
-
"share-files": false
},
-
"files": {
"blank": "blank.png"
}
-}
+}
\ No newline at end of file
diff --git a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
index 6844601d7..6a0d7dd11 100644
--- a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
@@ -8,212 +8,309 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
import Tesla.Mock
import Pleroma.Factory
- @emoji_dir_path Path.join(
- Pleroma.Config.get!([:instance, :static_dir]),
- "emoji"
- )
+ @emoji_path Path.join(
+ Pleroma.Config.get!([:instance, :static_dir]),
+ "emoji"
+ )
setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false)
- test "shared & non-shared pack information in list_packs is ok" do
- conn = build_conn()
- resp = conn |> get(emoji_api_path(conn, :list_packs)) |> json_response(200)
-
- assert Map.has_key?(resp, "test_pack")
+ setup do
+ admin = insert(:user, is_admin: true)
+ token = insert(:oauth_admin_token, user: admin)
- pack = resp["test_pack"]
+ admin_conn =
+ build_conn()
+ |> assign(:user, admin)
+ |> assign(:token, token)
- assert Map.has_key?(pack["pack"], "download-sha256")
- assert pack["pack"]["can-download"]
+ Pleroma.Emoji.reload()
+ {:ok, %{admin_conn: admin_conn}}
+ end
- assert pack["files"] == %{"blank" => "blank.png"}
+ test "GET /api/pleroma/emoji/packs", %{conn: conn} do
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response(200)
- # Non-shared pack
+ shared = resp["test_pack"]
+ assert shared["files"] == %{"blank" => "blank.png"}
+ assert Map.has_key?(shared["pack"], "download-sha256")
+ assert shared["pack"]["can-download"]
+ assert shared["pack"]["share-files"]
- assert Map.has_key?(resp, "test_pack_nonshared")
+ non_shared = resp["test_pack_nonshared"]
+ assert non_shared["pack"]["share-files"] == false
+ assert non_shared["pack"]["can-download"] == false
+ end
- pack = resp["test_pack_nonshared"]
+ describe "POST /api/pleroma/emoji/packs/list_from" do
+ test "shareable instance", %{admin_conn: admin_conn, conn: conn} do
+ resp =
+ conn
+ |> get("/api/pleroma/emoji/packs")
+ |> json_response(200)
- refute pack["pack"]["shared"]
- refute pack["pack"]["can-download"]
- end
+ mock(fn
+ %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
- test "listing remote packs" do
- conn = build_conn()
+ %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: ["shareable_emoji_packs"]}})
- resp =
- build_conn()
- |> get(emoji_api_path(conn, :list_packs))
- |> json_response(200)
+ %{method: :get, url: "https://example.com/api/pleroma/emoji/packs"} ->
+ json(resp)
+ end)
- mock(fn
- %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
- json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/list_from", %{
+ instance_address: "https://example.com"
+ })
+ |> json_response(200) == resp
+ end
- %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
- json(%{metadata: %{features: ["shareable_emoji_packs"]}})
+ test "non shareable instance", %{admin_conn: admin_conn} do
+ mock(fn
+ %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
- %{method: :get, url: "https://example.com/api/pleroma/emoji/packs"} ->
- json(resp)
- end)
+ %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: []}})
+ end)
- assert conn
- |> post(emoji_api_path(conn, :list_from), %{instance_address: "https://example.com"})
- |> json_response(200) == resp
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/list_from", %{
+ instance_address: "https://example.com"
+ })
+ |> json_response(500) == %{
+ "error" => "The requested instance does not support sharing emoji packs"
+ }
+ end
end
- test "downloading a shared pack from download_shared" do
- conn = build_conn()
+ describe "GET /api/pleroma/emoji/packs/:name/download_shared" do
+ test "download shared pack", %{conn: conn} do
+ resp =
+ conn
+ |> get("/api/pleroma/emoji/packs/test_pack/download_shared")
+ |> response(200)
- resp =
- conn
- |> get(emoji_api_path(conn, :download_shared, "test_pack"))
- |> response(200)
+ {:ok, arch} = :zip.unzip(resp, [:memory])
+
+ assert Enum.find(arch, fn {n, _} -> n == 'pack.json' end)
+ assert Enum.find(arch, fn {n, _} -> n == 'blank.png' end)
+ end
- {:ok, arch} = :zip.unzip(resp, [:memory])
+ test "non existing pack", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/emoji/packs/test_pack_for_import/download_shared")
+ |> json_response(:not_found) == %{
+ "error" => "Pack test_pack_for_import does not exist"
+ }
+ end
- assert Enum.find(arch, fn {n, _} -> n == 'pack.json' end)
- assert Enum.find(arch, fn {n, _} -> n == 'blank.png' end)
+ test "non downloadable pack", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/emoji/packs/test_pack_nonshared/download_shared")
+ |> json_response(:forbidden) == %{
+ "error" =>
+ "Pack test_pack_nonshared cannot be downloaded from this instance, either pack sharing was disabled for this pack or some files are missing"
+ }
+ end
end
- test "downloading shared & unshared packs from another instance, deleting them" do
- on_exit(fn ->
- File.rm_rf!("#{@emoji_dir_path}/test_pack2")
- File.rm_rf!("#{@emoji_dir_path}/test_pack_nonshared2")
- end)
+ describe "POST /api/pleroma/emoji/packs/download_from" do
+ test "shared pack from remote and non shared from fallback-src", %{
+ admin_conn: admin_conn,
+ conn: conn
+ } do
+ mock(fn
+ %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
- mock(fn
- %{method: :get, url: "https://old-instance/.well-known/nodeinfo"} ->
- json(%{links: [%{href: "https://old-instance/nodeinfo/2.1.json"}]})
+ %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: ["shareable_emoji_packs"]}})
- %{method: :get, url: "https://old-instance/nodeinfo/2.1.json"} ->
- json(%{metadata: %{features: []}})
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/test_pack"
+ } ->
+ conn
+ |> get("/api/pleroma/emoji/packs/test_pack")
+ |> json_response(200)
+ |> json()
- %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
- json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/test_pack/download_shared"
+ } ->
+ conn
+ |> get("/api/pleroma/emoji/packs/test_pack/download_shared")
+ |> response(200)
+ |> text()
- %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
- json(%{metadata: %{features: ["shareable_emoji_packs"]}})
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/test_pack_nonshared"
+ } ->
+ conn
+ |> get("/api/pleroma/emoji/packs/test_pack_nonshared")
+ |> json_response(200)
+ |> json()
- %{
- method: :get,
- url: "https://example.com/api/pleroma/emoji/packs/list"
- } ->
- conn = build_conn()
+ %{
+ method: :get,
+ url: "https://nonshared-pack"
+ } ->
+ text(File.read!("#{@emoji_path}/test_pack_nonshared/nonshared.zip"))
+ end)
- conn
- |> get(emoji_api_path(conn, :list_packs))
- |> json_response(200)
- |> json()
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/download_from", %{
+ instance_address: "https://example.com",
+ pack_name: "test_pack",
+ as: "test_pack2"
+ })
+ |> json_response(200) == "ok"
- %{
- method: :get,
- url: "https://example.com/api/pleroma/emoji/packs/download_shared/test_pack"
- } ->
- conn = build_conn()
+ assert File.exists?("#{@emoji_path}/test_pack2/pack.json")
+ assert File.exists?("#{@emoji_path}/test_pack2/blank.png")
- conn
- |> get(emoji_api_path(conn, :download_shared, "test_pack"))
- |> response(200)
- |> text()
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/test_pack2")
+ |> json_response(200) == "ok"
- %{
- method: :get,
- url: "https://nonshared-pack"
- } ->
- text(File.read!("#{@emoji_dir_path}/test_pack_nonshared/nonshared.zip"))
- end)
+ refute File.exists?("#{@emoji_path}/test_pack2")
- admin = insert(:user, is_admin: true)
+ assert admin_conn
+ |> post(
+ "/api/pleroma/emoji/packs/download_from",
+ %{
+ instance_address: "https://example.com",
+ pack_name: "test_pack_nonshared",
+ as: "test_pack_nonshared2"
+ }
+ )
+ |> json_response(200) == "ok"
- conn =
- build_conn()
- |> assign(:user, admin)
- |> assign(:token, insert(:oauth_admin_token, user: admin, scopes: ["admin:write"]))
-
- assert (conn
- |> put_req_header("content-type", "application/json")
- |> post(
- emoji_api_path(
- conn,
- :save_from
- ),
- %{
- instance_address: "https://old-instance",
- pack_name: "test_pack",
- as: "test_pack2"
- }
- |> Jason.encode!()
- )
- |> json_response(500))["error"] =~ "does not support"
-
- assert conn
- |> put_req_header("content-type", "application/json")
- |> post(
- emoji_api_path(
- conn,
- :save_from
- ),
- %{
- instance_address: "https://example.com",
- pack_name: "test_pack",
- as: "test_pack2"
+ assert File.exists?("#{@emoji_path}/test_pack_nonshared2/pack.json")
+ assert File.exists?("#{@emoji_path}/test_pack_nonshared2/blank.png")
+
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/test_pack_nonshared2")
+ |> json_response(200) == "ok"
+
+ refute File.exists?("#{@emoji_path}/test_pack_nonshared2")
+ end
+
+ test "nonshareable instance", %{admin_conn: admin_conn} do
+ mock(fn
+ %{method: :get, url: "https://old-instance/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://old-instance/nodeinfo/2.1.json"}]})
+
+ %{method: :get, url: "https://old-instance/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: []}})
+ end)
+
+ assert admin_conn
+ |> post(
+ "/api/pleroma/emoji/packs/download_from",
+ %{
+ instance_address: "https://old-instance",
+ pack_name: "test_pack",
+ as: "test_pack2"
+ }
+ )
+ |> json_response(500) == %{
+ "error" => "The requested instance does not support sharing emoji packs"
}
- |> Jason.encode!()
- )
- |> json_response(200) == "ok"
+ end
- assert File.exists?("#{@emoji_dir_path}/test_pack2/pack.json")
- assert File.exists?("#{@emoji_dir_path}/test_pack2/blank.png")
+ test "checksum fail", %{admin_conn: admin_conn} do
+ mock(fn
+ %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
- assert conn
- |> delete(emoji_api_path(conn, :delete, "test_pack2"))
- |> json_response(200) == "ok"
+ %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: ["shareable_emoji_packs"]}})
- refute File.exists?("#{@emoji_dir_path}/test_pack2")
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/pack_bad_sha"
+ } ->
+ %Tesla.Env{
+ status: 200,
+ body: Pleroma.Emoji.Pack.load_pack("pack_bad_sha") |> Jason.encode!()
+ }
- # non-shared, downloaded from the fallback URL
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/pack_bad_sha/download_shared"
+ } ->
+ %Tesla.Env{
+ status: 200,
+ body: File.read!("test/instance_static/emoji/pack_bad_sha/pack_bad_sha.zip")
+ }
+ end)
- assert conn
- |> put_req_header("content-type", "application/json")
- |> post(
- emoji_api_path(
- conn,
- :save_from
- ),
- %{
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/download_from", %{
instance_address: "https://example.com",
- pack_name: "test_pack_nonshared",
- as: "test_pack_nonshared2"
+ pack_name: "pack_bad_sha",
+ as: "pack_bad_sha2"
+ })
+ |> json_response(:internal_server_error) == %{
+ "error" => "SHA256 for the pack doesn't match the one sent by the server"
}
- |> Jason.encode!()
- )
- |> json_response(200) == "ok"
+ end
+
+ test "other error", %{admin_conn: admin_conn} do
+ mock(fn
+ %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
+
+ %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: ["shareable_emoji_packs"]}})
- assert File.exists?("#{@emoji_dir_path}/test_pack_nonshared2/pack.json")
- assert File.exists?("#{@emoji_dir_path}/test_pack_nonshared2/blank.png")
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/test_pack"
+ } ->
+ %Tesla.Env{
+ status: 200,
+ body: %{"test_pack" => Pleroma.Emoji.Pack.load_pack("test_pack")} |> Jason.encode!()
+ }
- assert conn
- |> delete(emoji_api_path(conn, :delete, "test_pack_nonshared2"))
- |> json_response(200) == "ok"
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/test_pack/download_shared"
+ } ->
+ %Tesla.Env{
+ status: 200,
+ body: File.read!("test/instance_static/emoji/test_pack/pack.json")
+ }
+ end)
- refute File.exists?("#{@emoji_dir_path}/test_pack_nonshared2")
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/download_from", %{
+ instance_address: "https://example.com",
+ pack_name: "test_pack",
+ as: "test_pack2"
+ })
+ |> json_response(:internal_server_error) == %{
+ "error" =>
+ "The pack was not set as shared and there is no fallback src to download from"
+ }
+ end
end
describe "updating pack metadata" do
setup do
- pack_file = "#{@emoji_dir_path}/test_pack/pack.json"
+ pack_file = "#{@emoji_path}/test_pack/pack.json"
original_content = File.read!(pack_file)
on_exit(fn ->
File.write!(pack_file, original_content)
end)
- admin = insert(:user, is_admin: true)
- %{conn: conn} = oauth_access(["admin:write"], user: admin)
-
{:ok,
- admin: admin,
- conn: conn,
pack_file: pack_file,
new_data: %{
"license" => "Test license changed",
@@ -224,11 +321,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end
test "for a pack without a fallback source", ctx do
- conn = ctx[:conn]
-
- assert conn
+ assert ctx[:admin_conn]
|> post(
- emoji_api_path(conn, :update_metadata, "test_pack"),
+ "/api/pleroma/emoji/packs/test_pack/update_metadata",
%{
"new_data" => ctx[:new_data]
}
@@ -244,7 +339,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
method: :get,
url: "https://nonshared-pack"
} ->
- text(File.read!("#{@emoji_dir_path}/test_pack_nonshared/nonshared.zip"))
+ text(File.read!("#{@emoji_path}/test_pack_nonshared/nonshared.zip"))
end)
new_data = Map.put(ctx[:new_data], "fallback-src", "https://nonshared-pack")
@@ -256,11 +351,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
"74409E2674DAA06C072729C6C8426C4CB3B7E0B85ED77792DB7A436E11D76DAF"
)
- conn = ctx[:conn]
-
- assert conn
+ assert ctx[:admin_conn]
|> post(
- emoji_api_path(conn, :update_metadata, "test_pack"),
+ "/api/pleroma/emoji/packs/test_pack/update_metadata",
%{
"new_data" => new_data
}
@@ -282,201 +375,418 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
new_data = Map.put(ctx[:new_data], "fallback-src", "https://nonshared-pack")
- conn = ctx[:conn]
-
- assert (conn
- |> post(
- emoji_api_path(conn, :update_metadata, "test_pack"),
- %{
- "new_data" => new_data
- }
- )
- |> json_response(:bad_request))["error"] =~ "does not have all"
+ assert ctx[:admin_conn]
+ |> post(
+ "/api/pleroma/emoji/packs/test_pack/update_metadata",
+ %{
+ "new_data" => new_data
+ }
+ )
+ |> json_response(:bad_request) == %{
+ "error" => "The fallback archive does not have all files specified in pack.json"
+ }
end
end
- describe "update_file/2" do
+ describe "POST /api/pleroma/emoji/packs/:pack_name/update_file" do
setup do
- pack_file = "#{@emoji_dir_path}/test_pack/pack.json"
+ pack_file = "#{@emoji_path}/test_pack/pack.json"
original_content = File.read!(pack_file)
on_exit(fn ->
File.write!(pack_file, original_content)
end)
- admin = insert(:user, is_admin: true)
- %{conn: conn} = oauth_access(["admin:write"], user: admin)
- {:ok, conn: conn}
+ :ok
+ end
+
+ test "create shortcode exists", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "add",
+ "shortcode" => "blank",
+ "filename" => "dir/blank.png",
+ "file" => %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
+ }
+ })
+ |> json_response(:conflict) == %{
+ "error" => "An emoji with the \"blank\" shortcode already exists"
+ }
end
- test "update file without shortcode", %{conn: conn} do
- on_exit(fn -> File.rm_rf!("#{@emoji_dir_path}/test_pack/shortcode.png") end)
+ test "don't rewrite old emoji", %{admin_conn: admin_conn} do
+ on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir/") end)
- assert conn
+ assert admin_conn
|> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
"action" => "add",
+ "shortcode" => "blank2",
+ "filename" => "dir/blank.png",
"file" => %Plug.Upload{
- filename: "shortcode.png",
- path: "#{Pleroma.Config.get([:instance, :static_dir])}/add/shortcode.png"
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
}
})
- |> json_response(200) == %{"shortcode" => "shortcode.png"}
+ |> json_response(200) == %{"blank" => "blank.png", "blank2" => "dir/blank.png"}
+
+ assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
+
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "update",
+ "shortcode" => "blank",
+ "new_shortcode" => "blank2",
+ "new_filename" => "dir_2/blank_3.png"
+ })
+ |> json_response(:conflict) == %{
+ "error" =>
+ "New shortcode \"blank2\" is already used. If you want to override emoji use 'force' option"
+ }
end
- test "updating pack files", %{conn: conn} do
- on_exit(fn ->
- File.rm_rf!("#{@emoji_dir_path}/test_pack/blank_url.png")
- File.rm_rf!("#{@emoji_dir_path}/test_pack/dir")
- File.rm_rf!("#{@emoji_dir_path}/test_pack/dir_2")
- end)
+ test "rewrite old emoji with force option", %{admin_conn: admin_conn} do
+ on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir_2/") end)
- same_name = %{
- "action" => "add",
- "shortcode" => "blank",
- "filename" => "dir/blank.png",
- "file" => %Plug.Upload{
- filename: "blank.png",
- path: "#{@emoji_dir_path}/test_pack/blank.png"
- }
- }
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "add",
+ "shortcode" => "blank2",
+ "filename" => "dir/blank.png",
+ "file" => %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
+ }
+ })
+ |> json_response(200) == %{"blank" => "blank.png", "blank2" => "dir/blank.png"}
- different_name = %{same_name | "shortcode" => "blank_2"}
+ assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
- assert (conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), same_name)
- |> json_response(:conflict))["error"] =~ "already exists"
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "update",
+ "shortcode" => "blank2",
+ "new_shortcode" => "blank3",
+ "new_filename" => "dir_2/blank_3.png",
+ "force" => true
+ })
+ |> json_response(200) == %{
+ "blank" => "blank.png",
+ "blank3" => "dir_2/blank_3.png"
+ }
- assert conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), different_name)
- |> json_response(200) == %{"blank_2" => "dir/blank.png"}
+ assert File.exists?("#{@emoji_path}/test_pack/dir_2/blank_3.png")
+ end
- assert File.exists?("#{@emoji_dir_path}/test_pack/dir/blank.png")
+ test "with empty filename", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "add",
+ "shortcode" => "blank2",
+ "filename" => "",
+ "file" => %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
+ }
+ })
+ |> json_response(:bad_request) == %{
+ "error" => "pack name, shortcode or filename cannot be empty"
+ }
+ end
- assert conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), %{
+ test "add file with not loaded pack", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/not_loaded/update_file", %{
+ "action" => "add",
+ "shortcode" => "blank2",
+ "filename" => "dir/blank.png",
+ "file" => %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
+ }
+ })
+ |> json_response(:bad_request) == %{
+ "error" => "pack \"not_loaded\" is not found"
+ }
+ end
+
+ test "remove file with not loaded pack", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/not_loaded/update_file", %{
+ "action" => "remove",
+ "shortcode" => "blank3"
+ })
+ |> json_response(:bad_request) == %{"error" => "pack \"not_loaded\" is not found"}
+ end
+
+ test "remove file with empty shortcode", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/not_loaded/update_file", %{
+ "action" => "remove",
+ "shortcode" => ""
+ })
+ |> json_response(:bad_request) == %{
+ "error" => "pack name or shortcode cannot be empty"
+ }
+ end
+
+ test "update file with not loaded pack", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/not_loaded/update_file", %{
+ "action" => "update",
+ "shortcode" => "blank4",
+ "new_shortcode" => "blank3",
+ "new_filename" => "dir_2/blank_3.png"
+ })
+ |> json_response(:bad_request) == %{"error" => "pack \"not_loaded\" is not found"}
+ end
+
+ test "new with shortcode as file with update", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "add",
+ "shortcode" => "blank4",
+ "filename" => "dir/blank.png",
+ "file" => %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
+ }
+ })
+ |> json_response(200) == %{"blank" => "blank.png", "blank4" => "dir/blank.png"}
+
+ assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
+
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
"action" => "update",
- "shortcode" => "blank_2",
- "new_shortcode" => "blank_3",
+ "shortcode" => "blank4",
+ "new_shortcode" => "blank3",
"new_filename" => "dir_2/blank_3.png"
})
- |> json_response(200) == %{"blank_3" => "dir_2/blank_3.png"}
+ |> json_response(200) == %{"blank3" => "dir_2/blank_3.png", "blank" => "blank.png"}
- refute File.exists?("#{@emoji_dir_path}/test_pack/dir/")
- assert File.exists?("#{@emoji_dir_path}/test_pack/dir_2/blank_3.png")
+ refute File.exists?("#{@emoji_path}/test_pack/dir/")
+ assert File.exists?("#{@emoji_path}/test_pack/dir_2/blank_3.png")
- assert conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), %{
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
"action" => "remove",
- "shortcode" => "blank_3"
+ "shortcode" => "blank3"
})
- |> json_response(200) == %{"blank_3" => "dir_2/blank_3.png"}
+ |> json_response(200) == %{"blank" => "blank.png"}
+
+ refute File.exists?("#{@emoji_path}/test_pack/dir_2/")
- refute File.exists?("#{@emoji_dir_path}/test_pack/dir_2/")
+ on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir") end)
+ end
+ test "new with shortcode from url", %{admin_conn: admin_conn} do
mock(fn
%{
method: :get,
url: "https://test-blank/blank_url.png"
} ->
- text(File.read!("#{@emoji_dir_path}/test_pack/blank.png"))
+ text(File.read!("#{@emoji_path}/test_pack/blank.png"))
end)
- # The name should be inferred from the URL ending
- from_url = %{
- "action" => "add",
- "shortcode" => "blank_url",
- "file" => "https://test-blank/blank_url.png"
- }
-
- assert conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), from_url)
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "add",
+ "shortcode" => "blank_url",
+ "file" => "https://test-blank/blank_url.png"
+ })
|> json_response(200) == %{
- "blank_url" => "blank_url.png"
+ "blank_url" => "blank_url.png",
+ "blank" => "blank.png"
}
- assert File.exists?("#{@emoji_dir_path}/test_pack/blank_url.png")
+ assert File.exists?("#{@emoji_path}/test_pack/blank_url.png")
- assert conn
- |> post(emoji_api_path(conn, :update_file, "test_pack"), %{
+ on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/blank_url.png") end)
+ end
+
+ test "new without shortcode", %{admin_conn: admin_conn} do
+ on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/shortcode.png") end)
+
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "add",
+ "file" => %Plug.Upload{
+ filename: "shortcode.png",
+ path: "#{Pleroma.Config.get([:instance, :static_dir])}/add/shortcode.png"
+ }
+ })
+ |> json_response(200) == %{"shortcode" => "shortcode.png", "blank" => "blank.png"}
+ end
+
+ test "remove non existing shortcode in pack.json", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
"action" => "remove",
- "shortcode" => "blank_url"
+ "shortcode" => "blank2"
+ })
+ |> json_response(:bad_request) == %{"error" => "Emoji \"blank2\" does not exist"}
+ end
+
+ test "update non existing emoji", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "update",
+ "shortcode" => "blank2",
+ "new_shortcode" => "blank3",
+ "new_filename" => "dir_2/blank_3.png"
})
- |> json_response(200) == %{"blank_url" => "blank_url.png"}
+ |> json_response(:bad_request) == %{"error" => "Emoji \"blank2\" does not exist"}
+ end
+
+ test "update with empty shortcode", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "update",
+ "shortcode" => "blank",
+ "new_filename" => "dir_2/blank_3.png"
+ })
+ |> json_response(:bad_request) == %{
+ "error" => "new_shortcode or new_filename cannot be empty"
+ }
+ end
- refute File.exists?("#{@emoji_dir_path}/test_pack/blank_url.png")
+ test "undefined action", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
+ "action" => "undefined"
+ })
+ |> json_response(:bad_request) == %{
+ "error" => "Unknown action: undefined"
+ }
end
end
- test "creating and deleting a pack" do
- on_exit(fn ->
- File.rm_rf!("#{@emoji_dir_path}/test_created")
- end)
+ describe "PUT /api/pleroma/emoji/packs/:name" do
+ test "creating and deleting a pack", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> put("/api/pleroma/emoji/packs/test_created")
+ |> json_response(200) == "ok"
- admin = insert(:user, is_admin: true)
- %{conn: conn} = oauth_access(["admin:write"], user: admin)
-
- assert conn
- |> put_req_header("content-type", "application/json")
- |> put(
- emoji_api_path(
- conn,
- :create,
- "test_created"
- )
- )
- |> json_response(200) == "ok"
+ assert File.exists?("#{@emoji_path}/test_created/pack.json")
+
+ assert Jason.decode!(File.read!("#{@emoji_path}/test_created/pack.json")) == %{
+ "pack" => %{},
+ "files" => %{}
+ }
- assert File.exists?("#{@emoji_dir_path}/test_created/pack.json")
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/test_created")
+ |> json_response(200) == "ok"
- assert Jason.decode!(File.read!("#{@emoji_dir_path}/test_created/pack.json")) == %{
- "pack" => %{},
- "files" => %{}
- }
+ refute File.exists?("#{@emoji_path}/test_created/pack.json")
+ end
+
+ test "if pack exists", %{admin_conn: admin_conn} do
+ path = Path.join(@emoji_path, "test_created")
+ File.mkdir(path)
+ pack_file = Jason.encode!(%{files: %{}, pack: %{}})
+ File.write!(Path.join(path, "pack.json"), pack_file)
+
+ assert admin_conn
+ |> put("/api/pleroma/emoji/packs/test_created")
+ |> json_response(:conflict) == %{
+ "error" => "A pack named \"test_created\" already exists"
+ }
+
+ on_exit(fn -> File.rm_rf(path) end)
+ end
- assert conn
- |> delete(emoji_api_path(conn, :delete, "test_created"))
- |> json_response(200) == "ok"
+ test "with empty name", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> put("/api/pleroma/emoji/packs/ ")
+ |> json_response(:bad_request) == %{"error" => "pack name cannot be empty"}
+ end
+ end
+
+ test "deleting nonexisting pack", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/non_existing")
+ |> json_response(:not_found) == %{"error" => "Pack non_existing does not exist"}
+ end
- refute File.exists?("#{@emoji_dir_path}/test_created/pack.json")
+ test "deleting with empty name", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/ ")
+ |> json_response(:bad_request) == %{"error" => "pack name cannot be empty"}
end
- test "filesystem import" do
+ test "filesystem import", %{admin_conn: admin_conn, conn: conn} do
on_exit(fn ->
- File.rm!("#{@emoji_dir_path}/test_pack_for_import/emoji.txt")
- File.rm!("#{@emoji_dir_path}/test_pack_for_import/pack.json")
+ File.rm!("#{@emoji_path}/test_pack_for_import/emoji.txt")
+ File.rm!("#{@emoji_path}/test_pack_for_import/pack.json")
end)
- conn = build_conn()
- resp = conn |> get(emoji_api_path(conn, :list_packs)) |> json_response(200)
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response(200)
refute Map.has_key?(resp, "test_pack_for_import")
- admin = insert(:user, is_admin: true)
- %{conn: conn} = oauth_access(["admin:write"], user: admin)
-
- assert conn
- |> post(emoji_api_path(conn, :import_from_fs))
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/import_from_fs")
|> json_response(200) == ["test_pack_for_import"]
- resp = conn |> get(emoji_api_path(conn, :list_packs)) |> json_response(200)
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response(200)
assert resp["test_pack_for_import"]["files"] == %{"blank" => "blank.png"}
- File.rm!("#{@emoji_dir_path}/test_pack_for_import/pack.json")
- refute File.exists?("#{@emoji_dir_path}/test_pack_for_import/pack.json")
+ File.rm!("#{@emoji_path}/test_pack_for_import/pack.json")
+ refute File.exists?("#{@emoji_path}/test_pack_for_import/pack.json")
- emoji_txt_content = "blank, blank.png, Fun\n\nblank2, blank.png"
+ emoji_txt_content = """
+ blank, blank.png, Fun
+ blank2, blank.png
+ foo, /emoji/test_pack_for_import/blank.png
+ bar
+ """
- File.write!("#{@emoji_dir_path}/test_pack_for_import/emoji.txt", emoji_txt_content)
+ File.write!("#{@emoji_path}/test_pack_for_import/emoji.txt", emoji_txt_content)
- assert conn
- |> post(emoji_api_path(conn, :import_from_fs))
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/import_from_fs")
|> json_response(200) == ["test_pack_for_import"]
- resp = build_conn() |> get(emoji_api_path(conn, :list_packs)) |> json_response(200)
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response(200)
assert resp["test_pack_for_import"]["files"] == %{
"blank" => "blank.png",
- "blank2" => "blank.png"
+ "blank2" => "blank.png",
+ "foo" => "blank.png"
}
end
+
+ describe "GET /api/pleroma/emoji/packs/:name" do
+ test "shows pack.json", %{conn: conn} do
+ assert %{
+ "files" => %{"blank" => "blank.png"},
+ "pack" => %{
+ "can-download" => true,
+ "description" => "Test description",
+ "download-sha256" => _,
+ "homepage" => "https://pleroma.social",
+ "license" => "Test license",
+ "share-files" => true
+ }
+ } =
+ conn
+ |> get("/api/pleroma/emoji/packs/test_pack")
+ |> json_response(200)
+ end
+
+ test "non existing pack", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/emoji/packs/non_existing")
+ |> json_response(:not_found) == %{"error" => "Pack non_existing does not exist"}
+ end
+
+ test "error name", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/emoji/packs/ ")
+ |> json_response(:bad_request) == %{"error" => "pack name cannot be empty"}
+ end
+ end
end
--
cgit v1.2.3
From ddb757f7434c7216eec1b6ba4fa8b0b7a54157c1 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Sat, 28 Mar 2020 21:15:14 +0300
Subject: emoji api packs changes in routes with docs update
---
.../controllers/emoji_api_controller_test.exs | 254 ++++++++-------------
1 file changed, 96 insertions(+), 158 deletions(-)
(limited to 'test')
diff --git a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
index 6a0d7dd11..d343256fe 100644
--- a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
@@ -41,7 +41,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
assert non_shared["pack"]["can-download"] == false
end
- describe "POST /api/pleroma/emoji/packs/list_from" do
+ describe "GET /api/pleroma/emoji/packs/remote" do
test "shareable instance", %{admin_conn: admin_conn, conn: conn} do
resp =
conn
@@ -60,8 +60,8 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
- |> post("/api/pleroma/emoji/packs/list_from", %{
- instance_address: "https://example.com"
+ |> get("/api/pleroma/emoji/packs/remote", %{
+ url: "https://example.com"
})
|> json_response(200) == resp
end
@@ -76,20 +76,18 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
- |> post("/api/pleroma/emoji/packs/list_from", %{
- instance_address: "https://example.com"
- })
+ |> get("/api/pleroma/emoji/packs/remote", %{url: "https://example.com"})
|> json_response(500) == %{
"error" => "The requested instance does not support sharing emoji packs"
}
end
end
- describe "GET /api/pleroma/emoji/packs/:name/download_shared" do
+ describe "GET /api/pleroma/emoji/packs/:name/archive" do
test "download shared pack", %{conn: conn} do
resp =
conn
- |> get("/api/pleroma/emoji/packs/test_pack/download_shared")
+ |> get("/api/pleroma/emoji/packs/test_pack/archive")
|> response(200)
{:ok, arch} = :zip.unzip(resp, [:memory])
@@ -100,7 +98,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "non existing pack", %{conn: conn} do
assert conn
- |> get("/api/pleroma/emoji/packs/test_pack_for_import/download_shared")
+ |> get("/api/pleroma/emoji/packs/test_pack_for_import/archive")
|> json_response(:not_found) == %{
"error" => "Pack test_pack_for_import does not exist"
}
@@ -108,7 +106,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "non downloadable pack", %{conn: conn} do
assert conn
- |> get("/api/pleroma/emoji/packs/test_pack_nonshared/download_shared")
+ |> get("/api/pleroma/emoji/packs/test_pack_nonshared/archive")
|> json_response(:forbidden) == %{
"error" =>
"Pack test_pack_nonshared cannot be downloaded from this instance, either pack sharing was disabled for this pack or some files are missing"
@@ -116,7 +114,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end
end
- describe "POST /api/pleroma/emoji/packs/download_from" do
+ describe "POST /api/pleroma/emoji/packs/download" do
test "shared pack from remote and non shared from fallback-src", %{
admin_conn: admin_conn,
conn: conn
@@ -139,10 +137,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
%{
method: :get,
- url: "https://example.com/api/pleroma/emoji/packs/test_pack/download_shared"
+ url: "https://example.com/api/pleroma/emoji/packs/test_pack/archive"
} ->
conn
- |> get("/api/pleroma/emoji/packs/test_pack/download_shared")
+ |> get("/api/pleroma/emoji/packs/test_pack/archive")
|> response(200)
|> text()
@@ -163,9 +161,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
- |> post("/api/pleroma/emoji/packs/download_from", %{
- instance_address: "https://example.com",
- pack_name: "test_pack",
+ |> post("/api/pleroma/emoji/packs/download", %{
+ url: "https://example.com",
+ name: "test_pack",
as: "test_pack2"
})
|> json_response(200) == "ok"
@@ -181,10 +179,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
assert admin_conn
|> post(
- "/api/pleroma/emoji/packs/download_from",
+ "/api/pleroma/emoji/packs/download",
%{
- instance_address: "https://example.com",
- pack_name: "test_pack_nonshared",
+ url: "https://example.com",
+ name: "test_pack_nonshared",
as: "test_pack_nonshared2"
}
)
@@ -211,10 +209,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
assert admin_conn
|> post(
- "/api/pleroma/emoji/packs/download_from",
+ "/api/pleroma/emoji/packs/download",
%{
- instance_address: "https://old-instance",
- pack_name: "test_pack",
+ url: "https://old-instance",
+ name: "test_pack",
as: "test_pack2"
}
)
@@ -242,7 +240,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
%{
method: :get,
- url: "https://example.com/api/pleroma/emoji/packs/pack_bad_sha/download_shared"
+ url: "https://example.com/api/pleroma/emoji/packs/pack_bad_sha/archive"
} ->
%Tesla.Env{
status: 200,
@@ -251,9 +249,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
- |> post("/api/pleroma/emoji/packs/download_from", %{
- instance_address: "https://example.com",
- pack_name: "pack_bad_sha",
+ |> post("/api/pleroma/emoji/packs/download", %{
+ url: "https://example.com",
+ name: "pack_bad_sha",
as: "pack_bad_sha2"
})
|> json_response(:internal_server_error) == %{
@@ -275,23 +273,14 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
} ->
%Tesla.Env{
status: 200,
- body: %{"test_pack" => Pleroma.Emoji.Pack.load_pack("test_pack")} |> Jason.encode!()
- }
-
- %{
- method: :get,
- url: "https://example.com/api/pleroma/emoji/packs/test_pack/download_shared"
- } ->
- %Tesla.Env{
- status: 200,
- body: File.read!("test/instance_static/emoji/test_pack/pack.json")
+ body: Pleroma.Emoji.Pack.load_pack("test_pack") |> Jason.encode!()
}
end)
assert admin_conn
- |> post("/api/pleroma/emoji/packs/download_from", %{
- instance_address: "https://example.com",
- pack_name: "test_pack",
+ |> post("/api/pleroma/emoji/packs/download", %{
+ url: "https://example.com",
+ name: "test_pack",
as: "test_pack2"
})
|> json_response(:internal_server_error) == %{
@@ -301,7 +290,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end
end
- describe "updating pack metadata" do
+ describe "PATCH /api/pleroma/emoji/packs/:name" do
setup do
pack_file = "#{@emoji_path}/test_pack/pack.json"
original_content = File.read!(pack_file)
@@ -322,12 +311,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "for a pack without a fallback source", ctx do
assert ctx[:admin_conn]
- |> post(
- "/api/pleroma/emoji/packs/test_pack/update_metadata",
- %{
- "new_data" => ctx[:new_data]
- }
- )
+ |> patch("/api/pleroma/emoji/packs/test_pack", %{"metadata" => ctx[:new_data]})
|> json_response(200) == ctx[:new_data]
assert Jason.decode!(File.read!(ctx[:pack_file]))["pack"] == ctx[:new_data]
@@ -352,12 +336,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
)
assert ctx[:admin_conn]
- |> post(
- "/api/pleroma/emoji/packs/test_pack/update_metadata",
- %{
- "new_data" => new_data
- }
- )
+ |> patch("/api/pleroma/emoji/packs/test_pack", %{metadata: new_data})
|> json_response(200) == new_data_with_sha
assert Jason.decode!(File.read!(ctx[:pack_file]))["pack"] == new_data_with_sha
@@ -376,19 +355,14 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
new_data = Map.put(ctx[:new_data], "fallback-src", "https://nonshared-pack")
assert ctx[:admin_conn]
- |> post(
- "/api/pleroma/emoji/packs/test_pack/update_metadata",
- %{
- "new_data" => new_data
- }
- )
+ |> patch("/api/pleroma/emoji/packs/test_pack", %{metadata: new_data})
|> json_response(:bad_request) == %{
"error" => "The fallback archive does not have all files specified in pack.json"
}
end
end
- describe "POST /api/pleroma/emoji/packs/:pack_name/update_file" do
+ describe "POST/PATCH/DELETE /api/pleroma/emoji/packs/:name/files" do
setup do
pack_file = "#{@emoji_path}/test_pack/pack.json"
original_content = File.read!(pack_file)
@@ -402,11 +376,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "create shortcode exists", %{admin_conn: admin_conn} do
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "add",
- "shortcode" => "blank",
- "filename" => "dir/blank.png",
- "file" => %Plug.Upload{
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank",
+ filename: "dir/blank.png",
+ file: %Plug.Upload{
filename: "blank.png",
path: "#{@emoji_path}/test_pack/blank.png"
}
@@ -420,11 +393,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir/") end)
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "add",
- "shortcode" => "blank2",
- "filename" => "dir/blank.png",
- "file" => %Plug.Upload{
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank2",
+ filename: "dir/blank.png",
+ file: %Plug.Upload{
filename: "blank.png",
path: "#{@emoji_path}/test_pack/blank.png"
}
@@ -434,11 +406,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "update",
- "shortcode" => "blank",
- "new_shortcode" => "blank2",
- "new_filename" => "dir_2/blank_3.png"
+ |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank",
+ new_shortcode: "blank2",
+ new_filename: "dir_2/blank_3.png"
})
|> json_response(:conflict) == %{
"error" =>
@@ -450,11 +421,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir_2/") end)
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "add",
- "shortcode" => "blank2",
- "filename" => "dir/blank.png",
- "file" => %Plug.Upload{
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank2",
+ filename: "dir/blank.png",
+ file: %Plug.Upload{
filename: "blank.png",
path: "#{@emoji_path}/test_pack/blank.png"
}
@@ -464,12 +434,11 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "update",
- "shortcode" => "blank2",
- "new_shortcode" => "blank3",
- "new_filename" => "dir_2/blank_3.png",
- "force" => true
+ |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank2",
+ new_shortcode: "blank3",
+ new_filename: "dir_2/blank_3.png",
+ force: true
})
|> json_response(200) == %{
"blank" => "blank.png",
@@ -481,11 +450,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "with empty filename", %{admin_conn: admin_conn} do
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "add",
- "shortcode" => "blank2",
- "filename" => "",
- "file" => %Plug.Upload{
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank2",
+ filename: "",
+ file: %Plug.Upload{
filename: "blank.png",
path: "#{@emoji_path}/test_pack/blank.png"
}
@@ -497,11 +465,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "add file with not loaded pack", %{admin_conn: admin_conn} do
assert admin_conn
- |> post("/api/pleroma/emoji/packs/not_loaded/update_file", %{
- "action" => "add",
- "shortcode" => "blank2",
- "filename" => "dir/blank.png",
- "file" => %Plug.Upload{
+ |> post("/api/pleroma/emoji/packs/not_loaded/files", %{
+ shortcode: "blank2",
+ filename: "dir/blank.png",
+ file: %Plug.Upload{
filename: "blank.png",
path: "#{@emoji_path}/test_pack/blank.png"
}
@@ -513,19 +480,13 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "remove file with not loaded pack", %{admin_conn: admin_conn} do
assert admin_conn
- |> post("/api/pleroma/emoji/packs/not_loaded/update_file", %{
- "action" => "remove",
- "shortcode" => "blank3"
- })
+ |> delete("/api/pleroma/emoji/packs/not_loaded/files", %{shortcode: "blank3"})
|> json_response(:bad_request) == %{"error" => "pack \"not_loaded\" is not found"}
end
test "remove file with empty shortcode", %{admin_conn: admin_conn} do
assert admin_conn
- |> post("/api/pleroma/emoji/packs/not_loaded/update_file", %{
- "action" => "remove",
- "shortcode" => ""
- })
+ |> delete("/api/pleroma/emoji/packs/not_loaded/files", %{shortcode: ""})
|> json_response(:bad_request) == %{
"error" => "pack name or shortcode cannot be empty"
}
@@ -533,22 +494,20 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "update file with not loaded pack", %{admin_conn: admin_conn} do
assert admin_conn
- |> post("/api/pleroma/emoji/packs/not_loaded/update_file", %{
- "action" => "update",
- "shortcode" => "blank4",
- "new_shortcode" => "blank3",
- "new_filename" => "dir_2/blank_3.png"
+ |> patch("/api/pleroma/emoji/packs/not_loaded/files", %{
+ shortcode: "blank4",
+ new_shortcode: "blank3",
+ new_filename: "dir_2/blank_3.png"
})
|> json_response(:bad_request) == %{"error" => "pack \"not_loaded\" is not found"}
end
test "new with shortcode as file with update", %{admin_conn: admin_conn} do
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "add",
- "shortcode" => "blank4",
- "filename" => "dir/blank.png",
- "file" => %Plug.Upload{
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank4",
+ filename: "dir/blank.png",
+ file: %Plug.Upload{
filename: "blank.png",
path: "#{@emoji_path}/test_pack/blank.png"
}
@@ -558,11 +517,10 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "update",
- "shortcode" => "blank4",
- "new_shortcode" => "blank3",
- "new_filename" => "dir_2/blank_3.png"
+ |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank4",
+ new_shortcode: "blank3",
+ new_filename: "dir_2/blank_3.png"
})
|> json_response(200) == %{"blank3" => "dir_2/blank_3.png", "blank" => "blank.png"}
@@ -570,10 +528,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
assert File.exists?("#{@emoji_path}/test_pack/dir_2/blank_3.png")
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "remove",
- "shortcode" => "blank3"
- })
+ |> delete("/api/pleroma/emoji/packs/test_pack/files", %{shortcode: "blank3"})
|> json_response(200) == %{"blank" => "blank.png"}
refute File.exists?("#{@emoji_path}/test_pack/dir_2/")
@@ -591,10 +546,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "add",
- "shortcode" => "blank_url",
- "file" => "https://test-blank/blank_url.png"
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank_url",
+ file: "https://test-blank/blank_url.png"
})
|> json_response(200) == %{
"blank_url" => "blank_url.png",
@@ -610,9 +564,8 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/shortcode.png") end)
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "add",
- "file" => %Plug.Upload{
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ file: %Plug.Upload{
filename: "shortcode.png",
path: "#{Pleroma.Config.get([:instance, :static_dir])}/add/shortcode.png"
}
@@ -622,51 +575,36 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "remove non existing shortcode in pack.json", %{admin_conn: admin_conn} do
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "remove",
- "shortcode" => "blank2"
- })
+ |> delete("/api/pleroma/emoji/packs/test_pack/files", %{shortcode: "blank2"})
|> json_response(:bad_request) == %{"error" => "Emoji \"blank2\" does not exist"}
end
test "update non existing emoji", %{admin_conn: admin_conn} do
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "update",
- "shortcode" => "blank2",
- "new_shortcode" => "blank3",
- "new_filename" => "dir_2/blank_3.png"
+ |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank2",
+ new_shortcode: "blank3",
+ new_filename: "dir_2/blank_3.png"
})
|> json_response(:bad_request) == %{"error" => "Emoji \"blank2\" does not exist"}
end
test "update with empty shortcode", %{admin_conn: admin_conn} do
assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "update",
- "shortcode" => "blank",
- "new_filename" => "dir_2/blank_3.png"
+ |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank",
+ new_filename: "dir_2/blank_3.png"
})
|> json_response(:bad_request) == %{
"error" => "new_shortcode or new_filename cannot be empty"
}
end
-
- test "undefined action", %{admin_conn: admin_conn} do
- assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_pack/update_file", %{
- "action" => "undefined"
- })
- |> json_response(:bad_request) == %{
- "error" => "Unknown action: undefined"
- }
- end
end
- describe "PUT /api/pleroma/emoji/packs/:name" do
+ describe "POST/DELETE /api/pleroma/emoji/packs/:name" do
test "creating and deleting a pack", %{admin_conn: admin_conn} do
assert admin_conn
- |> put("/api/pleroma/emoji/packs/test_created")
+ |> post("/api/pleroma/emoji/packs/test_created")
|> json_response(200) == "ok"
assert File.exists?("#{@emoji_path}/test_created/pack.json")
@@ -690,7 +628,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
File.write!(Path.join(path, "pack.json"), pack_file)
assert admin_conn
- |> put("/api/pleroma/emoji/packs/test_created")
+ |> post("/api/pleroma/emoji/packs/test_created")
|> json_response(:conflict) == %{
"error" => "A pack named \"test_created\" already exists"
}
@@ -700,7 +638,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "with empty name", %{admin_conn: admin_conn} do
assert admin_conn
- |> put("/api/pleroma/emoji/packs/ ")
+ |> post("/api/pleroma/emoji/packs/ ")
|> json_response(:bad_request) == %{"error" => "pack name cannot be empty"}
end
end
@@ -728,7 +666,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
refute Map.has_key?(resp, "test_pack_for_import")
assert admin_conn
- |> post("/api/pleroma/emoji/packs/import_from_fs")
+ |> get("/api/pleroma/emoji/packs/import")
|> json_response(200) == ["test_pack_for_import"]
resp = conn |> get("/api/pleroma/emoji/packs") |> json_response(200)
@@ -747,7 +685,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
File.write!("#{@emoji_path}/test_pack_for_import/emoji.txt", emoji_txt_content)
assert admin_conn
- |> post("/api/pleroma/emoji/packs/import_from_fs")
+ |> get("/api/pleroma/emoji/packs/import")
|> json_response(200) == ["test_pack_for_import"]
resp = conn |> get("/api/pleroma/emoji/packs") |> json_response(200)
--
cgit v1.2.3
From 4dc5302f455e56d3c2cb669e8a70f52457690a86 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 15:26:23 +0200
Subject: Transmogrifier: Handle incoming deletes for non-user objects.
---
test/web/activity_pub/side_effects_test.exs | 23 ++++++++++++++++++++++
.../transmogrifier/delete_handling_test.exs | 6 ++----
2 files changed, 25 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index 0b6b55156..eec9488e7 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -5,6 +5,7 @@
defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
use Pleroma.DataCase
+ alias Pleroma.Activity
alias Pleroma.Notification
alias Pleroma.Object
alias Pleroma.Repo
@@ -15,6 +16,28 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
import Pleroma.Factory
+ describe "delete objects" do
+ setup do
+ user = insert(:user)
+ {:ok, post} = CommonAPI.post(user, %{"status" => "hey"})
+ object = Object.normalize(post)
+ {:ok, delete_data, _meta} = Builder.delete(user, object.data["id"])
+ {:ok, delete, _meta} = ActivityPub.persist(delete_data, local: true)
+ %{user: user, delete: delete, post: post, object: object}
+ end
+
+ test "it handles object deletions", %{delete: delete, post: post, object: object} do
+ # In object deletions, the object is replaced by a tombstone and the
+ # create activity is deleted
+
+ {:ok, _delete, _} = SideEffects.handle(delete)
+
+ object = Object.get_by_id(object.id)
+ assert object.data["type"] == "Tombstone"
+ refute Activity.get_by_id(post.id)
+ end
+ end
+
describe "like objects" do
setup do
poster = insert(:user)
diff --git a/test/web/activity_pub/transmogrifier/delete_handling_test.exs b/test/web/activity_pub/transmogrifier/delete_handling_test.exs
index c15de5a95..64c908a05 100644
--- a/test/web/activity_pub/transmogrifier/delete_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/delete_handling_test.exs
@@ -68,7 +68,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do
|> Map.put("object", object)
assert capture_log(fn ->
- :error = Transmogrifier.handle_incoming(data)
+ {:error, _} = Transmogrifier.handle_incoming(data)
end) =~
"[error] Could not decode user at fetch http://mastodon.example.org/users/gargron, {:error, :nxdomain}"
@@ -97,9 +97,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do
|> Poison.decode!()
|> Map.put("actor", ap_id)
- assert capture_log(fn ->
- assert :error == Transmogrifier.handle_incoming(data)
- end) =~ "Object containment failed"
+ assert match?({:error, _}, Transmogrifier.handle_incoming(data))
assert User.get_cached_by_ap_id(ap_id)
end
--
cgit v1.2.3
From 1fb383f368b861d7aea77770ba7be6e3dfe3468e Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 15:42:30 +0200
Subject: DeleteValidator: Deleting a user is valid.
---
test/web/activity_pub/object_validator_test.exs | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index ab26d3501..83b21a9bc 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -15,14 +15,19 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
{:ok, post_activity} = CommonAPI.post(user, %{"status" => "cancel me daddy"})
{:ok, valid_post_delete, _} = Builder.delete(user, post_activity.data["object"])
+ {:ok, valid_user_delete, _} = Builder.delete(user, user.ap_id)
- %{user: user, valid_post_delete: valid_post_delete}
+ %{user: user, valid_post_delete: valid_post_delete, valid_user_delete: valid_user_delete}
end
test "it is valid for a post deletion", %{valid_post_delete: valid_post_delete} do
assert match?({:ok, _, _}, ObjectValidator.validate(valid_post_delete, []))
end
+ test "it is valid for a user deletion", %{valid_user_delete: valid_user_delete} do
+ assert match?({:ok, _, _}, ObjectValidator.validate(valid_user_delete, []))
+ end
+
test "it's invalid if the id is missing", %{valid_post_delete: valid_post_delete} do
no_id =
valid_post_delete
--
cgit v1.2.3
From 417eed4a2b10b0a1fd916839ddb03d0345966123 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 15:57:27 +0200
Subject: SideEffects: Handle deletions.
---
test/web/activity_pub/side_effects_test.exs | 14 +++++++++++++-
1 file changed, 13 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index eec9488e7..b3d0addc7 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -3,12 +3,15 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
+ use Oban.Testing, repo: Pleroma.Repo
use Pleroma.DataCase
alias Pleroma.Activity
alias Pleroma.Notification
alias Pleroma.Object
alias Pleroma.Repo
+ alias Pleroma.User
+ alias Pleroma.Tests.ObanHelpers
alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.SideEffects
@@ -22,8 +25,10 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
{:ok, post} = CommonAPI.post(user, %{"status" => "hey"})
object = Object.normalize(post)
{:ok, delete_data, _meta} = Builder.delete(user, object.data["id"])
+ {:ok, delete_user_data, _meta} = Builder.delete(user, user.ap_id)
{:ok, delete, _meta} = ActivityPub.persist(delete_data, local: true)
- %{user: user, delete: delete, post: post, object: object}
+ {:ok, delete_user, _meta} = ActivityPub.persist(delete_user_data, local: true)
+ %{user: user, delete: delete, post: post, object: object, delete_user: delete_user}
end
test "it handles object deletions", %{delete: delete, post: post, object: object} do
@@ -36,6 +41,13 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
assert object.data["type"] == "Tombstone"
refute Activity.get_by_id(post.id)
end
+
+ test "it handles user deletions", %{delete_user: delete, user: user} do
+ {:ok, _delete, _} = SideEffects.handle(delete)
+ ObanHelpers.perform_all()
+
+ refute User.get_cached_by_ap_id(user.ap_id)
+ end
end
describe "like objects" do
--
cgit v1.2.3
From c9bfa51ea9c0048ffa4c0d3e28c196da2f38e384 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 15:58:37 +0200
Subject: Credo fixes.
---
test/web/activity_pub/side_effects_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index b3d0addc7..fffe0ca38 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -10,8 +10,8 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
alias Pleroma.Notification
alias Pleroma.Object
alias Pleroma.Repo
- alias Pleroma.User
alias Pleroma.Tests.ObanHelpers
+ alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.SideEffects
--
cgit v1.2.3
From 2c4844237f294d27f58737f9694f77b1cfcb10e7 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Thu, 30 Apr 2020 18:19:51 +0300
Subject: Refactoring of :if_func / :unless_func plug options (general
availability). Added tests for Pleroma.Web.Plug.
---
test/plugs/ensure_authenticated_plug_test.exs | 4 +-
test/web/plugs/plug_test.exs | 91 +++++++++++++++++++++++++++
2 files changed, 93 insertions(+), 2 deletions(-)
create mode 100644 test/web/plugs/plug_test.exs
(limited to 'test')
diff --git a/test/plugs/ensure_authenticated_plug_test.exs b/test/plugs/ensure_authenticated_plug_test.exs
index 689fe757f..4e6142aab 100644
--- a/test/plugs/ensure_authenticated_plug_test.exs
+++ b/test/plugs/ensure_authenticated_plug_test.exs
@@ -27,8 +27,8 @@ defmodule Pleroma.Plugs.EnsureAuthenticatedPlugTest do
describe "with :if_func / :unless_func options" do
setup do
%{
- true_fn: fn -> true end,
- false_fn: fn -> false end
+ true_fn: fn _conn -> true end,
+ false_fn: fn _conn -> false end
}
end
diff --git a/test/web/plugs/plug_test.exs b/test/web/plugs/plug_test.exs
new file mode 100644
index 000000000..943e484e7
--- /dev/null
+++ b/test/web/plugs/plug_test.exs
@@ -0,0 +1,91 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.PlugTest do
+ @moduledoc "Tests for the functionality added via `use Pleroma.Web, :plug`"
+
+ alias Pleroma.Plugs.ExpectAuthenticatedCheckPlug
+ alias Pleroma.Plugs.ExpectPublicOrAuthenticatedCheckPlug
+ alias Pleroma.Plugs.PlugHelper
+
+ import Mock
+
+ use Pleroma.Web.ConnCase
+
+ describe "when plug is skipped, " do
+ setup_with_mocks(
+ [
+ {ExpectPublicOrAuthenticatedCheckPlug, [:passthrough], []}
+ ],
+ %{conn: conn}
+ ) do
+ conn = ExpectPublicOrAuthenticatedCheckPlug.skip_plug(conn)
+ %{conn: conn}
+ end
+
+ test "it neither adds plug to called plugs list nor calls `perform/2`, " <>
+ "regardless of :if_func / :unless_func options",
+ %{conn: conn} do
+ for opts <- [%{}, %{if_func: fn _ -> true end}, %{unless_func: fn _ -> false end}] do
+ ret_conn = ExpectPublicOrAuthenticatedCheckPlug.call(conn, opts)
+
+ refute called(ExpectPublicOrAuthenticatedCheckPlug.perform(:_, :_))
+ refute PlugHelper.plug_called?(ret_conn, ExpectPublicOrAuthenticatedCheckPlug)
+ end
+ end
+ end
+
+ describe "when plug is NOT skipped, " do
+ setup_with_mocks([{ExpectAuthenticatedCheckPlug, [:passthrough], []}]) do
+ :ok
+ end
+
+ test "with no pre-run checks, adds plug to called plugs list and calls `perform/2`", %{
+ conn: conn
+ } do
+ ret_conn = ExpectAuthenticatedCheckPlug.call(conn, %{})
+
+ assert called(ExpectAuthenticatedCheckPlug.perform(ret_conn, :_))
+ assert PlugHelper.plug_called?(ret_conn, ExpectAuthenticatedCheckPlug)
+ end
+
+ test "when :if_func option is given, calls the plug only if provided function evals tru-ish",
+ %{conn: conn} do
+ ret_conn = ExpectAuthenticatedCheckPlug.call(conn, %{if_func: fn _ -> false end})
+
+ refute called(ExpectAuthenticatedCheckPlug.perform(:_, :_))
+ refute PlugHelper.plug_called?(ret_conn, ExpectAuthenticatedCheckPlug)
+
+ ret_conn = ExpectAuthenticatedCheckPlug.call(conn, %{if_func: fn _ -> true end})
+
+ assert called(ExpectAuthenticatedCheckPlug.perform(ret_conn, :_))
+ assert PlugHelper.plug_called?(ret_conn, ExpectAuthenticatedCheckPlug)
+ end
+
+ test "if :unless_func option is given, calls the plug only if provided function evals falsy",
+ %{conn: conn} do
+ ret_conn = ExpectAuthenticatedCheckPlug.call(conn, %{unless_func: fn _ -> true end})
+
+ refute called(ExpectAuthenticatedCheckPlug.perform(:_, :_))
+ refute PlugHelper.plug_called?(ret_conn, ExpectAuthenticatedCheckPlug)
+
+ ret_conn = ExpectAuthenticatedCheckPlug.call(conn, %{unless_func: fn _ -> false end})
+
+ assert called(ExpectAuthenticatedCheckPlug.perform(ret_conn, :_))
+ assert PlugHelper.plug_called?(ret_conn, ExpectAuthenticatedCheckPlug)
+ end
+
+ test "allows a plug to be called multiple times (even if it's in called plugs list)", %{
+ conn: conn
+ } do
+ conn = ExpectAuthenticatedCheckPlug.call(conn, %{an_option: :value1})
+ assert called(ExpectAuthenticatedCheckPlug.perform(conn, %{an_option: :value1}))
+
+ assert PlugHelper.plug_called?(conn, ExpectAuthenticatedCheckPlug)
+
+ conn = ExpectAuthenticatedCheckPlug.call(conn, %{an_option: :value2})
+ assert called(ExpectAuthenticatedCheckPlug.perform(conn, %{an_option: :value2}))
+ end
+ end
+end
--
cgit v1.2.3
From bef34568f0d005baabca266b99ac0f6e620e6899 Mon Sep 17 00:00:00 2001
From: eugenijm
Date: Thu, 30 Apr 2020 15:02:35 +0300
Subject: Dismiss the follow request notification on rejection
---
test/notification_test.exs | 10 ++++++++++
1 file changed, 10 insertions(+)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 6ad824c57..0e9ffcb18 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -362,6 +362,16 @@ defmodule Pleroma.NotificationTest do
notification_id = notification.id
assert [%{id: ^notification_id}] = Notification.for_user(followed_user)
end
+
+ test "dismisses the notification on follow request rejection" do
+ clear_config([:notifications, :enable_follow_request_notifications], true)
+ user = insert(:user, locked: true)
+ follower = insert(:user)
+ {:ok, _, _, _follow_activity} = CommonAPI.follow(follower, user)
+ assert [notification] = Notification.for_user(user)
+ {:ok, _follower} = CommonAPI.reject_follow_request(follower, user)
+ assert [] = Notification.for_user(user)
+ end
end
describe "get notification" do
--
cgit v1.2.3
From 143353432a562c49f4432e74a549321c5b43650d Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 17:52:29 +0200
Subject: StreamerTest: Separate deletion test.
---
test/web/streamer/streamer_test.exs | 6 ++++++
1 file changed, 6 insertions(+)
(limited to 'test')
diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs
index 8b8d8af6c..3c0f240f5 100644
--- a/test/web/streamer/streamer_test.exs
+++ b/test/web/streamer/streamer_test.exs
@@ -210,6 +210,12 @@ defmodule Pleroma.Web.StreamerTest do
Worker.push_to_socket(topics, "public", activity)
Task.await(task)
+ end
+
+ test "works for deletions" do
+ user = insert(:user)
+ other_user = insert(:user)
+ {:ok, activity} = CommonAPI.post(other_user, %{"status" => "Test"})
task =
Task.async(fn ->
--
cgit v1.2.3
From 4500fdc04c528331f7289745dc08a34ce18d4da7 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 17:53:02 +0200
Subject: DeleteValidator: Add internal helper field after validation.
---
test/web/activity_pub/object_validator_test.exs | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 83b21a9bc..9e0589722 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -21,7 +21,9 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
end
test "it is valid for a post deletion", %{valid_post_delete: valid_post_delete} do
- assert match?({:ok, _, _}, ObjectValidator.validate(valid_post_delete, []))
+ {:ok, valid_post_delete_u, _} = ObjectValidator.validate(valid_post_delete, [])
+
+ assert valid_post_delete_u["deleted_activity_id"]
end
test "it is valid for a user deletion", %{valid_user_delete: valid_user_delete} do
--
cgit v1.2.3
From 315b773dd9fa185aef75b115efd90ac92113e6c3 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 17:58:31 +0200
Subject: ObjectValidator: Refactor.
---
test/web/activity_pub/object_validator_test.exs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 9e0589722..1d3646487 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -21,9 +21,9 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
end
test "it is valid for a post deletion", %{valid_post_delete: valid_post_delete} do
- {:ok, valid_post_delete_u, _} = ObjectValidator.validate(valid_post_delete, [])
+ {:ok, valid_post_delete, _} = ObjectValidator.validate(valid_post_delete, [])
- assert valid_post_delete_u["deleted_activity_id"]
+ assert valid_post_delete["deleted_activity_id"]
end
test "it is valid for a user deletion", %{valid_user_delete: valid_user_delete} do
--
cgit v1.2.3
From 3d0dc58e2e0a84cb46df5339596205f7baceb0a4 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 18:10:36 +0200
Subject: SideEffectsTest: Test streaming.
---
test/web/activity_pub/side_effects_test.exs | 12 ++++++++++--
1 file changed, 10 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index fffe0ca38..f5c57d887 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -18,6 +18,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
alias Pleroma.Web.CommonAPI
import Pleroma.Factory
+ import Mock
describe "delete objects" do
setup do
@@ -33,9 +34,16 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
test "it handles object deletions", %{delete: delete, post: post, object: object} do
# In object deletions, the object is replaced by a tombstone and the
- # create activity is deleted
+ # create activity is deleted.
- {:ok, _delete, _} = SideEffects.handle(delete)
+ with_mock Pleroma.Web.ActivityPub.ActivityPub,
+ stream_out: fn _ -> nil end,
+ stream_out_participations: fn _, _ -> nil end do
+ {:ok, delete, _} = SideEffects.handle(delete)
+ user = User.get_cached_by_ap_id(object.data["actor"])
+ assert called(Pleroma.Web.ActivityPub.ActivityPub.stream_out(delete))
+ assert called(Pleroma.Web.ActivityPub.ActivityPub.stream_out_participations(object, user))
+ end
object = Object.get_by_id(object.id)
assert object.data["type"] == "Tombstone"
--
cgit v1.2.3
From ab60ee17765ee9d7dcb69cbf9c0630b97d4f5a93 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 18:19:39 +0200
Subject: SideEffects: On deletion, reduce the User note count.
---
test/web/activity_pub/side_effects_test.exs | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index f5c57d887..06b3400d8 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -32,15 +32,16 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
%{user: user, delete: delete, post: post, object: object, delete_user: delete_user}
end
- test "it handles object deletions", %{delete: delete, post: post, object: object} do
+ test "it handles object deletions", %{delete: delete, post: post, object: object, user: user} do
# In object deletions, the object is replaced by a tombstone and the
# create activity is deleted.
- with_mock Pleroma.Web.ActivityPub.ActivityPub,
+ with_mock Pleroma.Web.ActivityPub.ActivityPub, [:passthrough],
stream_out: fn _ -> nil end,
stream_out_participations: fn _, _ -> nil end do
{:ok, delete, _} = SideEffects.handle(delete)
user = User.get_cached_by_ap_id(object.data["actor"])
+
assert called(Pleroma.Web.ActivityPub.ActivityPub.stream_out(delete))
assert called(Pleroma.Web.ActivityPub.ActivityPub.stream_out_participations(object, user))
end
@@ -48,6 +49,9 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
object = Object.get_by_id(object.id)
assert object.data["type"] == "Tombstone"
refute Activity.get_by_id(post.id)
+
+ user = User.get_by_id(user.id)
+ assert user.note_count == 0
end
test "it handles user deletions", %{delete_user: delete, user: user} do
--
cgit v1.2.3
From f1523f9acd61021d5026e8f8f991fa5c21f23b1f Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Thu, 30 Apr 2020 18:55:25 +0200
Subject: Increase tests on AP C2S
Related: https://git.pleroma.social/pleroma/pleroma/-/issues/954
---
.../activity_pub/activity_pub_controller_test.exs | 70 ++++++++++++++++------
1 file changed, 53 insertions(+), 17 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs
index eca526604..6b5913f95 100644
--- a/test/web/activity_pub/activity_pub_controller_test.exs
+++ b/test/web/activity_pub/activity_pub_controller_test.exs
@@ -765,51 +765,87 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
end
end
- describe "POST /users/:nickname/outbox" do
- test "it rejects posts from other users / unauthenticated users", %{conn: conn} do
- data = File.read!("test/fixtures/activitypub-client-post-activity.json") |> Poison.decode!()
+ describe "POST /users/:nickname/outbox (C2S)" do
+ setup do
+ [
+ activity: %{
+ "@context" => "https://www.w3.org/ns/activitystreams",
+ "type" => "Create",
+ "object" => %{"type" => "Note", "content" => "AP C2S test"},
+ "to" => "https://www.w3.org/ns/activitystreams#Public",
+ "cc" => []
+ }
+ ]
+ end
+
+ test "it rejects posts from other users / unauthenticated users", %{
+ conn: conn,
+ activity: activity
+ } do
user = insert(:user)
other_user = insert(:user)
conn = put_req_header(conn, "content-type", "application/activity+json")
conn
- |> post("/users/#{user.nickname}/outbox", data)
+ |> post("/users/#{user.nickname}/outbox", activity)
|> json_response(403)
conn
|> assign(:user, other_user)
- |> post("/users/#{user.nickname}/outbox", data)
+ |> post("/users/#{user.nickname}/outbox", activity)
|> json_response(403)
end
- test "it inserts an incoming create activity into the database", %{conn: conn} do
- data = File.read!("test/fixtures/activitypub-client-post-activity.json") |> Poison.decode!()
+ test "it inserts an incoming create activity into the database", %{
+ conn: conn,
+ activity: activity
+ } do
user = insert(:user)
- conn =
+ result =
conn
|> assign(:user, user)
|> put_req_header("content-type", "application/activity+json")
- |> post("/users/#{user.nickname}/outbox", data)
-
- result = json_response(conn, 201)
+ |> post("/users/#{user.nickname}/outbox", activity)
+ |> json_response(201)
assert Activity.get_by_ap_id(result["id"])
+ assert result["object"]
+ assert %Object{data: object} = Object.normalize(result["object"])
+ assert object["content"] == activity["object"]["content"]
end
- test "it rejects an incoming activity with bogus type", %{conn: conn} do
- data = File.read!("test/fixtures/activitypub-client-post-activity.json") |> Poison.decode!()
+ test "it inserts an incoming sensitive activity into the database", %{
+ conn: conn,
+ activity: activity
+ } do
user = insert(:user)
+ object = Map.put(activity["object"], "sensitive", true)
+ activity = Map.put(activity, "object", object)
- data =
- data
- |> Map.put("type", "BadType")
+ result =
+ conn
+ |> assign(:user, user)
+ |> put_req_header("content-type", "application/activity+json")
+ |> post("/users/#{user.nickname}/outbox", activity)
+ |> json_response(201)
+
+ assert Activity.get_by_ap_id(result["id"])
+ assert result["object"]
+ assert %Object{data: object} = Object.normalize(result["object"])
+ assert object["sensitive"] == activity["object"]["sensitive"]
+ assert object["content"] == activity["object"]["content"]
+ end
+
+ test "it rejects an incoming activity with bogus type", %{conn: conn, activity: activity} do
+ user = insert(:user)
+ activity = Map.put(activity, "type", "BadType")
conn =
conn
|> assign(:user, user)
|> put_req_header("content-type", "application/activity+json")
- |> post("/users/#{user.nickname}/outbox", data)
+ |> post("/users/#{user.nickname}/outbox", activity)
assert json_response(conn, 400)
end
--
cgit v1.2.3
From 500f5ec14eb02cd1c5a07970a557756b590caab0 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 19:47:13 +0200
Subject: SideEffects: On deletion, reduce the reply count cache
---
test/web/activity_pub/side_effects_test.exs | 22 ++++++++++++++++------
1 file changed, 16 insertions(+), 6 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index 06b3400d8..ce34eed4c 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -23,19 +23,25 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
describe "delete objects" do
setup do
user = insert(:user)
- {:ok, post} = CommonAPI.post(user, %{"status" => "hey"})
+ other_user = insert(:user)
+
+ {:ok, op} = CommonAPI.post(other_user, %{"status" => "big oof"})
+ {:ok, post} = CommonAPI.post(user, %{"status" => "hey", "in_reply_to_id" => op})
object = Object.normalize(post)
{:ok, delete_data, _meta} = Builder.delete(user, object.data["id"])
{:ok, delete_user_data, _meta} = Builder.delete(user, user.ap_id)
{:ok, delete, _meta} = ActivityPub.persist(delete_data, local: true)
{:ok, delete_user, _meta} = ActivityPub.persist(delete_user_data, local: true)
- %{user: user, delete: delete, post: post, object: object, delete_user: delete_user}
+ %{user: user, delete: delete, post: post, object: object, delete_user: delete_user, op: op}
end
- test "it handles object deletions", %{delete: delete, post: post, object: object, user: user} do
- # In object deletions, the object is replaced by a tombstone and the
- # create activity is deleted.
-
+ test "it handles object deletions", %{
+ delete: delete,
+ post: post,
+ object: object,
+ user: user,
+ op: op
+ } do
with_mock Pleroma.Web.ActivityPub.ActivityPub, [:passthrough],
stream_out: fn _ -> nil end,
stream_out_participations: fn _, _ -> nil end do
@@ -52,6 +58,10 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
user = User.get_by_id(user.id)
assert user.note_count == 0
+
+ object = Object.normalize(op.data["object"], false)
+
+ assert object.data["repliesCount"] == 0
end
test "it handles user deletions", %{delete_user: delete, user: user} do
--
cgit v1.2.3
From 5da08c2b73f9ce1f369434fbd2c11092007e4910 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 19:53:30 +0200
Subject: SideEffects: Fix comment
---
test/user_test.exs | 28 +---------------------------
1 file changed, 1 insertion(+), 27 deletions(-)
(limited to 'test')
diff --git a/test/user_test.exs b/test/user_test.exs
index 347c5be72..23afc605c 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -15,7 +15,6 @@ defmodule Pleroma.UserTest do
use Pleroma.DataCase
use Oban.Testing, repo: Pleroma.Repo
- import Mock
import Pleroma.Factory
import ExUnit.CaptureLog
@@ -1131,7 +1130,7 @@ defmodule Pleroma.UserTest do
User.delete_user_activities(user)
- # TODO: Remove favorites, repeats, delete activities.
+ # TODO: Test removal favorites, repeats, delete activities.
refute Activity.get_by_id(activity.id)
end
@@ -1180,31 +1179,6 @@ defmodule Pleroma.UserTest do
refute Activity.get_by_id(like_two.id)
refute Activity.get_by_id(repeat.id)
end
-
- test_with_mock "it sends out User Delete activity",
- %{user: user},
- Pleroma.Web.ActivityPub.Publisher,
- [:passthrough],
- [] do
- Pleroma.Config.put([:instance, :federating], true)
-
- {:ok, follower} = User.get_or_fetch_by_ap_id("http://mastodon.example.org/users/admin")
- {:ok, _} = User.follow(follower, user)
-
- {:ok, job} = User.delete(user)
- {:ok, _user} = ObanHelpers.perform(job)
-
- assert ObanHelpers.member?(
- %{
- "op" => "publish_one",
- "params" => %{
- "inbox" => "http://mastodon.example.org/inbox",
- "id" => "pleroma:fakeid"
- }
- },
- all_enqueued(worker: Pleroma.Workers.PublisherWorker)
- )
- end
end
test "get_public_key_for_ap_id fetches a user that's not in the db" do
--
cgit v1.2.3
From 999d639873b70f75c340dbac3360d25bca27a998 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 20:13:47 +0200
Subject: ActivityPub: Remove `delete` function.
This is handled by the common pipeline now.
---
test/web/activity_pub/activity_pub_test.exs | 137 ----------------------------
1 file changed, 137 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index edd7dfb22..b93ee708e 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -1331,143 +1331,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
end
end
- describe "deletion" do
- setup do: clear_config([:instance, :rewrite_policy])
-
- test "it reverts deletion on error" do
- note = insert(:note_activity)
- object = Object.normalize(note)
-
- with_mock(Utils, [:passthrough], maybe_federate: fn _ -> {:error, :reverted} end) do
- assert {:error, :reverted} = ActivityPub.delete(object)
- end
-
- assert Repo.aggregate(Activity, :count, :id) == 1
- assert Repo.get(Object, object.id) == object
- assert Activity.get_by_id(note.id) == note
- end
-
- test "it creates a delete activity and deletes the original object" do
- note = insert(:note_activity)
- object = Object.normalize(note)
- {:ok, delete} = ActivityPub.delete(object)
-
- assert delete.data["type"] == "Delete"
- assert delete.data["actor"] == note.data["actor"]
- assert delete.data["object"] == object.data["id"]
-
- assert Activity.get_by_id(delete.id) != nil
-
- assert Repo.get(Object, object.id).data["type"] == "Tombstone"
- end
-
- test "it doesn't fail when an activity was already deleted" do
- {:ok, delete} = insert(:note_activity) |> Object.normalize() |> ActivityPub.delete()
-
- assert {:ok, ^delete} = delete |> Object.normalize() |> ActivityPub.delete()
- end
-
- test "decrements user note count only for public activities" do
- user = insert(:user, note_count: 10)
-
- {:ok, a1} =
- CommonAPI.post(User.get_cached_by_id(user.id), %{
- "status" => "yeah",
- "visibility" => "public"
- })
-
- {:ok, a2} =
- CommonAPI.post(User.get_cached_by_id(user.id), %{
- "status" => "yeah",
- "visibility" => "unlisted"
- })
-
- {:ok, a3} =
- CommonAPI.post(User.get_cached_by_id(user.id), %{
- "status" => "yeah",
- "visibility" => "private"
- })
-
- {:ok, a4} =
- CommonAPI.post(User.get_cached_by_id(user.id), %{
- "status" => "yeah",
- "visibility" => "direct"
- })
-
- {:ok, _} = Object.normalize(a1) |> ActivityPub.delete()
- {:ok, _} = Object.normalize(a2) |> ActivityPub.delete()
- {:ok, _} = Object.normalize(a3) |> ActivityPub.delete()
- {:ok, _} = Object.normalize(a4) |> ActivityPub.delete()
-
- user = User.get_cached_by_id(user.id)
- assert user.note_count == 10
- end
-
- test "it creates a delete activity and checks that it is also sent to users mentioned by the deleted object" do
- user = insert(:user)
- note = insert(:note_activity)
- object = Object.normalize(note)
-
- {:ok, object} =
- object
- |> Object.change(%{
- data: %{
- "actor" => object.data["actor"],
- "id" => object.data["id"],
- "to" => [user.ap_id],
- "type" => "Note"
- }
- })
- |> Object.update_and_set_cache()
-
- {:ok, delete} = ActivityPub.delete(object)
-
- assert user.ap_id in delete.data["to"]
- end
-
- test "decreases reply count" do
- user = insert(:user)
- user2 = insert(:user)
-
- {:ok, activity} = CommonAPI.post(user, %{"status" => "1", "visibility" => "public"})
- reply_data = %{"status" => "1", "in_reply_to_status_id" => activity.id}
- ap_id = activity.data["id"]
-
- {:ok, public_reply} = CommonAPI.post(user2, Map.put(reply_data, "visibility", "public"))
- {:ok, unlisted_reply} = CommonAPI.post(user2, Map.put(reply_data, "visibility", "unlisted"))
- {:ok, private_reply} = CommonAPI.post(user2, Map.put(reply_data, "visibility", "private"))
- {:ok, direct_reply} = CommonAPI.post(user2, Map.put(reply_data, "visibility", "direct"))
-
- _ = CommonAPI.delete(direct_reply.id, user2)
- assert %{data: data, object: object} = Activity.get_by_ap_id_with_object(ap_id)
- assert object.data["repliesCount"] == 2
-
- _ = CommonAPI.delete(private_reply.id, user2)
- assert %{data: data, object: object} = Activity.get_by_ap_id_with_object(ap_id)
- assert object.data["repliesCount"] == 2
-
- _ = CommonAPI.delete(public_reply.id, user2)
- assert %{data: data, object: object} = Activity.get_by_ap_id_with_object(ap_id)
- assert object.data["repliesCount"] == 1
-
- _ = CommonAPI.delete(unlisted_reply.id, user2)
- assert %{data: data, object: object} = Activity.get_by_ap_id_with_object(ap_id)
- assert object.data["repliesCount"] == 0
- end
-
- test "it passes delete activity through MRF before deleting the object" do
- Pleroma.Config.put([:instance, :rewrite_policy], Pleroma.Web.ActivityPub.MRF.DropPolicy)
-
- note = insert(:note_activity)
- object = Object.normalize(note)
-
- {:error, {:reject, _}} = ActivityPub.delete(object)
-
- assert Activity.get_by_id(note.id)
- assert Repo.get(Object, object.id).data["type"] == object.data["type"]
- end
- end
-
describe "timeline post-processing" do
test "it filters broken threads" do
user1 = insert(:user)
--
cgit v1.2.3
From 32b8386edeec3e9b24123c3ccc81a22f1edd5a1c Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 30 Apr 2020 21:23:18 +0200
Subject: DeleteValidator: Don't federate local deletions of remote objects.
Closes #1497
---
test/web/activity_pub/object_validator_test.exs | 17 +++++-
test/web/common_api/common_api_test.exs | 80 +++++++++++++++++++++++++
2 files changed, 96 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 1d3646487..412db09ff 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -52,9 +52,11 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
test "it's invalid if the actor of the object and the actor of delete are from different domains",
%{valid_post_delete: valid_post_delete} do
+ valid_user = insert(:user)
+
valid_other_actor =
valid_post_delete
- |> Map.put("actor", valid_post_delete["actor"] <> "1")
+ |> Map.put("actor", valid_user.ap_id)
assert match?({:ok, _, _}, ObjectValidator.validate(valid_other_actor, []))
@@ -66,6 +68,19 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
assert {:actor, {"is not allowed to delete object", []}} in cng.errors
end
+
+ test "it's valid if the actor of the object is a local superuser",
+ %{valid_post_delete: valid_post_delete} do
+ user =
+ insert(:user, local: true, is_moderator: true, ap_id: "https://gensokyo.2hu/users/raymoo")
+
+ valid_other_actor =
+ valid_post_delete
+ |> Map.put("actor", user.ap_id)
+
+ {:ok, _, meta} = ObjectValidator.validate(valid_other_actor, [])
+ assert meta[:do_not_federate]
+ end
end
describe "likes" do
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index 1758662b0..32d91ce02 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -9,11 +9,13 @@ defmodule Pleroma.Web.CommonAPITest do
alias Pleroma.Object
alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
+ alias Pleroma.Web.ActivityPub.Transmogrifier
alias Pleroma.Web.ActivityPub.Visibility
alias Pleroma.Web.AdminAPI.AccountView
alias Pleroma.Web.CommonAPI
import Pleroma.Factory
+ import Mock
require Pleroma.Constants
@@ -21,6 +23,84 @@ defmodule Pleroma.Web.CommonAPITest do
setup do: clear_config([:instance, :limit])
setup do: clear_config([:instance, :max_pinned_statuses])
+ describe "deletion" do
+ test "it allows users to delete their posts" do
+ user = insert(:user)
+
+ {:ok, post} = CommonAPI.post(user, %{"status" => "namu amida butsu"})
+
+ with_mock Pleroma.Web.Federator,
+ publish: fn _ -> nil end do
+ assert {:ok, delete} = CommonAPI.delete(post.id, user)
+ assert delete.local
+ assert called(Pleroma.Web.Federator.publish(delete))
+ end
+
+ refute Activity.get_by_id(post.id)
+ end
+
+ test "it does not allow a user to delete their posts" do
+ user = insert(:user)
+ other_user = insert(:user)
+
+ {:ok, post} = CommonAPI.post(user, %{"status" => "namu amida butsu"})
+
+ assert {:error, "Could not delete"} = CommonAPI.delete(post.id, other_user)
+ assert Activity.get_by_id(post.id)
+ end
+
+ test "it allows moderators to delete other user's posts" do
+ user = insert(:user)
+ moderator = insert(:user, is_moderator: true)
+
+ {:ok, post} = CommonAPI.post(user, %{"status" => "namu amida butsu"})
+
+ assert {:ok, delete} = CommonAPI.delete(post.id, moderator)
+ assert delete.local
+
+ refute Activity.get_by_id(post.id)
+ end
+
+ test "it allows admins to delete other user's posts" do
+ user = insert(:user)
+ moderator = insert(:user, is_admin: true)
+
+ {:ok, post} = CommonAPI.post(user, %{"status" => "namu amida butsu"})
+
+ assert {:ok, delete} = CommonAPI.delete(post.id, moderator)
+ assert delete.local
+
+ refute Activity.get_by_id(post.id)
+ end
+
+ test "superusers deleting non-local posts won't federate the delete" do
+ # This is the user of the ingested activity
+ _user =
+ insert(:user,
+ local: false,
+ ap_id: "http://mastodon.example.org/users/admin",
+ last_refreshed_at: NaiveDateTime.utc_now()
+ )
+
+ moderator = insert(:user, is_admin: true)
+
+ data =
+ File.read!("test/fixtures/mastodon-post-activity.json")
+ |> Jason.decode!()
+
+ {:ok, post} = Transmogrifier.handle_incoming(data)
+
+ with_mock Pleroma.Web.Federator,
+ publish: fn _ -> nil end do
+ assert {:ok, delete} = CommonAPI.delete(post.id, moderator)
+ assert delete.local
+ refute called(Pleroma.Web.Federator.publish(:_))
+ end
+
+ refute Activity.get_by_id(post.id)
+ end
+ end
+
test "favoriting race condition" do
user = insert(:user)
users_serial = insert_list(10, :user)
--
cgit v1.2.3
From 92efb888c7b25692af205b1a4dbce0ae689c439b Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Fri, 1 May 2020 09:51:41 +0300
Subject: Made follow request notifications non-optional (removed config
switch).
---
test/notification_test.exs | 20 +-------------------
1 file changed, 1 insertion(+), 19 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 0e9ffcb18..601a6c0ca 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -312,9 +312,7 @@ defmodule Pleroma.NotificationTest do
})
end
- test "if `follow_request` notifications are enabled, " <>
- "it creates `follow_request` notification for pending Follow activity" do
- clear_config([:notifications, :enable_follow_request_notifications], true)
+ test "it creates `follow_request` notification for pending Follow activity" do
user = insert(:user)
followed_user = insert(:user, locked: true)
@@ -333,21 +331,6 @@ defmodule Pleroma.NotificationTest do
assert %{type: "follow"} = NotificationView.render("show.json", render_opts)
end
- test "if `follow_request` notifications are disabled, " <>
- "it does NOT create `follow*` notification for pending Follow activity" do
- clear_config([:notifications, :enable_follow_request_notifications], false)
- user = insert(:user)
- followed_user = insert(:user, locked: true)
-
- {:ok, _, _, _activity} = CommonAPI.follow(user, followed_user)
- refute FollowingRelationship.following?(user, followed_user)
- assert [] = Notification.for_user(followed_user)
-
- # After request is accepted, no new notifications are generated:
- assert {:ok, _} = CommonAPI.accept_follow_request(user, followed_user)
- assert [] = Notification.for_user(followed_user)
- end
-
test "it doesn't create a notification for follow-unfollow-follow chains" do
user = insert(:user)
followed_user = insert(:user, locked: false)
@@ -364,7 +347,6 @@ defmodule Pleroma.NotificationTest do
end
test "dismisses the notification on follow request rejection" do
- clear_config([:notifications, :enable_follow_request_notifications], true)
user = insert(:user, locked: true)
follower = insert(:user)
{:ok, _, _, _follow_activity} = CommonAPI.follow(follower, user)
--
cgit v1.2.3
From ecf37b46d2c06c701da390eba65239984afe683f Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Fri, 1 May 2020 14:31:24 +0300
Subject: pagination fix for service users filters
---
test/web/admin_api/admin_api_controller_test.exs | 38 ++++++++++++++++++++++--
1 file changed, 36 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index f80dbf8dd..e3af01089 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -18,6 +18,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
alias Pleroma.ReportNote
alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
+ alias Pleroma.Web
alias Pleroma.UserInviteToken
alias Pleroma.Web.ActivityPub.Relay
alias Pleroma.Web.CommonAPI
@@ -737,6 +738,39 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
}
end
+ test "pagination works correctly with service users", %{conn: conn} do
+ service1 = insert(:user, ap_id: Web.base_url() <> "/relay")
+ service2 = insert(:user, ap_id: Web.base_url() <> "/internal/fetch")
+ insert_list(25, :user)
+
+ assert %{"count" => 26, "page_size" => 10, "users" => users1} =
+ conn
+ |> get("/api/pleroma/admin/users?page=1&filters=", %{page_size: "10"})
+ |> json_response(200)
+
+ assert Enum.count(users1) == 10
+ assert service1 not in [users1]
+ assert service2 not in [users1]
+
+ assert %{"count" => 26, "page_size" => 10, "users" => users2} =
+ conn
+ |> get("/api/pleroma/admin/users?page=2&filters=", %{page_size: "10"})
+ |> json_response(200)
+
+ assert Enum.count(users2) == 10
+ assert service1 not in [users2]
+ assert service2 not in [users2]
+
+ assert %{"count" => 26, "page_size" => 10, "users" => users3} =
+ conn
+ |> get("/api/pleroma/admin/users?page=3&filters=", %{page_size: "10"})
+ |> json_response(200)
+
+ assert Enum.count(users3) == 6
+ assert service1 not in [users3]
+ assert service2 not in [users3]
+ end
+
test "renders empty array for the second page", %{conn: conn} do
insert(:user)
@@ -3526,7 +3560,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
test "success", %{conn: conn} do
- base_url = Pleroma.Web.base_url()
+ base_url = Web.base_url()
app_name = "Trusted app"
response =
@@ -3547,7 +3581,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
test "with trusted", %{conn: conn} do
- base_url = Pleroma.Web.base_url()
+ base_url = Web.base_url()
app_name = "Trusted app"
response =
--
cgit v1.2.3
From 5f42e6629d862f0a8dcbbd1527998685b6932d52 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 1 May 2020 13:34:47 +0200
Subject: DeleteValidator: Only allow deletion of certain types.
---
test/web/activity_pub/object_validator_test.exs | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 412db09ff..7ab1c8ffb 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -1,6 +1,7 @@
defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
use Pleroma.DataCase
+ alias Pleroma.Object
alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.ObjectValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator
@@ -26,6 +27,24 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
assert valid_post_delete["deleted_activity_id"]
end
+ test "it is invalid if the object isn't in a list of certain types", %{
+ valid_post_delete: valid_post_delete
+ } do
+ object = Object.get_by_ap_id(valid_post_delete["object"])
+
+ data =
+ object.data
+ |> Map.put("type", "Like")
+
+ {:ok, _object} =
+ object
+ |> Ecto.Changeset.change(%{data: data})
+ |> Object.update_and_set_cache()
+
+ {:error, cng} = ObjectValidator.validate(valid_post_delete, [])
+ assert {:object, {"object not in allowed types", []}} in cng.errors
+ end
+
test "it is valid for a user deletion", %{valid_user_delete: valid_user_delete} do
assert match?({:ok, _, _}, ObjectValidator.validate(valid_user_delete, []))
end
--
cgit v1.2.3
From 51f1dbf0a2bf6b61fdef0be56fd8f20a40827100 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 1 May 2020 14:05:25 +0200
Subject: User deletion mix task: Use common pipeline.
---
test/tasks/user_test.exs | 18 +++++++++++++-----
1 file changed, 13 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/tasks/user_test.exs b/test/tasks/user_test.exs
index 8df835b56..ab56f07c1 100644
--- a/test/tasks/user_test.exs
+++ b/test/tasks/user_test.exs
@@ -4,14 +4,17 @@
defmodule Mix.Tasks.Pleroma.UserTest do
alias Pleroma.Repo
+ alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
alias Pleroma.Web.OAuth.Authorization
alias Pleroma.Web.OAuth.Token
use Pleroma.DataCase
+ use Oban.Testing, repo: Pleroma.Repo
- import Pleroma.Factory
import ExUnit.CaptureIO
+ import Mock
+ import Pleroma.Factory
setup_all do
Mix.shell(Mix.Shell.Process)
@@ -87,12 +90,17 @@ defmodule Mix.Tasks.Pleroma.UserTest do
test "user is deleted" do
user = insert(:user)
- Mix.Tasks.Pleroma.User.run(["rm", user.nickname])
+ with_mock Pleroma.Web.Federator,
+ publish: fn _ -> nil end do
+ Mix.Tasks.Pleroma.User.run(["rm", user.nickname])
+ ObanHelpers.perform_all()
- assert_received {:mix_shell, :info, [message]}
- assert message =~ " deleted"
+ assert_received {:mix_shell, :info, [message]}
+ assert message =~ " deleted"
+ refute User.get_by_nickname(user.nickname)
- refute User.get_by_nickname(user.nickname)
+ assert called(Pleroma.Web.Federator.publish(:_))
+ end
end
test "no user to delete" do
--
cgit v1.2.3
From ebbd9c7f369f986b7a66f66eddab91537c490c79 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 1 May 2020 14:22:39 +0200
Subject: AdminAPIController: Refactor.
---
test/web/admin_api/admin_api_controller_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index f80dbf8dd..c92715fab 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -156,7 +156,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
assert ModerationLog.get_log_entry_message(log_entry) ==
"@#{admin.nickname} deleted users: @#{user.nickname}"
- assert json_response(conn, 200) == user.nickname
+ assert json_response(conn, 200) == [user.nickname]
end
test "multiple users", %{admin: admin, conn: conn} do
--
cgit v1.2.3
From 1ead5f49b8da941399fa2afadd40cd8beb8ccf8d Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 1 May 2020 14:30:39 +0200
Subject: AdminApiController: Use common pipeline for user deletion.
---
test/web/admin_api/admin_api_controller_test.exs | 28 ++++++++++++++++--------
1 file changed, 19 insertions(+), 9 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index c92715fab..35001ab4a 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -6,8 +6,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
use Pleroma.Web.ConnCase
use Oban.Testing, repo: Pleroma.Repo
- import Pleroma.Factory
import ExUnit.CaptureLog
+ import Mock
+ import Pleroma.Factory
alias Pleroma.Activity
alias Pleroma.Config
@@ -146,17 +147,26 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
test "single user", %{admin: admin, conn: conn} do
user = insert(:user)
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> delete("/api/pleroma/admin/users?nickname=#{user.nickname}")
+ with_mock Pleroma.Web.Federator,
+ publish: fn _ -> nil end do
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> delete("/api/pleroma/admin/users?nickname=#{user.nickname}")
- log_entry = Repo.one(ModerationLog)
+ ObanHelpers.perform_all()
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} deleted users: @#{user.nickname}"
+ refute User.get_by_nickname(user.nickname)
+
+ log_entry = Repo.one(ModerationLog)
- assert json_response(conn, 200) == [user.nickname]
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} deleted users: @#{user.nickname}"
+
+ assert json_response(conn, 200) == [user.nickname]
+
+ assert called(Pleroma.Web.Federator.publish(:_))
+ end
end
test "multiple users", %{admin: admin, conn: conn} do
--
cgit v1.2.3
From aea781cbd8fb43f906c6022a8d2e0bf896008203 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Fri, 1 May 2020 16:31:05 +0300
Subject: credo fix
---
test/web/admin_api/admin_api_controller_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index e3af01089..d798412e3 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -18,8 +18,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
alias Pleroma.ReportNote
alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
- alias Pleroma.Web
alias Pleroma.UserInviteToken
+ alias Pleroma.Web
alias Pleroma.Web.ActivityPub.Relay
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.MediaProxy
--
cgit v1.2.3
From a912f72a3674f80fe665db466295192b4dab82a9 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 1 May 2020 15:54:38 +0200
Subject: Signature: Handle non-ap ids in key ids.
Mastodon and Gab sometimes send the format `acct:name@server`.
---
test/signature_test.exs | 18 ++++++++++++++----
1 file changed, 14 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/signature_test.exs b/test/signature_test.exs
index d5a2a62c4..a7a75aa4d 100644
--- a/test/signature_test.exs
+++ b/test/signature_test.exs
@@ -44,7 +44,8 @@ defmodule Pleroma.SignatureTest do
test "it returns error when not found user" do
assert capture_log(fn ->
- assert Signature.fetch_public_key(make_fake_conn("test-ap_id")) == {:error, :error}
+ assert Signature.fetch_public_key(make_fake_conn("https://test-ap-id")) ==
+ {:error, :error}
end) =~ "[error] Could not decode user"
end
@@ -64,7 +65,7 @@ defmodule Pleroma.SignatureTest do
test "it returns error when not found user" do
assert capture_log(fn ->
- {:error, _} = Signature.refetch_public_key(make_fake_conn("test-ap_id"))
+ {:error, _} = Signature.refetch_public_key(make_fake_conn("https://test-ap_id"))
end) =~ "[error] Could not decode user"
end
end
@@ -100,12 +101,21 @@ defmodule Pleroma.SignatureTest do
describe "key_id_to_actor_id/1" do
test "it properly deduces the actor id for misskey" do
assert Signature.key_id_to_actor_id("https://example.com/users/1234/publickey") ==
- "https://example.com/users/1234"
+ {:ok, "https://example.com/users/1234"}
end
test "it properly deduces the actor id for mastodon and pleroma" do
assert Signature.key_id_to_actor_id("https://example.com/users/1234#main-key") ==
- "https://example.com/users/1234"
+ {:ok, "https://example.com/users/1234"}
+ end
+
+ test "it calls webfinger for 'acct:' accounts" do
+ with_mock(Pleroma.Web.WebFinger,
+ finger: fn _ -> %{"ap_id" => "https://gensokyo.2hu/users/raymoo"} end
+ ) do
+ assert Signature.key_id_to_actor_id("acct:raymoo@gensokyo.2hu") ==
+ {:ok, "https://gensokyo.2hu/users/raymoo"}
+ end
end
end
--
cgit v1.2.3
From d5cdc907e3fda14c2ce78ddbb124739441330ecc Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Fri, 1 May 2020 18:45:24 +0300
Subject: Restricted embedding of relationships where applicable (statuses /
notifications / accounts rendering). Added support for :skip_notifications
for accounts listing (index.json). Adjusted tests.
---
.../controllers/notification_controller_test.exs | 4 +---
.../controllers/status_controller_test.exs | 2 +-
.../controllers/timeline_controller_test.exs | 26 +++++++++++++++-------
.../mastodon_api/views/notification_view_test.exs | 25 +++++++++++++++------
test/web/mastodon_api/views/status_view_test.exs | 14 +++++-------
5 files changed, 43 insertions(+), 28 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs
index db380f76a..e2d98ef3e 100644
--- a/test/web/mastodon_api/controllers/notification_controller_test.exs
+++ b/test/web/mastodon_api/controllers/notification_controller_test.exs
@@ -12,9 +12,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
import Pleroma.Factory
- test "does NOT render account/pleroma/relationship if this is disabled by default" do
- clear_config([:extensions, :output_relationships_in_statuses_by_default], false)
-
+ test "does NOT render account/pleroma/relationship by default" do
%{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user)
diff --git a/test/web/mastodon_api/controllers/status_controller_test.exs b/test/web/mastodon_api/controllers/status_controller_test.exs
index 85068edd0..00e026087 100644
--- a/test/web/mastodon_api/controllers/status_controller_test.exs
+++ b/test/web/mastodon_api/controllers/status_controller_test.exs
@@ -1058,7 +1058,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
end
test "bookmarks" do
- bookmarks_uri = "/api/v1/bookmarks?with_relationships=true"
+ bookmarks_uri = "/api/v1/bookmarks"
%{conn: conn} = oauth_access(["write:bookmarks", "read:bookmarks"])
author = insert(:user)
diff --git a/test/web/mastodon_api/controllers/timeline_controller_test.exs b/test/web/mastodon_api/controllers/timeline_controller_test.exs
index 06efdc901..b8bb83af7 100644
--- a/test/web/mastodon_api/controllers/timeline_controller_test.exs
+++ b/test/web/mastodon_api/controllers/timeline_controller_test.exs
@@ -20,12 +20,10 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
describe "home" do
setup do: oauth_access(["read:statuses"])
- test "does NOT render account/pleroma/relationship if this is disabled by default", %{
+ test "does NOT render account/pleroma/relationship by default", %{
user: user,
conn: conn
} do
- clear_config([:extensions, :output_relationships_in_statuses_by_default], false)
-
other_user = insert(:user)
{:ok, _} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
@@ -41,7 +39,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
end)
end
- test "the home timeline", %{user: user, conn: conn} do
+ test "embeds account relationships with `with_relationships=true`", %{user: user, conn: conn} do
uri = "/api/v1/timelines/home?with_relationships=true"
following = insert(:user, nickname: "followed")
@@ -69,13 +67,19 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
}
}
},
- "account" => %{"pleroma" => %{"relationship" => %{"following" => true}}}
+ "account" => %{
+ "pleroma" => %{
+ "relationship" => %{"following" => true}
+ }
+ }
},
%{
"content" => "post",
"account" => %{
"acct" => "followed",
- "pleroma" => %{"relationship" => %{"following" => true}}
+ "pleroma" => %{
+ "relationship" => %{"following" => true}
+ }
}
}
] = json_response(ret_conn, :ok)
@@ -95,13 +99,19 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
}
}
},
- "account" => %{"pleroma" => %{"relationship" => %{"following" => true}}}
+ "account" => %{
+ "pleroma" => %{
+ "relationship" => %{"following" => true}
+ }
+ }
},
%{
"content" => "post",
"account" => %{
"acct" => "followed",
- "pleroma" => %{"relationship" => %{"following" => true}}
+ "pleroma" => %{
+ "relationship" => %{"following" => true}
+ }
}
}
] = json_response(ret_conn, :ok)
diff --git a/test/web/mastodon_api/views/notification_view_test.exs b/test/web/mastodon_api/views/notification_view_test.exs
index c3ec9dfec..e1f9c3ac4 100644
--- a/test/web/mastodon_api/views/notification_view_test.exs
+++ b/test/web/mastodon_api/views/notification_view_test.exs
@@ -42,7 +42,12 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
id: to_string(notification.id),
pleroma: %{is_seen: false},
type: "mention",
- account: AccountView.render("show.json", %{user: user, for: mentioned_user}),
+ account:
+ AccountView.render("show.json", %{
+ user: user,
+ for: mentioned_user,
+ skip_relationships: true
+ }),
status: StatusView.render("show.json", %{activity: activity, for: mentioned_user}),
created_at: Utils.to_masto_date(notification.inserted_at)
}
@@ -62,7 +67,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
id: to_string(notification.id),
pleroma: %{is_seen: false},
type: "favourite",
- account: AccountView.render("show.json", %{user: another_user, for: user}),
+ account:
+ AccountView.render("show.json", %{user: another_user, for: user, skip_relationships: true}),
status: StatusView.render("show.json", %{activity: create_activity, for: user}),
created_at: Utils.to_masto_date(notification.inserted_at)
}
@@ -82,7 +88,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
id: to_string(notification.id),
pleroma: %{is_seen: false},
type: "reblog",
- account: AccountView.render("show.json", %{user: another_user, for: user}),
+ account:
+ AccountView.render("show.json", %{user: another_user, for: user, skip_relationships: true}),
status: StatusView.render("show.json", %{activity: reblog_activity, for: user}),
created_at: Utils.to_masto_date(notification.inserted_at)
}
@@ -100,7 +107,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
id: to_string(notification.id),
pleroma: %{is_seen: false},
type: "follow",
- account: AccountView.render("show.json", %{user: follower, for: followed}),
+ account:
+ AccountView.render("show.json", %{user: follower, for: followed, skip_relationships: true}),
created_at: Utils.to_masto_date(notification.inserted_at)
}
@@ -143,8 +151,10 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
id: to_string(notification.id),
pleroma: %{is_seen: false},
type: "move",
- account: AccountView.render("show.json", %{user: old_user, for: follower}),
- target: AccountView.render("show.json", %{user: new_user, for: follower}),
+ account:
+ AccountView.render("show.json", %{user: old_user, for: follower, skip_relationships: true}),
+ target:
+ AccountView.render("show.json", %{user: new_user, for: follower, skip_relationships: true}),
created_at: Utils.to_masto_date(notification.inserted_at)
}
@@ -169,7 +179,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
pleroma: %{is_seen: false},
type: "pleroma:emoji_reaction",
emoji: "☕",
- account: AccountView.render("show.json", %{user: other_user, for: user}),
+ account:
+ AccountView.render("show.json", %{user: other_user, for: user, skip_relationships: true}),
status: StatusView.render("show.json", %{activity: activity, for: user}),
created_at: Utils.to_masto_date(notification.inserted_at)
}
diff --git a/test/web/mastodon_api/views/status_view_test.exs b/test/web/mastodon_api/views/status_view_test.exs
index 6791c2fb0..91d4ded2c 100644
--- a/test/web/mastodon_api/views/status_view_test.exs
+++ b/test/web/mastodon_api/views/status_view_test.exs
@@ -555,7 +555,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
end
end
- test "embeds a relationship in the account" do
+ test "does not embed a relationship in the account" do
user = insert(:user)
other_user = insert(:user)
@@ -566,11 +566,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
result = StatusView.render("show.json", %{activity: activity, for: other_user})
- assert result[:account][:pleroma][:relationship] ==
- AccountView.render("relationship.json", %{user: other_user, target: user})
+ assert result[:account][:pleroma][:relationship] == %{}
end
- test "embeds a relationship in the account in reposts" do
+ test "does not embed a relationship in the account in reposts" do
user = insert(:user)
other_user = insert(:user)
@@ -583,11 +582,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
result = StatusView.render("show.json", %{activity: activity, for: user})
- assert result[:account][:pleroma][:relationship] ==
- AccountView.render("relationship.json", %{user: user, target: other_user})
-
- assert result[:reblog][:account][:pleroma][:relationship] ==
- AccountView.render("relationship.json", %{user: user, target: user})
+ assert result[:account][:pleroma][:relationship] == %{}
+ assert result[:reblog][:account][:pleroma][:relationship] == %{}
end
test "visibility/list" do
--
cgit v1.2.3
From e7b1df7252aed1f4d41a6f4a9bd13050b86e7009 Mon Sep 17 00:00:00 2001
From: rinpatch
Date: Fri, 1 May 2020 22:50:40 +0300
Subject: Fix sporadic test compilation failure caused by unused alias
---
test/web/mastodon_api/controllers/suggestion_controller_test.exs | 2 --
1 file changed, 2 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/suggestion_controller_test.exs b/test/web/mastodon_api/controllers/suggestion_controller_test.exs
index 8d0e70db8..f120bd0cd 100644
--- a/test/web/mastodon_api/controllers/suggestion_controller_test.exs
+++ b/test/web/mastodon_api/controllers/suggestion_controller_test.exs
@@ -5,8 +5,6 @@
defmodule Pleroma.Web.MastodonAPI.SuggestionControllerTest do
use Pleroma.Web.ConnCase
- alias Pleroma.Config
-
setup do: oauth_access(["read"])
test "returns empty result", %{conn: conn} do
--
cgit v1.2.3
From 2d07ed77477ba7b62b2cfc524f91829937e2fdb3 Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Sat, 2 May 2020 18:28:04 +0300
Subject: [#1732] Made AP C2S :followers and :following endpoints serve on no
auth (as for related :api pipeline endpoints).
---
test/web/activity_pub/activity_pub_controller_test.exs | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs
index 6b5913f95..a8f1f0e26 100644
--- a/test/web/activity_pub/activity_pub_controller_test.exs
+++ b/test/web/activity_pub/activity_pub_controller_test.exs
@@ -1055,12 +1055,12 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
assert result["totalItems"] == 15
end
- test "returns 403 if requester is not logged in", %{conn: conn} do
+ test "does not require authentication", %{conn: conn} do
user = insert(:user)
conn
|> get("/users/#{user.nickname}/followers")
- |> json_response(403)
+ |> json_response(200)
end
end
@@ -1152,12 +1152,12 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
assert result["totalItems"] == 15
end
- test "returns 403 if requester is not logged in", %{conn: conn} do
+ test "does not require authentication", %{conn: conn} do
user = insert(:user)
conn
|> get("/users/#{user.nickname}/following")
- |> json_response(403)
+ |> json_response(200)
end
end
--
cgit v1.2.3
From e55876409b523d81bc19db876bc90f29ba80a47c Mon Sep 17 00:00:00 2001
From: rinpatch
Date: Wed, 29 Apr 2020 14:26:31 +0300
Subject: Deactivate local users on deletion instead of deleting the record
Prevents the possibility of re-registration, which allowed to read
DMs of the deleted account.
Also includes a migration that tries to find any already deleted
accounts and insert skeletons for them.
Closes pleroma/pleroma#1687
---
test/tasks/user_test.exs | 2 +-
test/user_test.exs | 14 ++------------
test/web/activity_pub/transmogrifier_test.exs | 3 ++-
3 files changed, 5 insertions(+), 14 deletions(-)
(limited to 'test')
diff --git a/test/tasks/user_test.exs b/test/tasks/user_test.exs
index 8df835b56..0f6ffb2b1 100644
--- a/test/tasks/user_test.exs
+++ b/test/tasks/user_test.exs
@@ -92,7 +92,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do
assert_received {:mix_shell, :info, [message]}
assert message =~ " deleted"
- refute User.get_by_nickname(user.nickname)
+ assert %{deactivated: true} = User.get_by_nickname(user.nickname)
end
test "no user to delete" do
diff --git a/test/user_test.exs b/test/user_test.exs
index 347c5be72..bff337d3e 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -1135,16 +1135,7 @@ defmodule Pleroma.UserTest do
refute Activity.get_by_id(activity.id)
end
- test "it deletes deactivated user" do
- {:ok, user} = insert(:user, deactivated: true) |> User.set_cache()
-
- {:ok, job} = User.delete(user)
- {:ok, _user} = ObanHelpers.perform(job)
-
- refute User.get_by_id(user.id)
- end
-
- test "it deletes a user, all follow relationships and all activities", %{user: user} do
+ test "it deactivates a user, all follow relationships and all activities", %{user: user} do
follower = insert(:user)
{:ok, follower} = User.follow(follower, user)
@@ -1164,8 +1155,7 @@ defmodule Pleroma.UserTest do
follower = User.get_cached_by_id(follower.id)
refute User.following?(follower, user)
- refute User.get_by_id(user.id)
- assert {:ok, nil} == Cachex.get(:user_cache, "ap_id:#{user.ap_id}")
+ assert %{deactivated: true} = User.get_by_id(user.id)
user_activities =
user.ap_id
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 10d86ee45..36e1e7bd1 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -872,7 +872,8 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
@tag capture_log: true
test "it works for incoming user deletes" do
- %{ap_id: ap_id} = insert(:user, ap_id: "http://mastodon.example.org/users/admin")
+ %{ap_id: ap_id} =
+ insert(:user, ap_id: "http://mastodon.example.org/users/admin", local: false)
data =
File.read!("test/fixtures/mastodon-delete-user.json")
--
cgit v1.2.3
From 66a8e1312dc82fa755a635984f89a5314917d209 Mon Sep 17 00:00:00 2001
From: eugenijm
Date: Mon, 27 Apr 2020 17:41:38 +0300
Subject: Mastodon API: do not create a following relationship if the
corresponding follow request doesn't exist when calling `POST
/api/v1/follow_requests/:id/authorize`
---
test/web/common_api/common_api_test.exs | 8 ++++++++
1 file changed, 8 insertions(+)
(limited to 'test')
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index c6ccc02c4..bc0c1a791 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -697,6 +697,14 @@ defmodule Pleroma.Web.CommonAPITest do
assert Repo.get(Activity, follow_activity_two.id).data["state"] == "reject"
assert Repo.get(Activity, follow_activity_three.id).data["state"] == "pending"
end
+
+ test "doesn't create a following relationship if the corresponding follow request doesn't exist" do
+ user = insert(:user, locked: true)
+ not_follower = insert(:user)
+ CommonAPI.accept_follow_request(not_follower, user)
+
+ assert Pleroma.FollowingRelationship.following?(not_follower, user) == false
+ end
end
describe "vote/3" do
--
cgit v1.2.3
From 4dfc617cdf1c2579f4f941dcd0fa5c728178df06 Mon Sep 17 00:00:00 2001
From: lain
Date: Sun, 3 May 2020 12:51:28 +0200
Subject: Transmogrifier: Don't fetch actor that's guaranteed to be there.
---
.../transmogrifier/delete_handling_test.exs | 30 +++++-----------------
1 file changed, 6 insertions(+), 24 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier/delete_handling_test.exs b/test/web/activity_pub/transmogrifier/delete_handling_test.exs
index 64c908a05..c141e25bc 100644
--- a/test/web/activity_pub/transmogrifier/delete_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/delete_handling_test.exs
@@ -13,7 +13,6 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do
alias Pleroma.Web.ActivityPub.Transmogrifier
import Pleroma.Factory
- import ExUnit.CaptureLog
setup_all do
Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
@@ -27,22 +26,15 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do
data =
File.read!("test/fixtures/mastodon-delete.json")
|> Poison.decode!()
-
- object =
- data["object"]
- |> Map.put("id", activity.data["object"])
-
- data =
- data
- |> Map.put("object", object)
|> Map.put("actor", deleting_user.ap_id)
+ |> put_in(["object", "id"], activity.data["object"])
{:ok, %Activity{actor: actor, local: false, data: %{"id" => id}}} =
Transmogrifier.handle_incoming(data)
assert id == data["id"]
- # We delete the Create activity because base our timelines on it.
+ # We delete the Create activity because we base our timelines on it.
# This should be changed after we unify objects and activities
refute Activity.get_by_id(activity.id)
assert actor == deleting_user.ap_id
@@ -54,25 +46,15 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do
test "it fails for incoming deletes with spoofed origin" do
activity = insert(:note_activity)
+ %{ap_id: ap_id} = insert(:user, ap_id: "https://gensokyo.2hu/users/raymoo")
data =
File.read!("test/fixtures/mastodon-delete.json")
|> Poison.decode!()
+ |> Map.put("actor", ap_id)
+ |> put_in(["object", "id"], activity.data["object"])
- object =
- data["object"]
- |> Map.put("id", activity.data["object"])
-
- data =
- data
- |> Map.put("object", object)
-
- assert capture_log(fn ->
- {:error, _} = Transmogrifier.handle_incoming(data)
- end) =~
- "[error] Could not decode user at fetch http://mastodon.example.org/users/gargron, {:error, :nxdomain}"
-
- assert Activity.get_by_id(activity.id)
+ assert match?({:error, _}, Transmogrifier.handle_incoming(data))
end
@tag capture_log: true
--
cgit v1.2.3
From 6c337489f4db28f78be940bef01ef3a80e279ffc Mon Sep 17 00:00:00 2001
From: lain
Date: Sun, 3 May 2020 13:01:19 +0200
Subject: Various testing fixes in relation to user deletion.
---
test/web/activity_pub/side_effects_test.exs | 2 +-
test/web/activity_pub/transmogrifier/delete_handling_test.exs | 2 +-
test/web/admin_api/admin_api_controller_test.exs | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index ce34eed4c..a9598d7b3 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -68,7 +68,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
{:ok, _delete, _} = SideEffects.handle(delete)
ObanHelpers.perform_all()
- refute User.get_cached_by_ap_id(user.ap_id)
+ assert User.get_cached_by_ap_id(user.ap_id).deactivated
end
end
diff --git a/test/web/activity_pub/transmogrifier/delete_handling_test.exs b/test/web/activity_pub/transmogrifier/delete_handling_test.exs
index c141e25bc..f235a8e63 100644
--- a/test/web/activity_pub/transmogrifier/delete_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/delete_handling_test.exs
@@ -68,7 +68,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do
{:ok, _} = Transmogrifier.handle_incoming(data)
ObanHelpers.perform_all()
- refute User.get_cached_by_ap_id(ap_id)
+ assert User.get_cached_by_ap_id(ap_id).deactivated
end
test "it fails for incoming user deletes with spoofed origin" do
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index bf054a12e..0daf29ffb 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -156,7 +156,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
ObanHelpers.perform_all()
- refute User.get_by_nickname(user.nickname)
+ assert User.get_by_nickname(user.nickname).deactivated
log_entry = Repo.one(ModerationLog)
--
cgit v1.2.3
From a7966f2080a0e9b3c2b35efa7ea647c1bdef2a2d Mon Sep 17 00:00:00 2001
From: lain
Date: Sun, 3 May 2020 13:48:01 +0200
Subject: Webfinger: Request account info with the acct scheme
---
test/support/http_request_mock.ex | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
(limited to 'test')
diff --git a/test/support/http_request_mock.ex b/test/support/http_request_mock.ex
index 9624cb0f7..3a95e92da 100644
--- a/test/support/http_request_mock.ex
+++ b/test/support/http_request_mock.ex
@@ -211,7 +211,7 @@ defmodule HttpRequestMock do
end
def get(
- "https://squeet.me/xrd/?uri=lain@squeet.me",
+ "https://squeet.me/xrd/?uri=acct:lain@squeet.me",
_,
_,
[{"accept", "application/xrd+xml,application/jrd+json"}]
@@ -870,7 +870,7 @@ defmodule HttpRequestMock do
end
def get(
- "https://social.heldscal.la/.well-known/webfinger?resource=shp@social.heldscal.la",
+ "https://social.heldscal.la/.well-known/webfinger?resource=acct:shp@social.heldscal.la",
_,
_,
[{"accept", "application/xrd+xml,application/jrd+json"}]
@@ -883,7 +883,7 @@ defmodule HttpRequestMock do
end
def get(
- "https://social.heldscal.la/.well-known/webfinger?resource=invalid_content@social.heldscal.la",
+ "https://social.heldscal.la/.well-known/webfinger?resource=acct:invalid_content@social.heldscal.la",
_,
_,
[{"accept", "application/xrd+xml,application/jrd+json"}]
@@ -900,7 +900,7 @@ defmodule HttpRequestMock do
end
def get(
- "http://framatube.org/main/xrd?uri=framasoft@framatube.org",
+ "http://framatube.org/main/xrd?uri=acct:framasoft@framatube.org",
_,
_,
[{"accept", "application/xrd+xml,application/jrd+json"}]
@@ -959,7 +959,7 @@ defmodule HttpRequestMock do
end
def get(
- "https://gerzilla.de/xrd/?uri=kaniini@gerzilla.de",
+ "https://gerzilla.de/xrd/?uri=acct:kaniini@gerzilla.de",
_,
_,
[{"accept", "application/xrd+xml,application/jrd+json"}]
@@ -1155,7 +1155,7 @@ defmodule HttpRequestMock do
end
def get(
- "https://zetsubou.xn--q9jyb4c/.well-known/webfinger?resource=lain@zetsubou.xn--q9jyb4c",
+ "https://zetsubou.xn--q9jyb4c/.well-known/webfinger?resource=acct:lain@zetsubou.xn--q9jyb4c",
_,
_,
[{"accept", "application/xrd+xml,application/jrd+json"}]
@@ -1168,7 +1168,7 @@ defmodule HttpRequestMock do
end
def get(
- "https://zetsubou.xn--q9jyb4c/.well-known/webfinger?resource=https://zetsubou.xn--q9jyb4c/users/lain",
+ "https://zetsubou.xn--q9jyb4c/.well-known/webfinger?resource=acct:https://zetsubou.xn--q9jyb4c/users/lain",
_,
_,
[{"accept", "application/xrd+xml,application/jrd+json"}]
--
cgit v1.2.3
From ec24c70db80665aaaf4d7794ea62e9f9e6676bec Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 4 May 2020 14:22:54 +0200
Subject: ActivityPub: Don't fetch `Application` follower counts.
---
test/web/activity_pub/activity_pub_test.exs | 50 ++++++++++++++++++++++++++++-
1 file changed, 49 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index edd7dfb22..84ead93bb 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -18,9 +18,10 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.Federator
+ import ExUnit.CaptureLog
+ import Mock
import Pleroma.Factory
import Tesla.Mock
- import Mock
setup do
mock(fn env -> apply(HttpRequestMock, :request, [env]) end)
@@ -2403,4 +2404,51 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
u3: %{r1: r3_1.id, r2: r3_2.id},
u4: %{r1: r4_1.id}}
end
+
+ describe "maybe_update_follow_information/1" do
+ setup do
+ clear_config([:instance, :external_user_synchronization], true)
+
+ user = %{
+ local: false,
+ ap_id: "https://gensokyo.2hu/users/raymoo",
+ following_address: "https://gensokyo.2hu/users/following",
+ follower_address: "https://gensokyo.2hu/users/followers",
+ type: "Person"
+ }
+
+ %{user: user}
+ end
+
+ test "logs an error when it can't fetch the info", %{user: user} do
+ assert capture_log(fn ->
+ ActivityPub.maybe_update_follow_information(user)
+ end) =~ "Follower/Following counter update for #{user.ap_id} failed"
+ end
+
+ test "just returns the input if the user type is Application", %{
+ user: user
+ } do
+ user =
+ user
+ |> Map.put(:type, "Application")
+
+ refute capture_log(fn ->
+ assert ^user = ActivityPub.maybe_update_follow_information(user)
+ end) =~ "Follower/Following counter update for #{user.ap_id} failed"
+ end
+
+ test "it just returns the input if the user has no following/follower addresses", %{
+ user: user
+ } do
+ user =
+ user
+ |> Map.put(:following_address, nil)
+ |> Map.put(:follower_address, nil)
+
+ refute capture_log(fn ->
+ assert ^user = ActivityPub.maybe_update_follow_information(user)
+ end) =~ "Follower/Following counter update for #{user.ap_id} failed"
+ end
+ end
end
--
cgit v1.2.3
From 335aabc39c6384216d2eaa3036cea541141d8025 Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 4 May 2020 14:45:28 +0200
Subject: Transmogrifier tests: Extract like tests.
---
test/support/factory.ex | 1 +
.../transmogrifier/like_handling_test.exs | 78 ++++++++++++++++++++++
test/web/activity_pub/transmogrifier_test.exs | 56 ----------------
3 files changed, 79 insertions(+), 56 deletions(-)
create mode 100644 test/web/activity_pub/transmogrifier/like_handling_test.exs
(limited to 'test')
diff --git a/test/support/factory.ex b/test/support/factory.ex
index f0b797fd4..495764782 100644
--- a/test/support/factory.ex
+++ b/test/support/factory.ex
@@ -32,6 +32,7 @@ defmodule Pleroma.Factory do
password_hash: Comeonin.Pbkdf2.hashpwsalt("test"),
bio: sequence(:bio, &"Tester Number #{&1}"),
last_digest_emailed_at: NaiveDateTime.utc_now(),
+ last_refreshed_at: NaiveDateTime.utc_now(),
notification_settings: %Pleroma.User.NotificationSetting{}
}
diff --git a/test/web/activity_pub/transmogrifier/like_handling_test.exs b/test/web/activity_pub/transmogrifier/like_handling_test.exs
new file mode 100644
index 000000000..54a5c1dbc
--- /dev/null
+++ b/test/web/activity_pub/transmogrifier/like_handling_test.exs
@@ -0,0 +1,78 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.Transmogrifier.LikeHandlingTest do
+ use Pleroma.DataCase
+
+ alias Pleroma.Activity
+ alias Pleroma.Web.ActivityPub.Transmogrifier
+ alias Pleroma.Web.CommonAPI
+
+ import Pleroma.Factory
+
+ test "it works for incoming likes" do
+ user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+
+ data =
+ File.read!("test/fixtures/mastodon-like.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+
+ _actor = insert(:user, ap_id: data["actor"], local: false)
+
+ {:ok, %Activity{data: data, local: false} = activity} = Transmogrifier.handle_incoming(data)
+
+ refute Enum.empty?(activity.recipients)
+
+ assert data["actor"] == "http://mastodon.example.org/users/admin"
+ assert data["type"] == "Like"
+ assert data["id"] == "http://mastodon.example.org/users/admin#likes/2"
+ assert data["object"] == activity.data["object"]
+ end
+
+ test "it works for incoming misskey likes, turning them into EmojiReacts" do
+ user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+
+ data =
+ File.read!("test/fixtures/misskey-like.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+
+ _actor = insert(:user, ap_id: data["actor"], local: false)
+
+ {:ok, %Activity{data: activity_data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert activity_data["actor"] == data["actor"]
+ assert activity_data["type"] == "EmojiReact"
+ assert activity_data["id"] == data["id"]
+ assert activity_data["object"] == activity.data["object"]
+ assert activity_data["content"] == "🍮"
+ end
+
+ test "it works for incoming misskey likes that contain unicode emojis, turning them into EmojiReacts" do
+ user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+
+ data =
+ File.read!("test/fixtures/misskey-like.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+ |> Map.put("_misskey_reaction", "⭐")
+
+ _actor = insert(:user, ap_id: data["actor"], local: false)
+
+ {:ok, %Activity{data: activity_data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert activity_data["actor"] == data["actor"]
+ assert activity_data["type"] == "EmojiReact"
+ assert activity_data["id"] == data["id"]
+ assert activity_data["object"] == activity.data["object"]
+ assert activity_data["content"] == "⭐"
+ end
+end
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 36e1e7bd1..23efa4be6 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -325,62 +325,6 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert object_data["cc"] == to
end
- test "it works for incoming likes" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
-
- data =
- File.read!("test/fixtures/mastodon-like.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- {:ok, %Activity{data: data, local: false} = activity} = Transmogrifier.handle_incoming(data)
-
- refute Enum.empty?(activity.recipients)
-
- assert data["actor"] == "http://mastodon.example.org/users/admin"
- assert data["type"] == "Like"
- assert data["id"] == "http://mastodon.example.org/users/admin#likes/2"
- assert data["object"] == activity.data["object"]
- end
-
- test "it works for incoming misskey likes, turning them into EmojiReacts" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
-
- data =
- File.read!("test/fixtures/misskey-like.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == data["actor"]
- assert data["type"] == "EmojiReact"
- assert data["id"] == data["id"]
- assert data["object"] == activity.data["object"]
- assert data["content"] == "🍮"
- end
-
- test "it works for incoming misskey likes that contain unicode emojis, turning them into EmojiReacts" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
-
- data =
- File.read!("test/fixtures/misskey-like.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
- |> Map.put("_misskey_reaction", "⭐")
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == data["actor"]
- assert data["type"] == "EmojiReact"
- assert data["id"] == data["id"]
- assert data["object"] == activity.data["object"]
- assert data["content"] == "⭐"
- end
-
test "it works for incoming emoji reactions" do
user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
--
cgit v1.2.3
From e03c301ebeea6687ee7f19d447232864b182d581 Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 4 May 2020 17:08:31 +0200
Subject: LikeValidator: Fix up missing recipients.
---
test/web/activity_pub/object_validator_test.exs | 13 +++++++++++++
1 file changed, 13 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 3c5c3696e..9e9e41c6b 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -36,6 +36,19 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
assert LikeValidator.cast_and_validate(valid_like).valid?
end
+ test "sets the 'to' field to the object actor if no recipients are given", %{
+ valid_like: valid_like,
+ user: user
+ } do
+ without_recipients =
+ valid_like
+ |> Map.delete("to")
+
+ {:ok, object, _meta} = ObjectValidator.validate(without_recipients, [])
+
+ assert object["to"] == [user.ap_id]
+ end
+
test "it errors when the actor is missing or not known", %{valid_like: valid_like} do
without_actor = Map.delete(valid_like, "actor")
--
cgit v1.2.3
From 0f9bed022fab80f59353597dde82896ef954a678 Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 4 May 2020 17:18:17 +0200
Subject: LikeValidator: Fix up context.
---
test/web/activity_pub/object_validator_test.exs | 13 +++++++++++++
1 file changed, 13 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 9e9e41c6b..93989e28a 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -49,6 +49,19 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
assert object["to"] == [user.ap_id]
end
+ test "sets the context field to the context of the object if no context is given", %{
+ valid_like: valid_like,
+ post_activity: post_activity
+ } do
+ without_context =
+ valid_like
+ |> Map.delete("context")
+
+ {:ok, object, _meta} = ObjectValidator.validate(without_context, [])
+
+ assert object["context"] == post_activity.data["context"]
+ end
+
test "it errors when the actor is missing or not known", %{valid_like: valid_like} do
without_actor = Map.delete(valid_like, "actor")
--
cgit v1.2.3
From bf0e41f0daa5809db53ed4a9130ade63952e8da0 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Mon, 4 May 2020 23:32:53 +0200
Subject: Transmogrifier.set_sensitive/1: Keep sensitive set to true
---
.../activity_pub/activity_pub_controller_test.exs | 22 +++++++++++++++-------
1 file changed, 15 insertions(+), 7 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs
index a8f1f0e26..5c8d20ac4 100644
--- a/test/web/activity_pub/activity_pub_controller_test.exs
+++ b/test/web/activity_pub/activity_pub_controller_test.exs
@@ -820,21 +820,29 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
activity: activity
} do
user = insert(:user)
+ conn = assign(conn, :user, user)
object = Map.put(activity["object"], "sensitive", true)
activity = Map.put(activity, "object", object)
- result =
+ response =
conn
- |> assign(:user, user)
|> put_req_header("content-type", "application/activity+json")
|> post("/users/#{user.nickname}/outbox", activity)
|> json_response(201)
- assert Activity.get_by_ap_id(result["id"])
- assert result["object"]
- assert %Object{data: object} = Object.normalize(result["object"])
- assert object["sensitive"] == activity["object"]["sensitive"]
- assert object["content"] == activity["object"]["content"]
+ assert Activity.get_by_ap_id(response["id"])
+ assert response["object"]
+ assert %Object{data: response_object} = Object.normalize(response["object"])
+ assert response_object["sensitive"] == true
+ assert response_object["content"] == activity["object"]["content"]
+
+ representation =
+ conn
+ |> put_req_header("accept", "application/activity+json")
+ |> get(response["id"])
+ |> json_response(200)
+
+ assert representation["object"]["sensitive"] == true
end
test "it rejects an incoming activity with bogus type", %{conn: conn, activity: activity} do
--
cgit v1.2.3
From 8bed6ea922dbc1cfb8166fea6ce344d3618b3d52 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 09:25:09 +0200
Subject: User, Webfinger: Remove OStatus vestiges
Mainly the `magic_key` field
---
test/web/web_finger/web_finger_test.exs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/web_finger/web_finger_test.exs b/test/web/web_finger/web_finger_test.exs
index 4b4282727..ce17f83d6 100644
--- a/test/web/web_finger/web_finger_test.exs
+++ b/test/web/web_finger/web_finger_test.exs
@@ -67,10 +67,10 @@ defmodule Pleroma.Web.WebFingerTest do
assert data["magic_key"] == nil
assert data["salmon"] == nil
- assert data["topic"] == "https://mstdn.jp/users/kPherox.atom"
+ assert data["topic"] == nil
assert data["subject"] == "acct:kPherox@mstdn.jp"
assert data["ap_id"] == "https://mstdn.jp/users/kPherox"
- assert data["subscribe_address"] == "https://mstdn.jp/authorize_interaction?acct={uri}"
+ assert data["subscribe_address"] == nil
end
test "it works for friendica" do
--
cgit v1.2.3
From 6a2905ccf08f89bd988b1bcd0788566930fbf17e Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 09:55:33 +0200
Subject: WebFinger Test: Add back test.
---
test/web/web_finger/web_finger_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/web_finger/web_finger_test.exs b/test/web/web_finger/web_finger_test.exs
index ce17f83d6..f4884e0a2 100644
--- a/test/web/web_finger/web_finger_test.exs
+++ b/test/web/web_finger/web_finger_test.exs
@@ -70,7 +70,7 @@ defmodule Pleroma.Web.WebFingerTest do
assert data["topic"] == nil
assert data["subject"] == "acct:kPherox@mstdn.jp"
assert data["ap_id"] == "https://mstdn.jp/users/kPherox"
- assert data["subscribe_address"] == nil
+ assert data["subscribe_address"] == "https://mstdn.jp/authorize_interaction?acct={uri}"
end
test "it works for friendica" do
--
cgit v1.2.3
From 6400998820084c7b81a53bbeb705b0eb2c0a0e1b Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 10:12:37 +0200
Subject: AP C2S: Restrict creation to `Note`s for now.
---
test/web/activity_pub/activity_pub_controller_test.exs | 15 +++++++++++++++
1 file changed, 15 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs
index a8f1f0e26..9a085ffc5 100644
--- a/test/web/activity_pub/activity_pub_controller_test.exs
+++ b/test/web/activity_pub/activity_pub_controller_test.exs
@@ -815,6 +815,21 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
assert object["content"] == activity["object"]["content"]
end
+ test "it rejects anything beyond 'Note' creations", %{conn: conn, activity: activity} do
+ user = insert(:user)
+
+ activity =
+ activity
+ |> put_in(["object", "type"], "Benis")
+
+ _result =
+ conn
+ |> assign(:user, user)
+ |> put_req_header("content-type", "application/activity+json")
+ |> post("/users/#{user.nickname}/outbox", activity)
+ |> json_response(400)
+ end
+
test "it inserts an incoming sensitive activity into the database", %{
conn: conn,
activity: activity
--
cgit v1.2.3
From 142bf0957c64f76b9b511200544b1ccbcef5ba16 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 11:20:53 +0200
Subject: Transmogrifier: Extract EmojiReact tests.
---
.../transmogrifier/emoji_react_handling_test.exs | 55 ++++++++++++++++++++++
test/web/activity_pub/transmogrifier_test.exs | 37 ---------------
2 files changed, 55 insertions(+), 37 deletions(-)
create mode 100644 test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs b/test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs
new file mode 100644
index 000000000..9f4f6b296
--- /dev/null
+++ b/test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs
@@ -0,0 +1,55 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.Transmogrifier.EmojiReactHandlingTest do
+ use Pleroma.DataCase
+
+ alias Pleroma.Activity
+ alias Pleroma.Web.ActivityPub.Transmogrifier
+ alias Pleroma.Web.CommonAPI
+
+ import Pleroma.Factory
+
+ test "it works for incoming emoji reactions" do
+ user = insert(:user)
+ other_user = insert(:user, local: false)
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+
+ data =
+ File.read!("test/fixtures/emoji-reaction.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+ |> Map.put("actor", other_user.ap_id)
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert data["actor"] == other_user.ap_id
+ assert data["type"] == "EmojiReact"
+ assert data["id"] == "http://mastodon.example.org/users/admin#reactions/2"
+ assert data["object"] == activity.data["object"]
+ assert data["content"] == "👌"
+ end
+
+ test "it reject invalid emoji reactions" do
+ user = insert(:user)
+ other_user = insert(:user, local: false)
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+
+ data =
+ File.read!("test/fixtures/emoji-reaction-too-long.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+ |> Map.put("actor", other_user.ap_id)
+
+ assert :error = Transmogrifier.handle_incoming(data)
+
+ data =
+ File.read!("test/fixtures/emoji-reaction-no-emoji.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+ |> Map.put("actor", other_user.ap_id)
+
+ assert :error = Transmogrifier.handle_incoming(data)
+ end
+end
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 23efa4be6..c1c3ff9d2 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -325,43 +325,6 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert object_data["cc"] == to
end
- test "it works for incoming emoji reactions" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
-
- data =
- File.read!("test/fixtures/emoji-reaction.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == "http://mastodon.example.org/users/admin"
- assert data["type"] == "EmojiReact"
- assert data["id"] == "http://mastodon.example.org/users/admin#reactions/2"
- assert data["object"] == activity.data["object"]
- assert data["content"] == "👌"
- end
-
- test "it reject invalid emoji reactions" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
-
- data =
- File.read!("test/fixtures/emoji-reaction-too-long.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- assert :error = Transmogrifier.handle_incoming(data)
-
- data =
- File.read!("test/fixtures/emoji-reaction-no-emoji.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- assert :error = Transmogrifier.handle_incoming(data)
- end
-
test "it works for incoming emoji reaction undos" do
user = insert(:user)
--
cgit v1.2.3
From ad771546d886171ea8c3e7694fad393eaa5a2017 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 12:11:46 +0200
Subject: Transmogrifier: Move emoji reactions to common pipeline.
---
test/web/activity_pub/object_validator_test.exs | 41 ++++++++++++++++++++++
test/web/activity_pub/side_effects_test.exs | 27 ++++++++++++++
.../transmogrifier/emoji_react_handling_test.exs | 10 ++++--
3 files changed, 76 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 93989e28a..a7ad8e646 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -1,6 +1,7 @@
defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
use Pleroma.DataCase
+ alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.ObjectValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator
alias Pleroma.Web.ActivityPub.Utils
@@ -8,6 +9,46 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
import Pleroma.Factory
+ describe "EmojiReacts" do
+ setup do
+ user = insert(:user)
+ {:ok, post_activity} = CommonAPI.post(user, %{"status" => "uguu"})
+
+ object = Pleroma.Object.get_by_ap_id(post_activity.data["object"])
+
+ {:ok, valid_emoji_react, []} = Builder.emoji_react(user, object, "👌")
+
+ %{user: user, post_activity: post_activity, valid_emoji_react: valid_emoji_react}
+ end
+
+ test "it validates a valid EmojiReact", %{valid_emoji_react: valid_emoji_react} do
+ assert {:ok, _, _} = ObjectValidator.validate(valid_emoji_react, [])
+ end
+
+ test "it is not valid without a 'content' field", %{valid_emoji_react: valid_emoji_react} do
+ without_content =
+ valid_emoji_react
+ |> Map.delete("content")
+
+ {:error, cng} = ObjectValidator.validate(without_content, [])
+
+ refute cng.valid?
+ assert {:content, {"can't be blank", [validation: :required]}} in cng.errors
+ end
+
+ test "it is not valid with a non-emoji content field", %{valid_emoji_react: valid_emoji_react} do
+ without_emoji_content =
+ valid_emoji_react
+ |> Map.put("content", "x")
+
+ {:error, cng} = ObjectValidator.validate(without_emoji_content, [])
+
+ refute cng.valid?
+
+ assert {:content, {"must be a single character emoji", []}} in cng.errors
+ end
+ end
+
describe "likes" do
setup do
user = insert(:user)
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index 0b6b55156..9271d5ba1 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -15,6 +15,33 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
import Pleroma.Factory
+ describe "EmojiReact objects" do
+ setup do
+ poster = insert(:user)
+ user = insert(:user)
+
+ {:ok, post} = CommonAPI.post(poster, %{"status" => "hey"})
+
+ {:ok, emoji_react_data, []} = Builder.emoji_react(user, post.object, "👌")
+ {:ok, emoji_react, _meta} = ActivityPub.persist(emoji_react_data, local: true)
+
+ %{emoji_react: emoji_react, user: user, poster: poster}
+ end
+
+ test "adds the reaction to the object", %{emoji_react: emoji_react, user: user} do
+ {:ok, emoji_react, _} = SideEffects.handle(emoji_react)
+ object = Object.get_by_ap_id(emoji_react.data["object"])
+
+ assert object.data["reaction_count"] == 1
+ assert ["👌", [user.ap_id]] in object.data["reactions"]
+ end
+
+ test "creates a notification", %{emoji_react: emoji_react, poster: poster} do
+ {:ok, emoji_react, _} = SideEffects.handle(emoji_react)
+ assert Repo.get_by(Notification, user_id: poster.id, activity_id: emoji_react.id)
+ end
+ end
+
describe "like objects" do
setup do
poster = insert(:user)
diff --git a/test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs b/test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs
index 9f4f6b296..6988e3e0a 100644
--- a/test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs
@@ -6,6 +6,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.EmojiReactHandlingTest do
use Pleroma.DataCase
alias Pleroma.Activity
+ alias Pleroma.Object
alias Pleroma.Web.ActivityPub.Transmogrifier
alias Pleroma.Web.CommonAPI
@@ -29,6 +30,11 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.EmojiReactHandlingTest do
assert data["id"] == "http://mastodon.example.org/users/admin#reactions/2"
assert data["object"] == activity.data["object"]
assert data["content"] == "👌"
+
+ object = Object.get_by_ap_id(data["object"])
+
+ assert object.data["reaction_count"] == 1
+ assert match?([["👌", _]], object.data["reactions"])
end
test "it reject invalid emoji reactions" do
@@ -42,7 +48,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.EmojiReactHandlingTest do
|> Map.put("object", activity.data["object"])
|> Map.put("actor", other_user.ap_id)
- assert :error = Transmogrifier.handle_incoming(data)
+ assert {:error, _} = Transmogrifier.handle_incoming(data)
data =
File.read!("test/fixtures/emoji-reaction-no-emoji.json")
@@ -50,6 +56,6 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.EmojiReactHandlingTest do
|> Map.put("object", activity.data["object"])
|> Map.put("actor", other_user.ap_id)
- assert :error = Transmogrifier.handle_incoming(data)
+ assert {:error, _} = Transmogrifier.handle_incoming(data)
end
end
--
cgit v1.2.3
From db55dc944581b1d4b50d1608b2e991050ea29bb3 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 12:28:28 +0200
Subject: ActivityPub: Remove `react_with_emoji`.
---
test/notification_test.exs | 2 +-
test/web/activity_pub/activity_pub_test.exs | 71 +---------------------
test/web/activity_pub/transmogrifier_test.exs | 4 +-
test/web/common_api/common_api_test.exs | 4 +-
.../mastodon_api/views/notification_view_test.exs | 2 +-
test/web/mastodon_api/views/status_view_test.exs | 6 +-
.../controllers/pleroma_api_controller_test.exs | 10 +--
7 files changed, 17 insertions(+), 82 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 601a6c0ca..bd562c85c 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -24,7 +24,7 @@ defmodule Pleroma.NotificationTest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "yeah"})
- {:ok, activity, _object} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
+ {:ok, activity} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
{:ok, [notification]} = Notification.create_notifications(activity)
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 84ead93bb..1ac4f9896 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -874,71 +874,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
end
end
- describe "react to an object" do
- test_with_mock "sends an activity to federation", Federator, [:passthrough], [] do
- Config.put([:instance, :federating], true)
- user = insert(:user)
- reactor = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "YASSSS queen slay"})
- assert object = Object.normalize(activity)
-
- {:ok, reaction_activity, _object} = ActivityPub.react_with_emoji(reactor, object, "🔥")
-
- assert called(Federator.publish(reaction_activity))
- end
-
- test "adds an emoji reaction activity to the db" do
- user = insert(:user)
- reactor = insert(:user)
- third_user = insert(:user)
- fourth_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "YASSSS queen slay"})
- assert object = Object.normalize(activity)
-
- {:ok, reaction_activity, object} = ActivityPub.react_with_emoji(reactor, object, "🔥")
-
- assert reaction_activity
-
- assert reaction_activity.data["actor"] == reactor.ap_id
- assert reaction_activity.data["type"] == "EmojiReact"
- assert reaction_activity.data["content"] == "🔥"
- assert reaction_activity.data["object"] == object.data["id"]
- assert reaction_activity.data["to"] == [User.ap_followers(reactor), activity.data["actor"]]
- assert reaction_activity.data["context"] == object.data["context"]
- assert object.data["reaction_count"] == 1
- assert object.data["reactions"] == [["🔥", [reactor.ap_id]]]
-
- {:ok, _reaction_activity, object} = ActivityPub.react_with_emoji(third_user, object, "☕")
-
- assert object.data["reaction_count"] == 2
- assert object.data["reactions"] == [["🔥", [reactor.ap_id]], ["☕", [third_user.ap_id]]]
-
- {:ok, _reaction_activity, object} = ActivityPub.react_with_emoji(fourth_user, object, "🔥")
-
- assert object.data["reaction_count"] == 3
-
- assert object.data["reactions"] == [
- ["🔥", [fourth_user.ap_id, reactor.ap_id]],
- ["☕", [third_user.ap_id]]
- ]
- end
-
- test "reverts emoji reaction on error" do
- [user, reactor] = insert_list(2, :user)
-
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Status"})
- object = Object.normalize(activity)
-
- with_mock(Utils, [:passthrough], maybe_federate: fn _ -> {:error, :reverted} end) do
- assert {:error, :reverted} = ActivityPub.react_with_emoji(reactor, object, "😀")
- end
-
- object = Object.get_by_ap_id(object.data["id"])
- refute object.data["reaction_count"]
- refute object.data["reactions"]
- end
- end
-
describe "unreacting to an object" do
test_with_mock "sends an activity to federation", Federator, [:passthrough], [] do
Config.put([:instance, :federating], true)
@@ -947,7 +882,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, activity} = CommonAPI.post(user, %{"status" => "YASSSS queen slay"})
assert object = Object.normalize(activity)
- {:ok, reaction_activity, _object} = ActivityPub.react_with_emoji(reactor, object, "🔥")
+ {:ok, reaction_activity} = CommonAPI.react_with_emoji(activity.id, reactor, "🔥")
assert called(Federator.publish(reaction_activity))
@@ -963,7 +898,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, activity} = CommonAPI.post(user, %{"status" => "YASSSS queen slay"})
assert object = Object.normalize(activity)
- {:ok, reaction_activity, _object} = ActivityPub.react_with_emoji(reactor, object, "🔥")
+ {:ok, reaction_activity} = CommonAPI.react_with_emoji(activity.id, reactor, "🔥")
{:ok, unreaction_activity, _object} =
ActivityPub.unreact_with_emoji(reactor, reaction_activity.data["id"])
@@ -981,7 +916,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, activity} = CommonAPI.post(user, %{"status" => "Status"})
object = Object.normalize(activity)
- {:ok, reaction_activity, _object} = ActivityPub.react_with_emoji(reactor, object, "😀")
+ {:ok, reaction_activity} = CommonAPI.react_with_emoji(activity.id, reactor, "😀")
with_mock(Utils, [:passthrough], maybe_federate: fn _ -> {:error, :reverted} end) do
assert {:error, :reverted} =
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index c1c3ff9d2..7deac2909 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -329,7 +329,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
- {:ok, reaction_activity, _object} = CommonAPI.react_with_emoji(activity.id, user, "👌")
+ {:ok, reaction_activity} = CommonAPI.react_with_emoji(activity.id, user, "👌")
data =
File.read!("test/fixtures/mastodon-undo-like.json")
@@ -562,7 +562,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "it strips internal reactions" do
user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
- {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, user, "📢")
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, user, "📢")
%{object: object} = Activity.get_by_id_with_object(activity.id)
assert Map.has_key?(object.data, "reactions")
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index bc0c1a791..74171fcd9 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -278,7 +278,7 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
- {:ok, reaction, _} = CommonAPI.react_with_emoji(activity.id, user, "👍")
+ {:ok, reaction} = CommonAPI.react_with_emoji(activity.id, user, "👍")
assert reaction.data["actor"] == user.ap_id
assert reaction.data["content"] == "👍"
@@ -293,7 +293,7 @@ defmodule Pleroma.Web.CommonAPITest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
- {:ok, reaction, _} = CommonAPI.react_with_emoji(activity.id, user, "👍")
+ {:ok, reaction} = CommonAPI.react_with_emoji(activity.id, user, "👍")
{:ok, unreaction, _} = CommonAPI.unreact_with_emoji(activity.id, user, "👍")
diff --git a/test/web/mastodon_api/views/notification_view_test.exs b/test/web/mastodon_api/views/notification_view_test.exs
index c3ec9dfec..0806269a2 100644
--- a/test/web/mastodon_api/views/notification_view_test.exs
+++ b/test/web/mastodon_api/views/notification_view_test.exs
@@ -156,7 +156,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
- {:ok, _activity, _} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
+ {:ok, _activity} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
activity = Repo.get(Activity, activity.id)
diff --git a/test/web/mastodon_api/views/status_view_test.exs b/test/web/mastodon_api/views/status_view_test.exs
index 6791c2fb0..b64370c3f 100644
--- a/test/web/mastodon_api/views/status_view_test.exs
+++ b/test/web/mastodon_api/views/status_view_test.exs
@@ -32,9 +32,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
third_user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "dae cofe??"})
- {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, user, "☕")
- {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, third_user, "🍵")
- {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, user, "☕")
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, third_user, "🍵")
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
activity = Repo.get(Activity, activity.id)
status = StatusView.render("show.json", activity: activity)
diff --git a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
index 61a1689b9..593aa92b2 100644
--- a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
@@ -41,7 +41,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
- {:ok, activity, _object} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
+ {:ok, activity} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
result =
conn
@@ -71,8 +71,8 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
assert result == []
- {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, other_user, "🎅")
- {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, doomed_user, "🎅")
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, other_user, "🎅")
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, doomed_user, "🎅")
User.perform(:delete, doomed_user)
@@ -109,8 +109,8 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
assert result == []
- {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, other_user, "🎅")
- {:ok, _, _} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, other_user, "🎅")
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
result =
conn
--
cgit v1.2.3
From 8b2457bdbf8791923701b0b015f6ddf2e7c89bf7 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 13:25:34 +0200
Subject: Transmogrifier tests: Extract Undo handling
---
.../transmogrifier/undo_handling_test.exs | 185 +++++++++++++++++++++
test/web/activity_pub/transmogrifier_test.exs | 161 ------------------
2 files changed, 185 insertions(+), 161 deletions(-)
create mode 100644 test/web/activity_pub/transmogrifier/undo_handling_test.exs
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier/undo_handling_test.exs b/test/web/activity_pub/transmogrifier/undo_handling_test.exs
new file mode 100644
index 000000000..a9ebfdb18
--- /dev/null
+++ b/test/web/activity_pub/transmogrifier/undo_handling_test.exs
@@ -0,0 +1,185 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do
+ use Pleroma.DataCase
+
+ alias Pleroma.Activity
+ alias Pleroma.User
+ alias Pleroma.Web.ActivityPub.Transmogrifier
+ alias Pleroma.Web.CommonAPI
+
+ import Pleroma.Factory
+
+ test "it works for incoming emoji reaction undos" do
+ user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+ {:ok, reaction_activity, _object} = CommonAPI.react_with_emoji(activity.id, user, "👌")
+
+ data =
+ File.read!("test/fixtures/mastodon-undo-like.json")
+ |> Poison.decode!()
+ |> Map.put("object", reaction_activity.data["id"])
+ |> Map.put("actor", user.ap_id)
+
+ {:ok, activity} = Transmogrifier.handle_incoming(data)
+
+ assert activity.actor == user.ap_id
+ assert activity.data["id"] == data["id"]
+ assert activity.data["type"] == "Undo"
+ end
+
+ test "it returns an error for incoming unlikes wihout a like activity" do
+ user = insert(:user)
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
+
+ data =
+ File.read!("test/fixtures/mastodon-undo-like.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+
+ assert Transmogrifier.handle_incoming(data) == :error
+ end
+
+ test "it works for incoming unlikes with an existing like activity" do
+ user = insert(:user)
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
+
+ like_data =
+ File.read!("test/fixtures/mastodon-like.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+
+ _liker = insert(:user, ap_id: like_data["actor"], local: false)
+
+ {:ok, %Activity{data: like_data, local: false}} = Transmogrifier.handle_incoming(like_data)
+
+ data =
+ File.read!("test/fixtures/mastodon-undo-like.json")
+ |> Poison.decode!()
+ |> Map.put("object", like_data)
+ |> Map.put("actor", like_data["actor"])
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert data["actor"] == "http://mastodon.example.org/users/admin"
+ assert data["type"] == "Undo"
+ assert data["id"] == "http://mastodon.example.org/users/admin#likes/2/undo"
+ assert data["object"]["id"] == "http://mastodon.example.org/users/admin#likes/2"
+ end
+
+ test "it works for incoming unlikes with an existing like activity and a compact object" do
+ user = insert(:user)
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
+
+ like_data =
+ File.read!("test/fixtures/mastodon-like.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+
+ _liker = insert(:user, ap_id: like_data["actor"], local: false)
+
+ {:ok, %Activity{data: like_data, local: false}} = Transmogrifier.handle_incoming(like_data)
+
+ data =
+ File.read!("test/fixtures/mastodon-undo-like.json")
+ |> Poison.decode!()
+ |> Map.put("object", like_data["id"])
+ |> Map.put("actor", like_data["actor"])
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert data["actor"] == "http://mastodon.example.org/users/admin"
+ assert data["type"] == "Undo"
+ assert data["id"] == "http://mastodon.example.org/users/admin#likes/2/undo"
+ assert data["object"]["id"] == "http://mastodon.example.org/users/admin#likes/2"
+ end
+
+ test "it works for incoming unannounces with an existing notice" do
+ user = insert(:user)
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
+
+ announce_data =
+ File.read!("test/fixtures/mastodon-announce.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+
+ _announcer = insert(:user, ap_id: announce_data["actor"], local: false)
+
+ {:ok, %Activity{data: announce_data, local: false}} =
+ Transmogrifier.handle_incoming(announce_data)
+
+ data =
+ File.read!("test/fixtures/mastodon-undo-announce.json")
+ |> Poison.decode!()
+ |> Map.put("object", announce_data)
+ |> Map.put("actor", announce_data["actor"])
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert data["type"] == "Undo"
+ assert object_data = data["object"]
+ assert object_data["type"] == "Announce"
+ assert object_data["object"] == activity.data["object"]
+
+ assert object_data["id"] ==
+ "http://mastodon.example.org/users/admin/statuses/99542391527669785/activity"
+ end
+
+ test "it works for incomming unfollows with an existing follow" do
+ user = insert(:user)
+
+ follow_data =
+ File.read!("test/fixtures/mastodon-follow-activity.json")
+ |> Poison.decode!()
+ |> Map.put("object", user.ap_id)
+
+ _follower = insert(:user, ap_id: follow_data["actor"], local: false)
+
+ {:ok, %Activity{data: _, local: false}} = Transmogrifier.handle_incoming(follow_data)
+
+ data =
+ File.read!("test/fixtures/mastodon-unfollow-activity.json")
+ |> Poison.decode!()
+ |> Map.put("object", follow_data)
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert data["type"] == "Undo"
+ assert data["object"]["type"] == "Follow"
+ assert data["object"]["object"] == user.ap_id
+ assert data["actor"] == "http://mastodon.example.org/users/admin"
+
+ refute User.following?(User.get_cached_by_ap_id(data["actor"]), user)
+ end
+
+ test "it works for incoming unblocks with an existing block" do
+ user = insert(:user)
+
+ block_data =
+ File.read!("test/fixtures/mastodon-block-activity.json")
+ |> Poison.decode!()
+ |> Map.put("object", user.ap_id)
+
+ _blocker = insert(:user, ap_id: block_data["actor"], local: false)
+
+ {:ok, %Activity{data: _, local: false}} = Transmogrifier.handle_incoming(block_data)
+
+ data =
+ File.read!("test/fixtures/mastodon-unblock-activity.json")
+ |> Poison.decode!()
+ |> Map.put("object", block_data)
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+ assert data["type"] == "Undo"
+ assert data["object"]["type"] == "Block"
+ assert data["object"]["object"] == user.ap_id
+ assert data["actor"] == "http://mastodon.example.org/users/admin"
+
+ blocker = User.get_cached_by_ap_id(data["actor"])
+
+ refute User.blocks?(blocker, user)
+ end
+end
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 23efa4be6..a315ff42d 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -362,87 +362,6 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert :error = Transmogrifier.handle_incoming(data)
end
- test "it works for incoming emoji reaction undos" do
- user = insert(:user)
-
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
- {:ok, reaction_activity, _object} = CommonAPI.react_with_emoji(activity.id, user, "👌")
-
- data =
- File.read!("test/fixtures/mastodon-undo-like.json")
- |> Poison.decode!()
- |> Map.put("object", reaction_activity.data["id"])
- |> Map.put("actor", user.ap_id)
-
- {:ok, activity} = Transmogrifier.handle_incoming(data)
-
- assert activity.actor == user.ap_id
- assert activity.data["id"] == data["id"]
- assert activity.data["type"] == "Undo"
- end
-
- test "it returns an error for incoming unlikes wihout a like activity" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
-
- data =
- File.read!("test/fixtures/mastodon-undo-like.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- assert Transmogrifier.handle_incoming(data) == :error
- end
-
- test "it works for incoming unlikes with an existing like activity" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
-
- like_data =
- File.read!("test/fixtures/mastodon-like.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- {:ok, %Activity{data: like_data, local: false}} = Transmogrifier.handle_incoming(like_data)
-
- data =
- File.read!("test/fixtures/mastodon-undo-like.json")
- |> Poison.decode!()
- |> Map.put("object", like_data)
- |> Map.put("actor", like_data["actor"])
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == "http://mastodon.example.org/users/admin"
- assert data["type"] == "Undo"
- assert data["id"] == "http://mastodon.example.org/users/admin#likes/2/undo"
- assert data["object"]["id"] == "http://mastodon.example.org/users/admin#likes/2"
- end
-
- test "it works for incoming unlikes with an existing like activity and a compact object" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
-
- like_data =
- File.read!("test/fixtures/mastodon-like.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- {:ok, %Activity{data: like_data, local: false}} = Transmogrifier.handle_incoming(like_data)
-
- data =
- File.read!("test/fixtures/mastodon-undo-like.json")
- |> Poison.decode!()
- |> Map.put("object", like_data["id"])
- |> Map.put("actor", like_data["actor"])
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == "http://mastodon.example.org/users/admin"
- assert data["type"] == "Undo"
- assert data["id"] == "http://mastodon.example.org/users/admin#likes/2/undo"
- assert data["object"]["id"] == "http://mastodon.example.org/users/admin#likes/2"
- end
-
test "it works for incoming announces" do
data = File.read!("test/fixtures/mastodon-announce.json") |> Poison.decode!()
@@ -844,60 +763,6 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert User.get_cached_by_ap_id(ap_id)
end
- test "it works for incoming unannounces with an existing notice" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
-
- announce_data =
- File.read!("test/fixtures/mastodon-announce.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- {:ok, %Activity{data: announce_data, local: false}} =
- Transmogrifier.handle_incoming(announce_data)
-
- data =
- File.read!("test/fixtures/mastodon-undo-announce.json")
- |> Poison.decode!()
- |> Map.put("object", announce_data)
- |> Map.put("actor", announce_data["actor"])
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["type"] == "Undo"
- assert object_data = data["object"]
- assert object_data["type"] == "Announce"
- assert object_data["object"] == activity.data["object"]
-
- assert object_data["id"] ==
- "http://mastodon.example.org/users/admin/statuses/99542391527669785/activity"
- end
-
- test "it works for incomming unfollows with an existing follow" do
- user = insert(:user)
-
- follow_data =
- File.read!("test/fixtures/mastodon-follow-activity.json")
- |> Poison.decode!()
- |> Map.put("object", user.ap_id)
-
- {:ok, %Activity{data: _, local: false}} = Transmogrifier.handle_incoming(follow_data)
-
- data =
- File.read!("test/fixtures/mastodon-unfollow-activity.json")
- |> Poison.decode!()
- |> Map.put("object", follow_data)
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["type"] == "Undo"
- assert data["object"]["type"] == "Follow"
- assert data["object"]["object"] == user.ap_id
- assert data["actor"] == "http://mastodon.example.org/users/admin"
-
- refute User.following?(User.get_cached_by_ap_id(data["actor"]), user)
- end
-
test "it works for incoming follows to locked account" do
pending_follower = insert(:user, ap_id: "http://mastodon.example.org/users/admin")
user = insert(:user, locked: true)
@@ -967,32 +832,6 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
refute User.following?(blocked, blocker)
end
- test "it works for incoming unblocks with an existing block" do
- user = insert(:user)
-
- block_data =
- File.read!("test/fixtures/mastodon-block-activity.json")
- |> Poison.decode!()
- |> Map.put("object", user.ap_id)
-
- {:ok, %Activity{data: _, local: false}} = Transmogrifier.handle_incoming(block_data)
-
- data =
- File.read!("test/fixtures/mastodon-unblock-activity.json")
- |> Poison.decode!()
- |> Map.put("object", block_data)
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
- assert data["type"] == "Undo"
- assert data["object"]["type"] == "Block"
- assert data["object"]["object"] == user.ap_id
- assert data["actor"] == "http://mastodon.example.org/users/admin"
-
- blocker = User.get_cached_by_ap_id(data["actor"])
-
- refute User.blocks?(blocker, user)
- end
-
test "it works for incoming accepts which were pre-accepted" do
follower = insert(:user)
followed = insert(:user)
--
cgit v1.2.3
From f1da8882f971f932b65f655b6457759387dafe51 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 14:17:47 +0200
Subject: UndoValidator: Add UndoValidator.
---
test/web/activity_pub/object_validator_test.exs | 41 +++++++++++++++++++++++++
1 file changed, 41 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 93989e28a..8626e127e 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -1,6 +1,7 @@
defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
use Pleroma.DataCase
+ alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.ObjectValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator
alias Pleroma.Web.ActivityPub.Utils
@@ -8,6 +9,46 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
import Pleroma.Factory
+ describe "Undos" do
+ setup do
+ user = insert(:user)
+ {:ok, post_activity} = CommonAPI.post(user, %{"status" => "uguu"})
+ {:ok, like} = CommonAPI.favorite(user, post_activity.id)
+ {:ok, valid_like_undo, []} = Builder.undo(user, like)
+
+ %{user: user, like: like, valid_like_undo: valid_like_undo}
+ end
+
+ test "it validates a basic like undo", %{valid_like_undo: valid_like_undo} do
+ assert {:ok, _, _} = ObjectValidator.validate(valid_like_undo, [])
+ end
+
+ test "it does not validate if the actor of the undo is not the actor of the object", %{
+ valid_like_undo: valid_like_undo
+ } do
+ other_user = insert(:user, ap_id: "https://gensokyo.2hu/users/raymoo")
+
+ bad_actor =
+ valid_like_undo
+ |> Map.put("actor", other_user.ap_id)
+
+ {:error, cng} = ObjectValidator.validate(bad_actor, [])
+
+ assert {:actor, {"not the same as object actor", []}} in cng.errors
+ end
+
+ test "it does not validate if the object is missing", %{valid_like_undo: valid_like_undo} do
+ missing_object =
+ valid_like_undo
+ |> Map.put("object", "https://gensokyo.2hu/objects/1")
+
+ {:error, cng} = ObjectValidator.validate(missing_object, [])
+
+ assert {:object, {"can't find object", []}} in cng.errors
+ assert length(cng.errors) == 1
+ end
+ end
+
describe "likes" do
setup do
user = insert(:user)
--
cgit v1.2.3
From d861b0790a62767b31b8a85862fc249a4f8ca542 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 5 May 2020 16:43:00 +0400
Subject: Add OpenAPI spec for SubscriptionController
---
.../controllers/subscription_controller_test.exs | 28 ++++++++++++----------
1 file changed, 15 insertions(+), 13 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/subscription_controller_test.exs b/test/web/mastodon_api/controllers/subscription_controller_test.exs
index 5682498c0..4aa260663 100644
--- a/test/web/mastodon_api/controllers/subscription_controller_test.exs
+++ b/test/web/mastodon_api/controllers/subscription_controller_test.exs
@@ -6,6 +6,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
use Pleroma.Web.ConnCase
import Pleroma.Factory
+
alias Pleroma.Web.Push
alias Pleroma.Web.Push.Subscription
@@ -27,6 +28,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
build_conn()
|> assign(:user, user)
|> assign(:token, token)
+ |> put_req_header("content-type", "application/json")
%{conn: conn, user: user, token: token}
end
@@ -47,8 +49,8 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
test "returns error when push disabled ", %{conn: conn} do
assert_error_when_disable_push do
conn
- |> post("/api/v1/push/subscription", %{})
- |> json_response(403)
+ |> post("/api/v1/push/subscription", %{subscription: @sub})
+ |> json_response_and_validate_schema(403)
end
end
@@ -59,7 +61,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
"data" => %{"alerts" => %{"mention" => true, "test" => true}},
"subscription" => @sub
})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
[subscription] = Pleroma.Repo.all(Subscription)
@@ -77,7 +79,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
assert_error_when_disable_push do
conn
|> get("/api/v1/push/subscription", %{})
- |> json_response(403)
+ |> json_response_and_validate_schema(403)
end
end
@@ -85,9 +87,9 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
res =
conn
|> get("/api/v1/push/subscription", %{})
- |> json_response(404)
+ |> json_response_and_validate_schema(404)
- assert "Not found" == res
+ assert %{"error" => "Record not found"} == res
end
test "returns a user subsciption", %{conn: conn, user: user, token: token} do
@@ -101,7 +103,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
res =
conn
|> get("/api/v1/push/subscription", %{})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
expect = %{
"alerts" => %{"mention" => true},
@@ -130,7 +132,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
assert_error_when_disable_push do
conn
|> put("/api/v1/push/subscription", %{data: %{"alerts" => %{"mention" => false}}})
- |> json_response(403)
+ |> json_response_and_validate_schema(403)
end
end
@@ -140,7 +142,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
|> put("/api/v1/push/subscription", %{
data: %{"alerts" => %{"mention" => false, "follow" => true}}
})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
expect = %{
"alerts" => %{"follow" => true, "mention" => false},
@@ -158,7 +160,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
assert_error_when_disable_push do
conn
|> delete("/api/v1/push/subscription", %{})
- |> json_response(403)
+ |> json_response_and_validate_schema(403)
end
end
@@ -166,9 +168,9 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
res =
conn
|> delete("/api/v1/push/subscription", %{})
- |> json_response(404)
+ |> json_response_and_validate_schema(404)
- assert "Not found" == res
+ assert %{"error" => "Record not found"} == res
end
test "returns empty result and delete user subsciption", %{
@@ -186,7 +188,7 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
res =
conn
|> delete("/api/v1/push/subscription", %{})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert %{} == res
refute Pleroma.Repo.get(Subscription, subscription.id)
--
cgit v1.2.3
From 8096565653f262844214d715228c31d4ef761f57 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 14 Apr 2020 22:50:29 +0400
Subject: Add OpenAPI spec for MarkerController
---
test/web/mastodon_api/controllers/marker_controller_test.exs | 12 +++++++++++-
1 file changed, 11 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/marker_controller_test.exs b/test/web/mastodon_api/controllers/marker_controller_test.exs
index 919f295bd..1c85ed032 100644
--- a/test/web/mastodon_api/controllers/marker_controller_test.exs
+++ b/test/web/mastodon_api/controllers/marker_controller_test.exs
@@ -4,8 +4,10 @@
defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
use Pleroma.Web.ConnCase
+ alias Pleroma.Web.ApiSpec
import Pleroma.Factory
+ import OpenApiSpex.TestAssertions
describe "GET /api/v1/markers" do
test "gets markers with correct scopes", %{conn: conn} do
@@ -22,7 +24,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
conn
|> assign(:user, user)
|> assign(:token, token)
- |> get("/api/v1/markers", %{timeline: ["notifications"]})
+ |> get("/api/v1/markers?timeline[]=notifications")
|> json_response(200)
assert response == %{
@@ -32,6 +34,8 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"version" => 0
}
}
+
+ assert_schema(response, "MarkersResponse", ApiSpec.spec())
end
test "gets markers with missed scopes", %{conn: conn} do
@@ -60,6 +64,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
conn
|> assign(:user, user)
|> assign(:token, token)
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/markers", %{
home: %{last_read_id: "777"},
notifications: %{"last_read_id" => "69420"}
@@ -73,6 +78,8 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"version" => 0
}
} = response
+
+ assert_schema(response, "MarkersResponse", ApiSpec.spec())
end
test "updates exist marker", %{conn: conn} do
@@ -89,6 +96,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
conn
|> assign(:user, user)
|> assign(:token, token)
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/markers", %{
home: %{last_read_id: "777"},
notifications: %{"last_read_id" => "69888"}
@@ -102,6 +110,8 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"version" => 0
}
}
+
+ assert_schema(response, "MarkersResponse", ApiSpec.spec())
end
test "creates a marker with missed scopes", %{conn: conn} do
--
cgit v1.2.3
From babcae7130d3bc75f85adeef1845997cd091eb84 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 5 May 2020 16:45:34 +0400
Subject: Move single used schemas to Marker operation schema
---
.../controllers/marker_controller_test.exs | 19 ++++++-------------
1 file changed, 6 insertions(+), 13 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/marker_controller_test.exs b/test/web/mastodon_api/controllers/marker_controller_test.exs
index 1c85ed032..bce719bea 100644
--- a/test/web/mastodon_api/controllers/marker_controller_test.exs
+++ b/test/web/mastodon_api/controllers/marker_controller_test.exs
@@ -4,10 +4,8 @@
defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
use Pleroma.Web.ConnCase
- alias Pleroma.Web.ApiSpec
import Pleroma.Factory
- import OpenApiSpex.TestAssertions
describe "GET /api/v1/markers" do
test "gets markers with correct scopes", %{conn: conn} do
@@ -25,7 +23,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
|> assign(:user, user)
|> assign(:token, token)
|> get("/api/v1/markers?timeline[]=notifications")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert response == %{
"notifications" => %{
@@ -34,8 +32,6 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"version" => 0
}
}
-
- assert_schema(response, "MarkersResponse", ApiSpec.spec())
end
test "gets markers with missed scopes", %{conn: conn} do
@@ -49,7 +45,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
|> assign(:user, user)
|> assign(:token, token)
|> get("/api/v1/markers", %{timeline: ["notifications"]})
- |> json_response(403)
+ |> json_response_and_validate_schema(403)
assert response == %{"error" => "Insufficient permissions: read:statuses."}
end
@@ -69,7 +65,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
home: %{last_read_id: "777"},
notifications: %{"last_read_id" => "69420"}
})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert %{
"notifications" => %{
@@ -78,8 +74,6 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"version" => 0
}
} = response
-
- assert_schema(response, "MarkersResponse", ApiSpec.spec())
end
test "updates exist marker", %{conn: conn} do
@@ -101,7 +95,7 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
home: %{last_read_id: "777"},
notifications: %{"last_read_id" => "69888"}
})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert response == %{
"notifications" => %{
@@ -110,8 +104,6 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
"version" => 0
}
}
-
- assert_schema(response, "MarkersResponse", ApiSpec.spec())
end
test "creates a marker with missed scopes", %{conn: conn} do
@@ -122,11 +114,12 @@ defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do
conn
|> assign(:user, user)
|> assign(:token, token)
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/markers", %{
home: %{last_read_id: "777"},
notifications: %{"last_read_id" => "69420"}
})
- |> json_response(403)
+ |> json_response_and_validate_schema(403)
assert response == %{"error" => "Insufficient permissions: write:statuses."}
end
--
cgit v1.2.3
From 5ec6aad5670cf0888942a13e83b9ffd16e97dd18 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 5 May 2020 17:05:34 +0400
Subject: Add OpenAPI spec for ListController
---
test/support/conn_case.ex | 2 +-
.../controllers/list_controller_test.exs | 60 ++++++++++++++--------
2 files changed, 39 insertions(+), 23 deletions(-)
(limited to 'test')
diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex
index fa30a0c41..91c03b1a8 100644
--- a/test/support/conn_case.ex
+++ b/test/support/conn_case.ex
@@ -74,7 +74,7 @@ defmodule Pleroma.Web.ConnCase do
status = Plug.Conn.Status.code(status)
unless lookup[op_id].responses[status] do
- err = "Response schema not found for #{conn.status} #{conn.method} #{conn.request_path}"
+ err = "Response schema not found for #{status} #{conn.method} #{conn.request_path}"
flunk(err)
end
diff --git a/test/web/mastodon_api/controllers/list_controller_test.exs b/test/web/mastodon_api/controllers/list_controller_test.exs
index c9c4cbb49..57a9ef4a4 100644
--- a/test/web/mastodon_api/controllers/list_controller_test.exs
+++ b/test/web/mastodon_api/controllers/list_controller_test.exs
@@ -12,37 +12,44 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do
test "creating a list" do
%{conn: conn} = oauth_access(["write:lists"])
- conn = post(conn, "/api/v1/lists", %{"title" => "cuties"})
-
- assert %{"title" => title} = json_response(conn, 200)
- assert title == "cuties"
+ assert %{"title" => "cuties"} =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/lists", %{"title" => "cuties"})
+ |> json_response_and_validate_schema(:ok)
end
test "renders error for invalid params" do
%{conn: conn} = oauth_access(["write:lists"])
- conn = post(conn, "/api/v1/lists", %{"title" => nil})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/lists", %{"title" => nil})
- assert %{"error" => "can't be blank"} == json_response(conn, :unprocessable_entity)
+ assert %{"error" => "title - null value where string expected."} =
+ json_response_and_validate_schema(conn, 400)
end
test "listing a user's lists" do
%{conn: conn} = oauth_access(["read:lists", "write:lists"])
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/lists", %{"title" => "cuties"})
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/lists", %{"title" => "cofe"})
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
conn = get(conn, "/api/v1/lists")
assert [
%{"id" => _, "title" => "cofe"},
%{"id" => _, "title" => "cuties"}
- ] = json_response(conn, :ok)
+ ] = json_response_and_validate_schema(conn, :ok)
end
test "adding users to a list" do
@@ -50,9 +57,12 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do
other_user = insert(:user)
{:ok, list} = Pleroma.List.create("name", user)
- conn = post(conn, "/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]})
+ assert %{} ==
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]})
+ |> json_response_and_validate_schema(:ok)
- assert %{} == json_response(conn, 200)
%Pleroma.List{following: following} = Pleroma.List.get(list.id, user)
assert following == [other_user.follower_address]
end
@@ -65,9 +75,12 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do
{:ok, list} = Pleroma.List.follow(list, other_user)
{:ok, list} = Pleroma.List.follow(list, third_user)
- conn = delete(conn, "/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]})
+ assert %{} ==
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> delete("/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]})
+ |> json_response_and_validate_schema(:ok)
- assert %{} == json_response(conn, 200)
%Pleroma.List{following: following} = Pleroma.List.get(list.id, user)
assert following == [third_user.follower_address]
end
@@ -83,7 +96,7 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do
|> assign(:user, user)
|> get("/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]})
- assert [%{"id" => id}] = json_response(conn, 200)
+ assert [%{"id" => id}] = json_response_and_validate_schema(conn, 200)
assert id == to_string(other_user.id)
end
@@ -96,7 +109,7 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do
|> assign(:user, user)
|> get("/api/v1/lists/#{list.id}")
- assert %{"id" => id} = json_response(conn, 200)
+ assert %{"id" => id} = json_response_and_validate_schema(conn, 200)
assert id == to_string(list.id)
end
@@ -105,17 +118,18 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do
conn = get(conn, "/api/v1/lists/666")
- assert %{"error" => "List not found"} = json_response(conn, :not_found)
+ assert %{"error" => "List not found"} = json_response_and_validate_schema(conn, :not_found)
end
test "renaming a list" do
%{user: user, conn: conn} = oauth_access(["write:lists"])
{:ok, list} = Pleroma.List.create("name", user)
- conn = put(conn, "/api/v1/lists/#{list.id}", %{"title" => "newname"})
-
- assert %{"title" => name} = json_response(conn, 200)
- assert name == "newname"
+ assert %{"title" => "newname"} =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> put("/api/v1/lists/#{list.id}", %{"title" => "newname"})
+ |> json_response_and_validate_schema(:ok)
end
test "validates title when renaming a list" do
@@ -125,9 +139,11 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do
conn =
conn
|> assign(:user, user)
+ |> put_req_header("content-type", "application/json")
|> put("/api/v1/lists/#{list.id}", %{"title" => " "})
- assert %{"error" => "can't be blank"} == json_response(conn, :unprocessable_entity)
+ assert %{"error" => "can't be blank"} ==
+ json_response_and_validate_schema(conn, :unprocessable_entity)
end
test "deleting a list" do
@@ -136,7 +152,7 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do
conn = delete(conn, "/api/v1/lists/#{list.id}")
- assert %{} = json_response(conn, 200)
+ assert %{} = json_response_and_validate_schema(conn, 200)
assert is_nil(Repo.get(Pleroma.List, list.id))
end
end
--
cgit v1.2.3
From a3071f023166cb5364ce56e3666d5a77baa16434 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 15:08:41 +0200
Subject: Undoing: Move undoing likes to the pipeline everywhere.
---
test/notification_test.exs | 2 +-
test/web/activity_pub/activity_pub_test.exs | 60 ----------------------
test/web/activity_pub/side_effects_test.exs | 29 +++++++++++
.../transmogrifier/undo_handling_test.exs | 9 +++-
4 files changed, 37 insertions(+), 63 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 601a6c0ca..7d5b82993 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -724,7 +724,7 @@ defmodule Pleroma.NotificationTest do
assert length(Notification.for_user(user)) == 1
- {:ok, _, _, _} = CommonAPI.unfavorite(activity.id, other_user)
+ {:ok, _} = CommonAPI.unfavorite(activity.id, other_user)
assert Enum.empty?(Notification.for_user(user))
end
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 84ead93bb..797af66a0 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -995,66 +995,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
end
end
- describe "unliking" do
- test_with_mock "sends an activity to federation", Federator, [:passthrough], [] do
- Config.put([:instance, :federating], true)
-
- note_activity = insert(:note_activity)
- object = Object.normalize(note_activity)
- user = insert(:user)
-
- {:ok, object} = ActivityPub.unlike(user, object)
- refute called(Federator.publish())
-
- {:ok, _like_activity} = CommonAPI.favorite(user, note_activity.id)
- object = Object.get_by_id(object.id)
- assert object.data["like_count"] == 1
-
- {:ok, unlike_activity, _, object} = ActivityPub.unlike(user, object)
- assert object.data["like_count"] == 0
-
- assert called(Federator.publish(unlike_activity))
- end
-
- test "reverts unliking on error" do
- note_activity = insert(:note_activity)
- user = insert(:user)
-
- {:ok, like_activity} = CommonAPI.favorite(user, note_activity.id)
- object = Object.normalize(note_activity)
- assert object.data["like_count"] == 1
-
- with_mock(Utils, [:passthrough], maybe_federate: fn _ -> {:error, :reverted} end) do
- assert {:error, :reverted} = ActivityPub.unlike(user, object)
- end
-
- assert Object.get_by_ap_id(object.data["id"]) == object
- assert object.data["like_count"] == 1
- assert Activity.get_by_id(like_activity.id)
- end
-
- test "unliking a previously liked object" do
- note_activity = insert(:note_activity)
- object = Object.normalize(note_activity)
- user = insert(:user)
-
- # Unliking something that hasn't been liked does nothing
- {:ok, object} = ActivityPub.unlike(user, object)
- assert object.data["like_count"] == 0
-
- {:ok, like_activity} = CommonAPI.favorite(user, note_activity.id)
-
- object = Object.get_by_id(object.id)
- assert object.data["like_count"] == 1
-
- {:ok, unlike_activity, _, object} = ActivityPub.unlike(user, object)
- assert object.data["like_count"] == 0
-
- assert Activity.get_by_id(like_activity.id) == nil
- assert note_activity.actor in unlike_activity.recipients
- end
- end
-
describe "announcing an object" do
test "adds an announce activity to the db" do
note_activity = insert(:note_activity)
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index 0b6b55156..61ef72742 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -5,6 +5,7 @@
defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
use Pleroma.DataCase
+ alias Pleroma.Activity
alias Pleroma.Notification
alias Pleroma.Object
alias Pleroma.Repo
@@ -15,6 +16,34 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
import Pleroma.Factory
+ describe "Undo objects" do
+ setup do
+ poster = insert(:user)
+ user = insert(:user)
+ {:ok, post} = CommonAPI.post(poster, %{"status" => "hey"})
+ {:ok, like} = CommonAPI.favorite(user, post.id)
+
+ {:ok, undo_data, _meta} = Builder.undo(user, like)
+ {:ok, like_undo, _meta} = ActivityPub.persist(undo_data, local: true)
+
+ %{like_undo: like_undo, post: post, like: like}
+ end
+
+ test "a like undo removes the like from the object", %{like_undo: like_undo, post: post} do
+ {:ok, _like_undo, _} = SideEffects.handle(like_undo)
+
+ object = Object.get_by_ap_id(post.data["object"])
+
+ assert object.data["like_count"] == 0
+ assert object.data["likes"] == []
+ end
+
+ test "deletes the original like", %{like_undo: like_undo, like: like} do
+ {:ok, _like_undo, _} = SideEffects.handle(like_undo)
+ refute Activity.get_by_id(like.id)
+ end
+ end
+
describe "like objects" do
setup do
poster = insert(:user)
diff --git a/test/web/activity_pub/transmogrifier/undo_handling_test.exs b/test/web/activity_pub/transmogrifier/undo_handling_test.exs
index a9ebfdb18..bf2a6bc5b 100644
--- a/test/web/activity_pub/transmogrifier/undo_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/undo_handling_test.exs
@@ -6,6 +6,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do
use Pleroma.DataCase
alias Pleroma.Activity
+ alias Pleroma.Object
alias Pleroma.User
alias Pleroma.Web.ActivityPub.Transmogrifier
alias Pleroma.Web.CommonAPI
@@ -67,7 +68,11 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do
assert data["actor"] == "http://mastodon.example.org/users/admin"
assert data["type"] == "Undo"
assert data["id"] == "http://mastodon.example.org/users/admin#likes/2/undo"
- assert data["object"]["id"] == "http://mastodon.example.org/users/admin#likes/2"
+ assert data["object"] == "http://mastodon.example.org/users/admin#likes/2"
+
+ note = Object.get_by_ap_id(like_data["object"])
+ assert note.data["like_count"] == 0
+ assert note.data["likes"] == []
end
test "it works for incoming unlikes with an existing like activity and a compact object" do
@@ -94,7 +99,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do
assert data["actor"] == "http://mastodon.example.org/users/admin"
assert data["type"] == "Undo"
assert data["id"] == "http://mastodon.example.org/users/admin#likes/2/undo"
- assert data["object"]["id"] == "http://mastodon.example.org/users/admin#likes/2"
+ assert data["object"] == "http://mastodon.example.org/users/admin#likes/2"
end
test "it works for incoming unannounces with an existing notice" do
--
cgit v1.2.3
From e7d8ab8303cb69682a75c30a356572a75deb9837 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 5 May 2020 16:08:44 +0300
Subject: admin_api fetch status by id
---
test/web/admin_api/admin_api_controller_test.exs | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 1862a9589..c3f3ad051 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -1620,6 +1620,25 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
end
+ describe "GET /api/pleroma/admin/statuses/:id" do
+ test "not found", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/admin/statuses/not_found")
+ |> json_response(:not_found)
+ end
+
+ test "shows activity", %{conn: conn} do
+ activity = insert(:note_activity)
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/statuses/#{activity.id}")
+ |> json_response(200)
+
+ assert response["id"] == activity.id
+ end
+ end
+
describe "PUT /api/pleroma/admin/statuses/:id" do
setup do
activity = insert(:note_activity)
--
cgit v1.2.3
From 88a14da8172cde6316926b5fbaa2f55b6da6f080 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 5 May 2020 17:24:16 +0400
Subject: Add OpenAPI spec for InstanceController
---
test/web/mastodon_api/controllers/instance_controller_test.exs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/instance_controller_test.exs b/test/web/mastodon_api/controllers/instance_controller_test.exs
index 2c7fd9fd0..90840d5ab 100644
--- a/test/web/mastodon_api/controllers/instance_controller_test.exs
+++ b/test/web/mastodon_api/controllers/instance_controller_test.exs
@@ -10,7 +10,7 @@ defmodule Pleroma.Web.MastodonAPI.InstanceControllerTest do
test "get instance information", %{conn: conn} do
conn = get(conn, "/api/v1/instance")
- assert result = json_response(conn, 200)
+ assert result = json_response_and_validate_schema(conn, 200)
email = Pleroma.Config.get([:instance, :email])
# Note: not checking for "max_toot_chars" since it's optional
@@ -56,7 +56,7 @@ defmodule Pleroma.Web.MastodonAPI.InstanceControllerTest do
conn = get(conn, "/api/v1/instance")
- assert result = json_response(conn, 200)
+ assert result = json_response_and_validate_schema(conn, 200)
stats = result["stats"]
@@ -74,7 +74,7 @@ defmodule Pleroma.Web.MastodonAPI.InstanceControllerTest do
conn = get(conn, "/api/v1/instance/peers")
- assert result = json_response(conn, 200)
+ assert result = json_response_and_validate_schema(conn, 200)
assert ["peer1.com", "peer2.com"] == Enum.sort(result)
end
--
cgit v1.2.3
From ec1e4b4f1acb81fc36b396e7f58f67928dc6a0df Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 5 May 2020 17:40:00 +0400
Subject: Add OpenAPI spec for FollowRequestController
---
.../web/mastodon_api/controllers/follow_request_controller_test.exs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/follow_request_controller_test.exs b/test/web/mastodon_api/controllers/follow_request_controller_test.exs
index d8dbe4800..44e12d15a 100644
--- a/test/web/mastodon_api/controllers/follow_request_controller_test.exs
+++ b/test/web/mastodon_api/controllers/follow_request_controller_test.exs
@@ -27,7 +27,7 @@ defmodule Pleroma.Web.MastodonAPI.FollowRequestControllerTest do
conn = get(conn, "/api/v1/follow_requests")
- assert [relationship] = json_response(conn, 200)
+ assert [relationship] = json_response_and_validate_schema(conn, 200)
assert to_string(other_user.id) == relationship["id"]
end
@@ -44,7 +44,7 @@ defmodule Pleroma.Web.MastodonAPI.FollowRequestControllerTest do
conn = post(conn, "/api/v1/follow_requests/#{other_user.id}/authorize")
- assert relationship = json_response(conn, 200)
+ assert relationship = json_response_and_validate_schema(conn, 200)
assert to_string(other_user.id) == relationship["id"]
user = User.get_cached_by_id(user.id)
@@ -62,7 +62,7 @@ defmodule Pleroma.Web.MastodonAPI.FollowRequestControllerTest do
conn = post(conn, "/api/v1/follow_requests/#{other_user.id}/reject")
- assert relationship = json_response(conn, 200)
+ assert relationship = json_response_and_validate_schema(conn, 200)
assert to_string(other_user.id) == relationship["id"]
user = User.get_cached_by_id(user.id)
--
cgit v1.2.3
From 7e7a3e15449792581412be002f287c504e3449a6 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 14 Apr 2020 18:36:32 +0400
Subject: Add OpenAPI spec for FilterController
---
test/filter_test.exs | 10 ++--
.../controllers/filter_controller_test.exs | 55 ++++++++++++++++++++--
2 files changed, 54 insertions(+), 11 deletions(-)
(limited to 'test')
diff --git a/test/filter_test.exs b/test/filter_test.exs
index b2a8330ee..63a30c736 100644
--- a/test/filter_test.exs
+++ b/test/filter_test.exs
@@ -141,17 +141,15 @@ defmodule Pleroma.FilterTest do
context: ["home"]
}
- query_two = %Pleroma.Filter{
- user_id: user.id,
- filter_id: 1,
+ changes = %{
phrase: "who",
context: ["home", "timeline"]
}
{:ok, filter_one} = Pleroma.Filter.create(query_one)
- {:ok, filter_two} = Pleroma.Filter.update(query_two)
+ {:ok, filter_two} = Pleroma.Filter.update(filter_one, changes)
assert filter_one != filter_two
- assert filter_two.phrase == query_two.phrase
- assert filter_two.context == query_two.context
+ assert filter_two.phrase == changes.phrase
+ assert filter_two.context == changes.context
end
end
diff --git a/test/web/mastodon_api/controllers/filter_controller_test.exs b/test/web/mastodon_api/controllers/filter_controller_test.exs
index 97ab005e0..41a290eb2 100644
--- a/test/web/mastodon_api/controllers/filter_controller_test.exs
+++ b/test/web/mastodon_api/controllers/filter_controller_test.exs
@@ -5,8 +5,15 @@
defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
use Pleroma.Web.ConnCase
+ alias Pleroma.Web.ApiSpec
+ alias Pleroma.Web.ApiSpec.Schemas.Filter
+ alias Pleroma.Web.ApiSpec.Schemas.FilterCreateRequest
+ alias Pleroma.Web.ApiSpec.Schemas.FiltersResponse
+ alias Pleroma.Web.ApiSpec.Schemas.FilterUpdateRequest
alias Pleroma.Web.MastodonAPI.FilterView
+ import OpenApiSpex.TestAssertions
+
test "creating a filter" do
%{conn: conn} = oauth_access(["write:filters"])
@@ -15,7 +22,10 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
context: ["home"]
}
- conn = post(conn, "/api/v1/filters", %{"phrase" => filter.phrase, context: filter.context})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/filters", %{"phrase" => filter.phrase, context: filter.context})
assert response = json_response(conn, 200)
assert response["phrase"] == filter.phrase
@@ -23,6 +33,7 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
assert response["irreversible"] == false
assert response["id"] != nil
assert response["id"] != ""
+ assert_schema(response, "Filter", ApiSpec.spec())
end
test "fetching a list of filters" do
@@ -53,9 +64,11 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
assert response ==
render_json(
FilterView,
- "filters.json",
+ "index.json",
filters: [filter_two, filter_one]
)
+
+ assert_schema(response, "FiltersResponse", ApiSpec.spec())
end
test "get a filter" do
@@ -72,7 +85,8 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
conn = get(conn, "/api/v1/filters/#{filter.filter_id}")
- assert _response = json_response(conn, 200)
+ assert response = json_response(conn, 200)
+ assert_schema(response, "Filter", ApiSpec.spec())
end
test "update a filter" do
@@ -82,7 +96,8 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
user_id: user.id,
filter_id: 2,
phrase: "knight",
- context: ["home"]
+ context: ["home"],
+ hide: true
}
{:ok, _filter} = Pleroma.Filter.create(query)
@@ -93,7 +108,9 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
}
conn =
- put(conn, "/api/v1/filters/#{query.filter_id}", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> put("/api/v1/filters/#{query.filter_id}", %{
phrase: new.phrase,
context: new.context
})
@@ -101,6 +118,8 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
assert response = json_response(conn, 200)
assert response["phrase"] == new.phrase
assert response["context"] == new.context
+ assert response["irreversible"] == true
+ assert_schema(response, "Filter", ApiSpec.spec())
end
test "delete a filter" do
@@ -120,4 +139,30 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
assert response = json_response(conn, 200)
assert response == %{}
end
+
+ describe "OpenAPI" do
+ test "Filter example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = Filter.schema()
+ assert_schema(schema.example, "Filter", api_spec)
+ end
+
+ test "FiltersResponse example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = FiltersResponse.schema()
+ assert_schema(schema.example, "FiltersResponse", api_spec)
+ end
+
+ test "FilterCreateRequest example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = FilterCreateRequest.schema()
+ assert_schema(schema.example, "FilterCreateRequest", api_spec)
+ end
+
+ test "FilterUpdateRequest example matches schema" do
+ api_spec = ApiSpec.spec()
+ schema = FilterUpdateRequest.schema()
+ assert_schema(schema.example, "FilterUpdateRequest", api_spec)
+ end
+ end
end
--
cgit v1.2.3
From 46aae346f8530d4b9933b8e718e9578a96447f0a Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 27 Apr 2020 23:54:11 +0400
Subject: Move single used schemas to Filter operation schema
---
.../controllers/filter_controller_test.exs | 49 +++-------------------
1 file changed, 5 insertions(+), 44 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/filter_controller_test.exs b/test/web/mastodon_api/controllers/filter_controller_test.exs
index 41a290eb2..f29547d13 100644
--- a/test/web/mastodon_api/controllers/filter_controller_test.exs
+++ b/test/web/mastodon_api/controllers/filter_controller_test.exs
@@ -5,15 +5,8 @@
defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
use Pleroma.Web.ConnCase
- alias Pleroma.Web.ApiSpec
- alias Pleroma.Web.ApiSpec.Schemas.Filter
- alias Pleroma.Web.ApiSpec.Schemas.FilterCreateRequest
- alias Pleroma.Web.ApiSpec.Schemas.FiltersResponse
- alias Pleroma.Web.ApiSpec.Schemas.FilterUpdateRequest
alias Pleroma.Web.MastodonAPI.FilterView
- import OpenApiSpex.TestAssertions
-
test "creating a filter" do
%{conn: conn} = oauth_access(["write:filters"])
@@ -27,13 +20,12 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
|> put_req_header("content-type", "application/json")
|> post("/api/v1/filters", %{"phrase" => filter.phrase, context: filter.context})
- assert response = json_response(conn, 200)
+ assert response = json_response_and_validate_schema(conn, 200)
assert response["phrase"] == filter.phrase
assert response["context"] == filter.context
assert response["irreversible"] == false
assert response["id"] != nil
assert response["id"] != ""
- assert_schema(response, "Filter", ApiSpec.spec())
end
test "fetching a list of filters" do
@@ -59,7 +51,7 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
response =
conn
|> get("/api/v1/filters")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert response ==
render_json(
@@ -67,8 +59,6 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
"index.json",
filters: [filter_two, filter_one]
)
-
- assert_schema(response, "FiltersResponse", ApiSpec.spec())
end
test "get a filter" do
@@ -85,8 +75,7 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
conn = get(conn, "/api/v1/filters/#{filter.filter_id}")
- assert response = json_response(conn, 200)
- assert_schema(response, "Filter", ApiSpec.spec())
+ assert response = json_response_and_validate_schema(conn, 200)
end
test "update a filter" do
@@ -115,11 +104,10 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
context: new.context
})
- assert response = json_response(conn, 200)
+ assert response = json_response_and_validate_schema(conn, 200)
assert response["phrase"] == new.phrase
assert response["context"] == new.context
assert response["irreversible"] == true
- assert_schema(response, "Filter", ApiSpec.spec())
end
test "delete a filter" do
@@ -136,33 +124,6 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
conn = delete(conn, "/api/v1/filters/#{filter.filter_id}")
- assert response = json_response(conn, 200)
- assert response == %{}
- end
-
- describe "OpenAPI" do
- test "Filter example matches schema" do
- api_spec = ApiSpec.spec()
- schema = Filter.schema()
- assert_schema(schema.example, "Filter", api_spec)
- end
-
- test "FiltersResponse example matches schema" do
- api_spec = ApiSpec.spec()
- schema = FiltersResponse.schema()
- assert_schema(schema.example, "FiltersResponse", api_spec)
- end
-
- test "FilterCreateRequest example matches schema" do
- api_spec = ApiSpec.spec()
- schema = FilterCreateRequest.schema()
- assert_schema(schema.example, "FilterCreateRequest", api_spec)
- end
-
- test "FilterUpdateRequest example matches schema" do
- api_spec = ApiSpec.spec()
- schema = FilterUpdateRequest.schema()
- assert_schema(schema.example, "FilterUpdateRequest", api_spec)
- end
+ assert json_response_and_validate_schema(conn, 200) == %{}
end
end
--
cgit v1.2.3
From 3a45952a3a324e5fb823e9bdf3ffe19fb3923cb3 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 5 May 2020 17:44:46 +0400
Subject: Add OpenAPI spec for ConversationController
---
.../controllers/conversation_controller_test.exs | 22 +++++++++++-----------
1 file changed, 11 insertions(+), 11 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/conversation_controller_test.exs b/test/web/mastodon_api/controllers/conversation_controller_test.exs
index 801b0259b..04695572e 100644
--- a/test/web/mastodon_api/controllers/conversation_controller_test.exs
+++ b/test/web/mastodon_api/controllers/conversation_controller_test.exs
@@ -36,7 +36,7 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
res_conn = get(conn, "/api/v1/conversations")
- assert response = json_response(res_conn, 200)
+ assert response = json_response_and_validate_schema(res_conn, 200)
assert [
%{
@@ -91,18 +91,18 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
"visibility" => "direct"
})
- [conversation1, conversation2] =
- conn
- |> get("/api/v1/conversations", %{"recipients" => [user_two.id]})
- |> json_response(200)
+ assert [conversation1, conversation2] =
+ conn
+ |> get("/api/v1/conversations?recipients[]=#{user_two.id}")
+ |> json_response_and_validate_schema(200)
assert conversation1["last_status"]["id"] == direct5.id
assert conversation2["last_status"]["id"] == direct1.id
[conversation1] =
conn
- |> get("/api/v1/conversations", %{"recipients" => [user_two.id, user_three.id]})
- |> json_response(200)
+ |> get("/api/v1/conversations?recipients[]=#{user_two.id}&recipients[]=#{user_three.id}")
+ |> json_response_and_validate_schema(200)
assert conversation1["last_status"]["id"] == direct3.id
end
@@ -126,7 +126,7 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
[%{"last_status" => res_last_status}] =
conn
|> get("/api/v1/conversations")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert res_last_status["id"] == direct_reply.id
end
@@ -154,12 +154,12 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
[%{"id" => direct_conversation_id, "unread" => true}] =
user_two_conn
|> get("/api/v1/conversations")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
%{"unread" => false} =
user_two_conn
|> post("/api/v1/conversations/#{direct_conversation_id}/read")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert User.get_cached_by_id(user_one.id).unread_conversation_count == 0
assert User.get_cached_by_id(user_two.id).unread_conversation_count == 0
@@ -175,7 +175,7 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
[%{"unread" => true}] =
conn
|> get("/api/v1/conversations")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert User.get_cached_by_id(user_one.id).unread_conversation_count == 1
assert User.get_cached_by_id(user_two.id).unread_conversation_count == 0
--
cgit v1.2.3
From b34debe61540cf845ccf4ac93066e45a1d9c8f85 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 16:17:09 +0200
Subject: Undoing: Move undoing reactions to the pipeline everywhere.
---
test/web/activity_pub/activity_pub_test.exs | 56 ----------------------
test/web/activity_pub/side_effects_test.exs | 30 +++++++++++-
test/web/common_api/common_api_test.exs | 3 +-
.../controllers/pleroma_api_controller_test.exs | 10 +++-
4 files changed, 39 insertions(+), 60 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 797af66a0..cb2d41f0b 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -939,62 +939,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
end
end
- describe "unreacting to an object" do
- test_with_mock "sends an activity to federation", Federator, [:passthrough], [] do
- Config.put([:instance, :federating], true)
- user = insert(:user)
- reactor = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "YASSSS queen slay"})
- assert object = Object.normalize(activity)
-
- {:ok, reaction_activity, _object} = ActivityPub.react_with_emoji(reactor, object, "🔥")
-
- assert called(Federator.publish(reaction_activity))
-
- {:ok, unreaction_activity, _object} =
- ActivityPub.unreact_with_emoji(reactor, reaction_activity.data["id"])
-
- assert called(Federator.publish(unreaction_activity))
- end
-
- test "adds an undo activity to the db" do
- user = insert(:user)
- reactor = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "YASSSS queen slay"})
- assert object = Object.normalize(activity)
-
- {:ok, reaction_activity, _object} = ActivityPub.react_with_emoji(reactor, object, "🔥")
-
- {:ok, unreaction_activity, _object} =
- ActivityPub.unreact_with_emoji(reactor, reaction_activity.data["id"])
-
- assert unreaction_activity.actor == reactor.ap_id
- assert unreaction_activity.data["object"] == reaction_activity.data["id"]
-
- object = Object.get_by_ap_id(object.data["id"])
- assert object.data["reaction_count"] == 0
- assert object.data["reactions"] == []
- end
-
- test "reverts emoji unreact on error" do
- [user, reactor] = insert_list(2, :user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Status"})
- object = Object.normalize(activity)
-
- {:ok, reaction_activity, _object} = ActivityPub.react_with_emoji(reactor, object, "😀")
-
- with_mock(Utils, [:passthrough], maybe_federate: fn _ -> {:error, :reverted} end) do
- assert {:error, :reverted} =
- ActivityPub.unreact_with_emoji(reactor, reaction_activity.data["id"])
- end
-
- object = Object.get_by_ap_id(object.data["id"])
-
- assert object.data["reaction_count"] == 1
- assert object.data["reactions"] == [["😀", [reactor.ap_id]]]
- end
- end
-
describe "announcing an object" do
test "adds an announce activity to the db" do
note_activity = insert(:note_activity)
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index 61ef72742..abcfdfa2f 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -23,10 +23,38 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
{:ok, post} = CommonAPI.post(poster, %{"status" => "hey"})
{:ok, like} = CommonAPI.favorite(user, post.id)
+ {:ok, reaction, _} = CommonAPI.react_with_emoji(post.id, user, "👍")
+
{:ok, undo_data, _meta} = Builder.undo(user, like)
{:ok, like_undo, _meta} = ActivityPub.persist(undo_data, local: true)
- %{like_undo: like_undo, post: post, like: like}
+ {:ok, undo_data, _meta} = Builder.undo(user, reaction)
+ {:ok, reaction_undo, _meta} = ActivityPub.persist(undo_data, local: true)
+
+ %{
+ like_undo: like_undo,
+ post: post,
+ like: like,
+ reaction_undo: reaction_undo,
+ reaction: reaction
+ }
+ end
+
+ test "a reaction undo removes the reaction from the object", %{
+ reaction_undo: reaction_undo,
+ post: post
+ } do
+ {:ok, _reaction_undo, _} = SideEffects.handle(reaction_undo)
+
+ object = Object.get_by_ap_id(post.data["object"])
+
+ assert object.data["reaction_count"] == 0
+ assert object.data["reactions"] == []
+ end
+
+ test "deletes the original reaction", %{reaction_undo: reaction_undo, reaction: reaction} do
+ {:ok, _reaction_undo, _} = SideEffects.handle(reaction_undo)
+ refute Activity.get_by_id(reaction.id)
end
test "a like undo removes the like from the object", %{like_undo: like_undo, post: post} do
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index bc0c1a791..0664b7f90 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -295,10 +295,11 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
{:ok, reaction, _} = CommonAPI.react_with_emoji(activity.id, user, "👍")
- {:ok, unreaction, _} = CommonAPI.unreact_with_emoji(activity.id, user, "👍")
+ {:ok, unreaction} = CommonAPI.unreact_with_emoji(activity.id, user, "👍")
assert unreaction.data["type"] == "Undo"
assert unreaction.data["object"] == reaction.data["id"]
+ assert unreaction.local
end
test "repeating a status" do
diff --git a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
index 61a1689b9..299dbad41 100644
--- a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
@@ -3,12 +3,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
+ use Oban.Testing, repo: Pleroma.Repo
use Pleroma.Web.ConnCase
alias Pleroma.Conversation.Participation
alias Pleroma.Notification
alias Pleroma.Object
alias Pleroma.Repo
+ alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
alias Pleroma.Web.CommonAPI
@@ -41,7 +43,9 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
- {:ok, activity, _object} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
+ {:ok, _reaction, _object} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
+
+ ObanHelpers.perform_all()
result =
conn
@@ -52,7 +56,9 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
assert %{"id" => id} = json_response(result, 200)
assert to_string(activity.id) == id
- object = Object.normalize(activity)
+ ObanHelpers.perform_all()
+
+ object = Object.get_by_ap_id(activity.data["object"])
assert object.data["reaction_count"] == 0
end
--
cgit v1.2.3
From a3bb2e5474ee068bf375b24df8906e51654c9699 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 16:42:34 +0200
Subject: Undoing: Move undoing announcements to the pipeline everywhere.
---
test/notification_test.exs | 2 +-
test/web/activity_pub/activity_pub_test.exs | 46 ----------------------
test/web/activity_pub/side_effects_test.exs | 26 +++++++++++-
.../transmogrifier/undo_handling_test.exs | 5 +--
4 files changed, 26 insertions(+), 53 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 7d5b82993..09714f4c5 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -758,7 +758,7 @@ defmodule Pleroma.NotificationTest do
assert length(Notification.for_user(user)) == 1
- {:ok, _, _} = CommonAPI.unrepeat(activity.id, other_user)
+ {:ok, _} = CommonAPI.unrepeat(activity.id, other_user)
assert Enum.empty?(Notification.for_user(user))
end
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index cb2d41f0b..2c3d354f2 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -1008,52 +1008,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
end
end
- describe "unannouncing an object" do
- test "unannouncing a previously announced object" do
- note_activity = insert(:note_activity)
- object = Object.normalize(note_activity)
- user = insert(:user)
-
- # Unannouncing an object that is not announced does nothing
- {:ok, object} = ActivityPub.unannounce(user, object)
- refute object.data["announcement_count"]
-
- {:ok, announce_activity, object} = ActivityPub.announce(user, object)
- assert object.data["announcement_count"] == 1
-
- {:ok, unannounce_activity, object} = ActivityPub.unannounce(user, object)
- assert object.data["announcement_count"] == 0
-
- assert unannounce_activity.data["to"] == [
- User.ap_followers(user),
- object.data["actor"]
- ]
-
- assert unannounce_activity.data["type"] == "Undo"
- assert unannounce_activity.data["object"] == announce_activity.data
- assert unannounce_activity.data["actor"] == user.ap_id
- assert unannounce_activity.data["context"] == announce_activity.data["context"]
-
- assert Activity.get_by_id(announce_activity.id) == nil
- end
-
- test "reverts unannouncing on error" do
- note_activity = insert(:note_activity)
- object = Object.normalize(note_activity)
- user = insert(:user)
-
- {:ok, _announce_activity, object} = ActivityPub.announce(user, object)
- assert object.data["announcement_count"] == 1
-
- with_mock(Utils, [:passthrough], maybe_federate: fn _ -> {:error, :reverted} end) do
- assert {:error, :reverted} = ActivityPub.unannounce(user, object)
- end
-
- object = Object.get_by_ap_id(object.data["id"])
- assert object.data["announcement_count"] == 1
- end
- end
-
describe "uploading files" do
test "copies the file to the configured folder" do
file = %Plug.Upload{
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index abcfdfa2f..00241320b 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -22,8 +22,8 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
user = insert(:user)
{:ok, post} = CommonAPI.post(poster, %{"status" => "hey"})
{:ok, like} = CommonAPI.favorite(user, post.id)
-
{:ok, reaction, _} = CommonAPI.react_with_emoji(post.id, user, "👍")
+ {:ok, announce, _} = CommonAPI.repeat(post.id, user)
{:ok, undo_data, _meta} = Builder.undo(user, like)
{:ok, like_undo, _meta} = ActivityPub.persist(undo_data, local: true)
@@ -31,15 +31,37 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
{:ok, undo_data, _meta} = Builder.undo(user, reaction)
{:ok, reaction_undo, _meta} = ActivityPub.persist(undo_data, local: true)
+ {:ok, undo_data, _meta} = Builder.undo(user, announce)
+ {:ok, announce_undo, _meta} = ActivityPub.persist(undo_data, local: true)
+
%{
like_undo: like_undo,
post: post,
like: like,
reaction_undo: reaction_undo,
- reaction: reaction
+ reaction: reaction,
+ announce_undo: announce_undo,
+ announce: announce
}
end
+ test "an announce undo removes the announce from the object", %{
+ announce_undo: announce_undo,
+ post: post
+ } do
+ {:ok, _announce_undo, _} = SideEffects.handle(announce_undo)
+
+ object = Object.get_by_ap_id(post.data["object"])
+
+ assert object.data["announcement_count"] == 0
+ assert object.data["announcements"] == []
+ end
+
+ test "deletes the original announce", %{announce_undo: announce_undo, announce: announce} do
+ {:ok, _announce_undo, _} = SideEffects.handle(announce_undo)
+ refute Activity.get_by_id(announce.id)
+ end
+
test "a reaction undo removes the reaction from the object", %{
reaction_undo: reaction_undo,
post: post
diff --git a/test/web/activity_pub/transmogrifier/undo_handling_test.exs b/test/web/activity_pub/transmogrifier/undo_handling_test.exs
index bf2a6bc5b..281cf5b0d 100644
--- a/test/web/activity_pub/transmogrifier/undo_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/undo_handling_test.exs
@@ -125,11 +125,8 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do
{:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
assert data["type"] == "Undo"
- assert object_data = data["object"]
- assert object_data["type"] == "Announce"
- assert object_data["object"] == activity.data["object"]
- assert object_data["id"] ==
+ assert data["object"] ==
"http://mastodon.example.org/users/admin/statuses/99542391527669785/activity"
end
--
cgit v1.2.3
From 92caae592338a3ca307686e7644f2de18bb57ce5 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 5 May 2020 18:00:37 +0200
Subject: Undoing: Move undoing blocks to the pipeline everywhere.
---
test/web/activity_pub/activity_pub_test.exs | 34 +---------------------
test/web/activity_pub/side_effects_test.exs | 25 +++++++++++++++-
.../transmogrifier/undo_handling_test.exs | 4 +--
test/web/activity_pub/utils_test.exs | 28 ------------------
4 files changed, 26 insertions(+), 65 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 2c3d354f2..7824095c7 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -1114,7 +1114,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
end
end
- describe "blocking / unblocking" do
+ describe "blocking" do
test "reverts block activity on error" do
[blocker, blocked] = insert_list(2, :user)
@@ -1136,38 +1136,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
assert activity.data["actor"] == blocker.ap_id
assert activity.data["object"] == blocked.ap_id
end
-
- test "reverts unblock activity on error" do
- [blocker, blocked] = insert_list(2, :user)
- {:ok, block_activity} = ActivityPub.block(blocker, blocked)
-
- with_mock(Utils, [:passthrough], maybe_federate: fn _ -> {:error, :reverted} end) do
- assert {:error, :reverted} = ActivityPub.unblock(blocker, blocked)
- end
-
- assert block_activity.data["type"] == "Block"
- assert block_activity.data["actor"] == blocker.ap_id
-
- assert Repo.aggregate(Activity, :count, :id) == 1
- assert Repo.aggregate(Object, :count, :id) == 1
- end
-
- test "creates an undo activity for the last block" do
- blocker = insert(:user)
- blocked = insert(:user)
-
- {:ok, block_activity} = ActivityPub.block(blocker, blocked)
- {:ok, activity} = ActivityPub.unblock(blocker, blocked)
-
- assert activity.data["type"] == "Undo"
- assert activity.data["actor"] == blocker.ap_id
-
- embedded_object = activity.data["object"]
- assert is_map(embedded_object)
- assert embedded_object["type"] == "Block"
- assert embedded_object["object"] == blocked.ap_id
- assert embedded_object["id"] == block_activity.data["id"]
- end
end
describe "deletion" do
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index 00241320b..f41a7f3c1 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -9,6 +9,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
alias Pleroma.Notification
alias Pleroma.Object
alias Pleroma.Repo
+ alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.SideEffects
@@ -24,6 +25,8 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
{:ok, like} = CommonAPI.favorite(user, post.id)
{:ok, reaction, _} = CommonAPI.react_with_emoji(post.id, user, "👍")
{:ok, announce, _} = CommonAPI.repeat(post.id, user)
+ {:ok, block} = ActivityPub.block(user, poster)
+ User.block(user, poster)
{:ok, undo_data, _meta} = Builder.undo(user, like)
{:ok, like_undo, _meta} = ActivityPub.persist(undo_data, local: true)
@@ -34,6 +37,9 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
{:ok, undo_data, _meta} = Builder.undo(user, announce)
{:ok, announce_undo, _meta} = ActivityPub.persist(undo_data, local: true)
+ {:ok, undo_data, _meta} = Builder.undo(user, block)
+ {:ok, block_undo, _meta} = ActivityPub.persist(undo_data, local: true)
+
%{
like_undo: like_undo,
post: post,
@@ -41,10 +47,27 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
reaction_undo: reaction_undo,
reaction: reaction,
announce_undo: announce_undo,
- announce: announce
+ announce: announce,
+ block_undo: block_undo,
+ block: block,
+ poster: poster,
+ user: user
}
end
+ test "deletes the original block", %{block_undo: block_undo, block: block} do
+ {:ok, _block_undo, _} = SideEffects.handle(block_undo)
+ refute Activity.get_by_id(block.id)
+ end
+
+ test "unblocks the blocked user", %{block_undo: block_undo, block: block} do
+ blocker = User.get_by_ap_id(block.data["actor"])
+ blocked = User.get_by_ap_id(block.data["object"])
+
+ {:ok, _block_undo, _} = SideEffects.handle(block_undo)
+ refute User.blocks?(blocker, blocked)
+ end
+
test "an announce undo removes the announce from the object", %{
announce_undo: announce_undo,
post: post
diff --git a/test/web/activity_pub/transmogrifier/undo_handling_test.exs b/test/web/activity_pub/transmogrifier/undo_handling_test.exs
index 281cf5b0d..6f5e61ac3 100644
--- a/test/web/activity_pub/transmogrifier/undo_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/undo_handling_test.exs
@@ -176,9 +176,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do
{:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
assert data["type"] == "Undo"
- assert data["object"]["type"] == "Block"
- assert data["object"]["object"] == user.ap_id
- assert data["actor"] == "http://mastodon.example.org/users/admin"
+ assert data["object"] == block_data["id"]
blocker = User.get_cached_by_ap_id(data["actor"])
diff --git a/test/web/activity_pub/utils_test.exs b/test/web/activity_pub/utils_test.exs
index b0bfed917..b8d811c73 100644
--- a/test/web/activity_pub/utils_test.exs
+++ b/test/web/activity_pub/utils_test.exs
@@ -102,34 +102,6 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do
end
end
- describe "make_unlike_data/3" do
- test "returns data for unlike activity" do
- user = insert(:user)
- like_activity = insert(:like_activity, data_attrs: %{"context" => "test context"})
-
- object = Object.normalize(like_activity.data["object"])
-
- assert Utils.make_unlike_data(user, like_activity, nil) == %{
- "type" => "Undo",
- "actor" => user.ap_id,
- "object" => like_activity.data,
- "to" => [user.follower_address, object.data["actor"]],
- "cc" => [Pleroma.Constants.as_public()],
- "context" => like_activity.data["context"]
- }
-
- assert Utils.make_unlike_data(user, like_activity, "9mJEZK0tky1w2xD2vY") == %{
- "type" => "Undo",
- "actor" => user.ap_id,
- "object" => like_activity.data,
- "to" => [user.follower_address, object.data["actor"]],
- "cc" => [Pleroma.Constants.as_public()],
- "context" => like_activity.data["context"],
- "id" => "9mJEZK0tky1w2xD2vY"
- }
- end
- end
-
describe "make_like_data" do
setup do
user = insert(:user)
--
cgit v1.2.3
From 0a1394cc1a38ce66b1b30d728856ae891aa3d7b0 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 5 May 2020 20:14:22 +0400
Subject: Add OpenAPI spec for PollController
---
.../controllers/poll_controller_test.exs | 38 +++++++++++++++-------
1 file changed, 26 insertions(+), 12 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/poll_controller_test.exs b/test/web/mastodon_api/controllers/poll_controller_test.exs
index 88b13a25a..d8f34aa86 100644
--- a/test/web/mastodon_api/controllers/poll_controller_test.exs
+++ b/test/web/mastodon_api/controllers/poll_controller_test.exs
@@ -24,7 +24,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
conn = get(conn, "/api/v1/polls/#{object.id}")
- response = json_response(conn, 200)
+ response = json_response_and_validate_schema(conn, 200)
id = to_string(object.id)
assert %{"id" => ^id, "expired" => false, "multiple" => false} = response
end
@@ -43,7 +43,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
conn = get(conn, "/api/v1/polls/#{object.id}")
- assert json_response(conn, 404)
+ assert json_response_and_validate_schema(conn, 404)
end
end
@@ -65,9 +65,12 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
object = Object.normalize(activity)
- conn = post(conn, "/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1, 2]})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1, 2]})
- assert json_response(conn, 200)
+ assert json_response_and_validate_schema(conn, 200)
object = Object.get_by_id(object.id)
assert Enum.all?(object.data["anyOf"], fn %{"replies" => %{"totalItems" => total_items}} ->
@@ -85,8 +88,9 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
object = Object.normalize(activity)
assert conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [1]})
- |> json_response(422) == %{"error" => "Poll's author can't vote"}
+ |> json_response_and_validate_schema(422) == %{"error" => "Poll's author can't vote"}
object = Object.get_by_id(object.id)
@@ -105,8 +109,9 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
object = Object.normalize(activity)
assert conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1]})
- |> json_response(422) == %{"error" => "Too many choices"}
+ |> json_response_and_validate_schema(422) == %{"error" => "Too many choices"}
object = Object.get_by_id(object.id)
@@ -126,15 +131,21 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
object = Object.normalize(activity)
- conn = post(conn, "/api/v1/polls/#{object.id}/votes", %{"choices" => [2]})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [2]})
- assert json_response(conn, 422) == %{"error" => "Invalid indices"}
+ assert json_response_and_validate_schema(conn, 422) == %{"error" => "Invalid indices"}
end
test "returns 404 error when object is not exist", %{conn: conn} do
- conn = post(conn, "/api/v1/polls/1/votes", %{"choices" => [0]})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/polls/1/votes", %{"choices" => [0]})
- assert json_response(conn, 404) == %{"error" => "Record not found"}
+ assert json_response_and_validate_schema(conn, 404) == %{"error" => "Record not found"}
end
test "returns 404 when poll is private and not available for user", %{conn: conn} do
@@ -149,9 +160,12 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
object = Object.normalize(activity)
- conn = post(conn, "/api/v1/polls/#{object.id}/votes", %{"choices" => [0]})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0]})
- assert json_response(conn, 404) == %{"error" => "Record not found"}
+ assert json_response_and_validate_schema(conn, 404) == %{"error" => "Record not found"}
end
end
end
--
cgit v1.2.3
From 332e016bcdbda5dca90d916bc62a9c67544b5323 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 5 May 2020 23:42:18 +0400
Subject: Add OpenAPI spec for ScheduledActivityController
---
test/support/helpers.ex | 8 ++++-
.../scheduled_activity_controller_test.exs | 34 ++++++++++++++--------
test/web/mastodon_api/views/status_view_test.exs | 8 ++++-
3 files changed, 36 insertions(+), 14 deletions(-)
(limited to 'test')
diff --git a/test/support/helpers.ex b/test/support/helpers.ex
index e68e9bfd2..26281b45e 100644
--- a/test/support/helpers.ex
+++ b/test/support/helpers.ex
@@ -40,12 +40,18 @@ defmodule Pleroma.Tests.Helpers do
clear_config: 2
]
- def to_datetime(naive_datetime) do
+ def to_datetime(%NaiveDateTime{} = naive_datetime) do
naive_datetime
|> DateTime.from_naive!("Etc/UTC")
|> DateTime.truncate(:second)
end
+ def to_datetime(datetime) when is_binary(datetime) do
+ datetime
+ |> NaiveDateTime.from_iso8601!()
+ |> to_datetime()
+ end
+
def collect_ids(collection) do
collection
|> Enum.map(& &1.id)
diff --git a/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs b/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs
index f86274d57..1ff871c89 100644
--- a/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs
+++ b/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs
@@ -24,19 +24,19 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityControllerTest do
# min_id
conn_res = get(conn, "/api/v1/scheduled_statuses?limit=2&min_id=#{scheduled_activity_id1}")
- result = json_response(conn_res, 200)
+ result = json_response_and_validate_schema(conn_res, 200)
assert [%{"id" => ^scheduled_activity_id3}, %{"id" => ^scheduled_activity_id2}] = result
# since_id
conn_res = get(conn, "/api/v1/scheduled_statuses?limit=2&since_id=#{scheduled_activity_id1}")
- result = json_response(conn_res, 200)
+ result = json_response_and_validate_schema(conn_res, 200)
assert [%{"id" => ^scheduled_activity_id4}, %{"id" => ^scheduled_activity_id3}] = result
# max_id
conn_res = get(conn, "/api/v1/scheduled_statuses?limit=2&max_id=#{scheduled_activity_id4}")
- result = json_response(conn_res, 200)
+ result = json_response_and_validate_schema(conn_res, 200)
assert [%{"id" => ^scheduled_activity_id3}, %{"id" => ^scheduled_activity_id2}] = result
end
@@ -46,12 +46,12 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityControllerTest do
res_conn = get(conn, "/api/v1/scheduled_statuses/#{scheduled_activity.id}")
- assert %{"id" => scheduled_activity_id} = json_response(res_conn, 200)
+ assert %{"id" => scheduled_activity_id} = json_response_and_validate_schema(res_conn, 200)
assert scheduled_activity_id == scheduled_activity.id |> to_string()
res_conn = get(conn, "/api/v1/scheduled_statuses/404")
- assert %{"error" => "Record not found"} = json_response(res_conn, 404)
+ assert %{"error" => "Record not found"} = json_response_and_validate_schema(res_conn, 404)
end
test "updates a scheduled activity" do
@@ -74,22 +74,32 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityControllerTest do
assert job.args == %{"activity_id" => scheduled_activity.id}
assert DateTime.truncate(job.scheduled_at, :second) == to_datetime(scheduled_at)
- new_scheduled_at = Timex.shift(NaiveDateTime.utc_now(), minutes: 120)
+ new_scheduled_at =
+ NaiveDateTime.utc_now()
+ |> Timex.shift(minutes: 120)
+ |> Timex.format!("%Y-%m-%dT%H:%M:%S.%fZ", :strftime)
res_conn =
- put(conn, "/api/v1/scheduled_statuses/#{scheduled_activity.id}", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> put("/api/v1/scheduled_statuses/#{scheduled_activity.id}", %{
scheduled_at: new_scheduled_at
})
- assert %{"scheduled_at" => expected_scheduled_at} = json_response(res_conn, 200)
+ assert %{"scheduled_at" => expected_scheduled_at} =
+ json_response_and_validate_schema(res_conn, 200)
+
assert expected_scheduled_at == Pleroma.Web.CommonAPI.Utils.to_masto_date(new_scheduled_at)
job = refresh_record(job)
assert DateTime.truncate(job.scheduled_at, :second) == to_datetime(new_scheduled_at)
- res_conn = put(conn, "/api/v1/scheduled_statuses/404", %{scheduled_at: new_scheduled_at})
+ res_conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> put("/api/v1/scheduled_statuses/404", %{scheduled_at: new_scheduled_at})
- assert %{"error" => "Record not found"} = json_response(res_conn, 404)
+ assert %{"error" => "Record not found"} = json_response_and_validate_schema(res_conn, 404)
end
test "deletes a scheduled activity" do
@@ -115,7 +125,7 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityControllerTest do
|> assign(:user, user)
|> delete("/api/v1/scheduled_statuses/#{scheduled_activity.id}")
- assert %{} = json_response(res_conn, 200)
+ assert %{} = json_response_and_validate_schema(res_conn, 200)
refute Repo.get(ScheduledActivity, scheduled_activity.id)
refute Repo.get(Oban.Job, job.id)
@@ -124,6 +134,6 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityControllerTest do
|> assign(:user, user)
|> delete("/api/v1/scheduled_statuses/#{scheduled_activity.id}")
- assert %{"error" => "Record not found"} = json_response(res_conn, 404)
+ assert %{"error" => "Record not found"} = json_response_and_validate_schema(res_conn, 404)
end
end
diff --git a/test/web/mastodon_api/views/status_view_test.exs b/test/web/mastodon_api/views/status_view_test.exs
index 6791c2fb0..451723e60 100644
--- a/test/web/mastodon_api/views/status_view_test.exs
+++ b/test/web/mastodon_api/views/status_view_test.exs
@@ -402,11 +402,17 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
pleroma: %{mime_type: "image/png"}
}
+ api_spec = Pleroma.Web.ApiSpec.spec()
+
assert expected == StatusView.render("attachment.json", %{attachment: object})
+ OpenApiSpex.TestAssertions.assert_schema(expected, "Attachment", api_spec)
# If theres a "id", use that instead of the generated one
object = Map.put(object, "id", 2)
- assert %{id: "2"} = StatusView.render("attachment.json", %{attachment: object})
+ result = StatusView.render("attachment.json", %{attachment: object})
+
+ assert %{id: "2"} = result
+ OpenApiSpex.TestAssertions.assert_schema(result, "Attachment", api_spec)
end
test "put the url advertised in the Activity in to the url attribute" do
--
cgit v1.2.3
From bd261309cc27ebf5d2f78ea3c1474fe71ae8046d Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Wed, 6 May 2020 15:08:38 +0300
Subject: added `unread_notifications_count` for
`/api/v1/accounts/verify_credentials`
---
.../controllers/account_controller_test.exs | 3 +++
test/web/mastodon_api/views/account_view_test.exs | 18 ++++++++++++++++++
2 files changed, 21 insertions(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index b9da7e924..256a8b304 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -1196,12 +1196,15 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
describe "verify_credentials" do
test "verify_credentials" do
%{user: user, conn: conn} = oauth_access(["read:accounts"])
+ [notification | _] = insert_list(7, :notification, user: user)
+ Pleroma.Notification.set_read_up_to(user, notification.id)
conn = get(conn, "/api/v1/accounts/verify_credentials")
response = json_response_and_validate_schema(conn, 200)
assert %{"id" => id, "source" => %{"privacy" => "public"}} = response
assert response["pleroma"]["chat_token"]
+ assert response["pleroma"]["unread_notifications_count"] == 6
assert id == to_string(user.id)
end
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index 85fa4f6a2..5fb162141 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -466,6 +466,24 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
:unread_conversation_count
] == 1
end
+
+ test "shows unread_count only to the account owner" do
+ user = insert(:user)
+ insert_list(7, :notification, user: user)
+ other_user = insert(:user)
+
+ user = User.get_cached_by_ap_id(user.ap_id)
+
+ assert AccountView.render(
+ "show.json",
+ %{user: user, for: other_user}
+ )[:pleroma][:unread_notifications_count] == nil
+
+ assert AccountView.render(
+ "show.json",
+ %{user: user, for: user}
+ )[:pleroma][:unread_notifications_count] == 7
+ end
end
describe "follow requests counter" do
--
cgit v1.2.3
From a2580adc91ac757e47b88839f5fb723fb15305b1 Mon Sep 17 00:00:00 2001
From: Mark Felder
Date: Wed, 6 May 2020 16:42:27 -0500
Subject: Hide the sender when privacy option is enabled
---
test/web/push/impl_test.exs | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/push/impl_test.exs b/test/web/push/impl_test.exs
index b2664bf28..3de911810 100644
--- a/test/web/push/impl_test.exs
+++ b/test/web/push/impl_test.exs
@@ -209,8 +209,7 @@ defmodule Pleroma.Web.Push.ImplTest do
object = Object.normalize(activity)
assert Impl.build_content(notif, actor, object) == %{
- body: "@Bob",
- title: "New Direct Message"
+ body: "New Direct Message"
}
end
--
cgit v1.2.3
From 3d0c567fbc3506770fdac5f1269c45b244928747 Mon Sep 17 00:00:00 2001
From: Maksim
Date: Thu, 7 May 2020 08:14:54 +0000
Subject: Pleroma.Web.TwitterAPI.TwoFactorAuthenticationController ->
Pleroma.Web.PleromaAPI.TwoFactorAuthenticationController
---
test/mfa/backup_codes_test.exs | 11 +
test/mfa/totp_test.exs | 17 ++
test/mfa_test.exs | 53 ++++
test/plugs/ensure_authenticated_plug_test.exs | 25 ++
test/support/builders/user_builder.ex | 1 +
test/support/factory.ex | 12 +-
test/user_search_test.exs | 1 +
test/web/admin_api/admin_api_controller_test.exs | 33 +++
test/web/auth/pleroma_authenticator_test.exs | 43 +++
test/web/auth/totp_authenticator_test.exs | 51 ++++
test/web/oauth/mfa_controller_test.exs | 306 +++++++++++++++++++++
test/web/oauth/oauth_controller_test.exs | 77 ++++++
.../two_factor_authentication_controller_test.exs | 260 +++++++++++++++++
.../twitter_api/remote_follow_controller_test.exs | 116 ++++++++
14 files changed, 1005 insertions(+), 1 deletion(-)
create mode 100644 test/mfa/backup_codes_test.exs
create mode 100644 test/mfa/totp_test.exs
create mode 100644 test/mfa_test.exs
create mode 100644 test/web/auth/pleroma_authenticator_test.exs
create mode 100644 test/web/auth/totp_authenticator_test.exs
create mode 100644 test/web/oauth/mfa_controller_test.exs
create mode 100644 test/web/pleroma_api/controllers/two_factor_authentication_controller_test.exs
(limited to 'test')
diff --git a/test/mfa/backup_codes_test.exs b/test/mfa/backup_codes_test.exs
new file mode 100644
index 000000000..7bc01b36b
--- /dev/null
+++ b/test/mfa/backup_codes_test.exs
@@ -0,0 +1,11 @@
+defmodule Pleroma.MFA.BackupCodesTest do
+ use Pleroma.DataCase
+
+ alias Pleroma.MFA.BackupCodes
+
+ test "generate backup codes" do
+ codes = BackupCodes.generate(number_of_codes: 2, length: 4)
+
+ assert [<<_::bytes-size(4)>>, <<_::bytes-size(4)>>] = codes
+ end
+end
diff --git a/test/mfa/totp_test.exs b/test/mfa/totp_test.exs
new file mode 100644
index 000000000..50153d208
--- /dev/null
+++ b/test/mfa/totp_test.exs
@@ -0,0 +1,17 @@
+defmodule Pleroma.MFA.TOTPTest do
+ use Pleroma.DataCase
+
+ alias Pleroma.MFA.TOTP
+
+ test "create provisioning_uri to generate qrcode" do
+ uri =
+ TOTP.provisioning_uri("test-secrcet", "test@example.com",
+ issuer: "Plerome-42",
+ digits: 8,
+ period: 60
+ )
+
+ assert uri ==
+ "otpauth://totp/test@example.com?digits=8&issuer=Plerome-42&period=60&secret=test-secrcet"
+ end
+end
diff --git a/test/mfa_test.exs b/test/mfa_test.exs
new file mode 100644
index 000000000..94bc48c26
--- /dev/null
+++ b/test/mfa_test.exs
@@ -0,0 +1,53 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2018 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.MFATest do
+ use Pleroma.DataCase
+
+ import Pleroma.Factory
+ alias Comeonin.Pbkdf2
+ alias Pleroma.MFA
+
+ describe "mfa_settings" do
+ test "returns settings user's" do
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ totp: %MFA.Settings.TOTP{secret: "xx", confirmed: true}
+ }
+ )
+
+ settings = MFA.mfa_settings(user)
+ assert match?(^settings, %{enabled: true, totp: true})
+ end
+ end
+
+ describe "generate backup codes" do
+ test "returns backup codes" do
+ user = insert(:user)
+
+ {:ok, [code1, code2]} = MFA.generate_backup_codes(user)
+ updated_user = refresh_record(user)
+ [hash1, hash2] = updated_user.multi_factor_authentication_settings.backup_codes
+ assert Pbkdf2.checkpw(code1, hash1)
+ assert Pbkdf2.checkpw(code2, hash2)
+ end
+ end
+
+ describe "invalidate_backup_code" do
+ test "invalid used code" do
+ user = insert(:user)
+
+ {:ok, _} = MFA.generate_backup_codes(user)
+ user = refresh_record(user)
+ assert length(user.multi_factor_authentication_settings.backup_codes) == 2
+ [hash_code | _] = user.multi_factor_authentication_settings.backup_codes
+
+ {:ok, user} = MFA.invalidate_backup_code(user, hash_code)
+
+ assert length(user.multi_factor_authentication_settings.backup_codes) == 1
+ end
+ end
+end
diff --git a/test/plugs/ensure_authenticated_plug_test.exs b/test/plugs/ensure_authenticated_plug_test.exs
index 4e6142aab..a0667c5e0 100644
--- a/test/plugs/ensure_authenticated_plug_test.exs
+++ b/test/plugs/ensure_authenticated_plug_test.exs
@@ -24,6 +24,31 @@ defmodule Pleroma.Plugs.EnsureAuthenticatedPlugTest do
end
end
+ test "it halts if user is assigned and MFA enabled", %{conn: conn} do
+ conn =
+ conn
+ |> assign(:user, %User{multi_factor_authentication_settings: %{enabled: true}})
+ |> assign(:auth_credentials, %{password: "xd-42"})
+ |> EnsureAuthenticatedPlug.call(%{})
+
+ assert conn.status == 403
+ assert conn.halted == true
+
+ assert conn.resp_body ==
+ "{\"error\":\"Two-factor authentication enabled, you must use a access token.\"}"
+ end
+
+ test "it continues if user is assigned and MFA disabled", %{conn: conn} do
+ conn =
+ conn
+ |> assign(:user, %User{multi_factor_authentication_settings: %{enabled: false}})
+ |> assign(:auth_credentials, %{password: "xd-42"})
+ |> EnsureAuthenticatedPlug.call(%{})
+
+ refute conn.status == 403
+ refute conn.halted
+ end
+
describe "with :if_func / :unless_func options" do
setup do
%{
diff --git a/test/support/builders/user_builder.ex b/test/support/builders/user_builder.ex
index fcfea666f..0d0490714 100644
--- a/test/support/builders/user_builder.ex
+++ b/test/support/builders/user_builder.ex
@@ -11,6 +11,7 @@ defmodule Pleroma.Builders.UserBuilder do
bio: "A tester.",
ap_id: "some id",
last_digest_emailed_at: NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second),
+ multi_factor_authentication_settings: %Pleroma.MFA.Settings{},
notification_settings: %Pleroma.User.NotificationSetting{}
}
diff --git a/test/support/factory.ex b/test/support/factory.ex
index 495764782..c8c45e2a7 100644
--- a/test/support/factory.ex
+++ b/test/support/factory.ex
@@ -33,7 +33,8 @@ defmodule Pleroma.Factory do
bio: sequence(:bio, &"Tester Number #{&1}"),
last_digest_emailed_at: NaiveDateTime.utc_now(),
last_refreshed_at: NaiveDateTime.utc_now(),
- notification_settings: %Pleroma.User.NotificationSetting{}
+ notification_settings: %Pleroma.User.NotificationSetting{},
+ multi_factor_authentication_settings: %Pleroma.MFA.Settings{}
}
%{
@@ -422,4 +423,13 @@ defmodule Pleroma.Factory do
last_read_id: "1"
}
end
+
+ def mfa_token_factory do
+ %Pleroma.MFA.Token{
+ token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false),
+ authorization: build(:oauth_authorization),
+ valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10),
+ user: build(:user)
+ }
+ end
end
diff --git a/test/user_search_test.exs b/test/user_search_test.exs
index cb847b516..17c63322a 100644
--- a/test/user_search_test.exs
+++ b/test/user_search_test.exs
@@ -172,6 +172,7 @@ defmodule Pleroma.UserSearchTest do
|> Map.put(:search_rank, nil)
|> Map.put(:search_type, nil)
|> Map.put(:last_digest_emailed_at, nil)
+ |> Map.put(:multi_factor_authentication_settings, nil)
|> Map.put(:notification_settings, nil)
assert user == expected
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 7ab7cc15c..4697af50e 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -14,6 +14,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
alias Pleroma.Config
alias Pleroma.ConfigDB
alias Pleroma.HTML
+ alias Pleroma.MFA
alias Pleroma.ModerationLog
alias Pleroma.Repo
alias Pleroma.ReportNote
@@ -1278,6 +1279,38 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
"@#{admin.nickname} deactivated users: @#{user.nickname}"
end
+ describe "PUT disable_mfa" do
+ test "returns 200 and disable 2fa", %{conn: conn} do
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ totp: %MFA.Settings.TOTP{secret: "otp_secret", confirmed: true}
+ }
+ )
+
+ response =
+ conn
+ |> put("/api/pleroma/admin/users/disable_mfa", %{nickname: user.nickname})
+ |> json_response(200)
+
+ assert response == user.nickname
+ mfa_settings = refresh_record(user).multi_factor_authentication_settings
+
+ refute mfa_settings.enabled
+ refute mfa_settings.totp.confirmed
+ end
+
+ test "returns 404 if user not found", %{conn: conn} do
+ response =
+ conn
+ |> put("/api/pleroma/admin/users/disable_mfa", %{nickname: "nickname"})
+ |> json_response(404)
+
+ assert response == "Not found"
+ end
+ end
+
describe "POST /api/pleroma/admin/users/invite_token" do
test "without options", %{conn: conn} do
conn = post(conn, "/api/pleroma/admin/users/invite_token")
diff --git a/test/web/auth/pleroma_authenticator_test.exs b/test/web/auth/pleroma_authenticator_test.exs
new file mode 100644
index 000000000..7125c5081
--- /dev/null
+++ b/test/web/auth/pleroma_authenticator_test.exs
@@ -0,0 +1,43 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.Auth.PleromaAuthenticatorTest do
+ use Pleroma.Web.ConnCase
+
+ alias Pleroma.Web.Auth.PleromaAuthenticator
+ import Pleroma.Factory
+
+ setup do
+ password = "testpassword"
+ name = "AgentSmith"
+ user = insert(:user, nickname: name, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
+ {:ok, [user: user, name: name, password: password]}
+ end
+
+ test "get_user/authorization", %{user: user, name: name, password: password} do
+ params = %{"authorization" => %{"name" => name, "password" => password}}
+ res = PleromaAuthenticator.get_user(%Plug.Conn{params: params})
+
+ assert {:ok, user} == res
+ end
+
+ test "get_user/authorization with invalid password", %{name: name} do
+ params = %{"authorization" => %{"name" => name, "password" => "password"}}
+ res = PleromaAuthenticator.get_user(%Plug.Conn{params: params})
+
+ assert {:error, {:checkpw, false}} == res
+ end
+
+ test "get_user/grant_type_password", %{user: user, name: name, password: password} do
+ params = %{"grant_type" => "password", "username" => name, "password" => password}
+ res = PleromaAuthenticator.get_user(%Plug.Conn{params: params})
+
+ assert {:ok, user} == res
+ end
+
+ test "error credintails" do
+ res = PleromaAuthenticator.get_user(%Plug.Conn{params: %{}})
+ assert {:error, :invalid_credentials} == res
+ end
+end
diff --git a/test/web/auth/totp_authenticator_test.exs b/test/web/auth/totp_authenticator_test.exs
new file mode 100644
index 000000000..e08069490
--- /dev/null
+++ b/test/web/auth/totp_authenticator_test.exs
@@ -0,0 +1,51 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.Auth.TOTPAuthenticatorTest do
+ use Pleroma.Web.ConnCase
+
+ alias Pleroma.MFA
+ alias Pleroma.MFA.BackupCodes
+ alias Pleroma.MFA.TOTP
+ alias Pleroma.Web.Auth.TOTPAuthenticator
+
+ import Pleroma.Factory
+
+ test "verify token" do
+ otp_secret = TOTP.generate_secret()
+ otp_token = TOTP.generate_token(otp_secret)
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
+ }
+ )
+
+ assert TOTPAuthenticator.verify(otp_token, user) == {:ok, :pass}
+ assert TOTPAuthenticator.verify(nil, user) == {:error, :invalid_token}
+ assert TOTPAuthenticator.verify("", user) == {:error, :invalid_token}
+ end
+
+ test "checks backup codes" do
+ [code | _] = backup_codes = BackupCodes.generate()
+
+ hashed_codes =
+ backup_codes
+ |> Enum.map(&Comeonin.Pbkdf2.hashpwsalt(&1))
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ backup_codes: hashed_codes,
+ totp: %MFA.Settings.TOTP{secret: "otp_secret", confirmed: true}
+ }
+ )
+
+ assert TOTPAuthenticator.verify_recovery_code(user, code) == {:ok, :pass}
+ refute TOTPAuthenticator.verify_recovery_code(code, refresh_record(user)) == {:ok, :pass}
+ end
+end
diff --git a/test/web/oauth/mfa_controller_test.exs b/test/web/oauth/mfa_controller_test.exs
new file mode 100644
index 000000000..ce4a07320
--- /dev/null
+++ b/test/web/oauth/mfa_controller_test.exs
@@ -0,0 +1,306 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2018 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.OAuth.MFAControllerTest do
+ use Pleroma.Web.ConnCase
+ import Pleroma.Factory
+
+ alias Pleroma.MFA
+ alias Pleroma.MFA.BackupCodes
+ alias Pleroma.MFA.TOTP
+ alias Pleroma.Repo
+ alias Pleroma.Web.OAuth.Authorization
+ alias Pleroma.Web.OAuth.OAuthController
+
+ setup %{conn: conn} do
+ otp_secret = TOTP.generate_secret()
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ backup_codes: [Comeonin.Pbkdf2.hashpwsalt("test-code")],
+ totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
+ }
+ )
+
+ app = insert(:oauth_app)
+ {:ok, conn: conn, user: user, app: app}
+ end
+
+ describe "show" do
+ setup %{conn: conn, user: user, app: app} do
+ mfa_token =
+ insert(:mfa_token,
+ user: user,
+ authorization: build(:oauth_authorization, app: app, scopes: ["write"])
+ )
+
+ {:ok, conn: conn, mfa_token: mfa_token}
+ end
+
+ test "GET /oauth/mfa renders mfa forms", %{conn: conn, mfa_token: mfa_token} do
+ conn =
+ get(
+ conn,
+ "/oauth/mfa",
+ %{
+ "mfa_token" => mfa_token.token,
+ "state" => "a_state",
+ "redirect_uri" => "http://localhost:8080/callback"
+ }
+ )
+
+ assert response = html_response(conn, 200)
+ assert response =~ "Two-factor authentication"
+ assert response =~ mfa_token.token
+ assert response =~ "http://localhost:8080/callback"
+ end
+
+ test "GET /oauth/mfa renders mfa recovery forms", %{conn: conn, mfa_token: mfa_token} do
+ conn =
+ get(
+ conn,
+ "/oauth/mfa",
+ %{
+ "mfa_token" => mfa_token.token,
+ "state" => "a_state",
+ "redirect_uri" => "http://localhost:8080/callback",
+ "challenge_type" => "recovery"
+ }
+ )
+
+ assert response = html_response(conn, 200)
+ assert response =~ "Two-factor recovery"
+ assert response =~ mfa_token.token
+ assert response =~ "http://localhost:8080/callback"
+ end
+ end
+
+ describe "verify" do
+ setup %{conn: conn, user: user, app: app} do
+ mfa_token =
+ insert(:mfa_token,
+ user: user,
+ authorization: build(:oauth_authorization, app: app, scopes: ["write"])
+ )
+
+ {:ok, conn: conn, user: user, mfa_token: mfa_token, app: app}
+ end
+
+ test "POST /oauth/mfa/verify, verify totp code", %{
+ conn: conn,
+ user: user,
+ mfa_token: mfa_token,
+ app: app
+ } do
+ otp_token = TOTP.generate_token(user.multi_factor_authentication_settings.totp.secret)
+
+ conn =
+ conn
+ |> post("/oauth/mfa/verify", %{
+ "mfa" => %{
+ "mfa_token" => mfa_token.token,
+ "challenge_type" => "totp",
+ "code" => otp_token,
+ "state" => "a_state",
+ "redirect_uri" => OAuthController.default_redirect_uri(app)
+ }
+ })
+
+ target = redirected_to(conn)
+ target_url = %URI{URI.parse(target) | query: nil} |> URI.to_string()
+ query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
+ assert %{"state" => "a_state", "code" => code} = query
+ assert target_url == OAuthController.default_redirect_uri(app)
+ auth = Repo.get_by(Authorization, token: code)
+ assert auth.scopes == ["write"]
+ end
+
+ test "POST /oauth/mfa/verify, verify recovery code", %{
+ conn: conn,
+ mfa_token: mfa_token,
+ app: app
+ } do
+ conn =
+ conn
+ |> post("/oauth/mfa/verify", %{
+ "mfa" => %{
+ "mfa_token" => mfa_token.token,
+ "challenge_type" => "recovery",
+ "code" => "test-code",
+ "state" => "a_state",
+ "redirect_uri" => OAuthController.default_redirect_uri(app)
+ }
+ })
+
+ target = redirected_to(conn)
+ target_url = %URI{URI.parse(target) | query: nil} |> URI.to_string()
+ query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
+ assert %{"state" => "a_state", "code" => code} = query
+ assert target_url == OAuthController.default_redirect_uri(app)
+ auth = Repo.get_by(Authorization, token: code)
+ assert auth.scopes == ["write"]
+ end
+ end
+
+ describe "challenge/totp" do
+ test "returns access token with valid code", %{conn: conn, user: user, app: app} do
+ otp_token = TOTP.generate_token(user.multi_factor_authentication_settings.totp.secret)
+
+ mfa_token =
+ insert(:mfa_token,
+ user: user,
+ authorization: build(:oauth_authorization, app: app, scopes: ["write"])
+ )
+
+ response =
+ conn
+ |> post("/oauth/mfa/challenge", %{
+ "mfa_token" => mfa_token.token,
+ "challenge_type" => "totp",
+ "code" => otp_token,
+ "client_id" => app.client_id,
+ "client_secret" => app.client_secret
+ })
+ |> json_response(:ok)
+
+ ap_id = user.ap_id
+
+ assert match?(
+ %{
+ "access_token" => _,
+ "expires_in" => 600,
+ "me" => ^ap_id,
+ "refresh_token" => _,
+ "scope" => "write",
+ "token_type" => "Bearer"
+ },
+ response
+ )
+ end
+
+ test "returns errors when mfa token invalid", %{conn: conn, user: user, app: app} do
+ otp_token = TOTP.generate_token(user.multi_factor_authentication_settings.totp.secret)
+
+ response =
+ conn
+ |> post("/oauth/mfa/challenge", %{
+ "mfa_token" => "XXX",
+ "challenge_type" => "totp",
+ "code" => otp_token,
+ "client_id" => app.client_id,
+ "client_secret" => app.client_secret
+ })
+ |> json_response(400)
+
+ assert response == %{"error" => "Invalid code"}
+ end
+
+ test "returns error when otp code is invalid", %{conn: conn, user: user, app: app} do
+ mfa_token = insert(:mfa_token, user: user)
+
+ response =
+ conn
+ |> post("/oauth/mfa/challenge", %{
+ "mfa_token" => mfa_token.token,
+ "challenge_type" => "totp",
+ "code" => "XXX",
+ "client_id" => app.client_id,
+ "client_secret" => app.client_secret
+ })
+ |> json_response(400)
+
+ assert response == %{"error" => "Invalid code"}
+ end
+
+ test "returns error when client credentails is wrong ", %{conn: conn, user: user} do
+ otp_token = TOTP.generate_token(user.multi_factor_authentication_settings.totp.secret)
+ mfa_token = insert(:mfa_token, user: user)
+
+ response =
+ conn
+ |> post("/oauth/mfa/challenge", %{
+ "mfa_token" => mfa_token.token,
+ "challenge_type" => "totp",
+ "code" => otp_token,
+ "client_id" => "xxx",
+ "client_secret" => "xxx"
+ })
+ |> json_response(400)
+
+ assert response == %{"error" => "Invalid code"}
+ end
+ end
+
+ describe "challenge/recovery" do
+ setup %{conn: conn} do
+ app = insert(:oauth_app)
+ {:ok, conn: conn, app: app}
+ end
+
+ test "returns access token with valid code", %{conn: conn, app: app} do
+ otp_secret = TOTP.generate_secret()
+
+ [code | _] = backup_codes = BackupCodes.generate()
+
+ hashed_codes =
+ backup_codes
+ |> Enum.map(&Comeonin.Pbkdf2.hashpwsalt(&1))
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ backup_codes: hashed_codes,
+ totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
+ }
+ )
+
+ mfa_token =
+ insert(:mfa_token,
+ user: user,
+ authorization: build(:oauth_authorization, app: app, scopes: ["write"])
+ )
+
+ response =
+ conn
+ |> post("/oauth/mfa/challenge", %{
+ "mfa_token" => mfa_token.token,
+ "challenge_type" => "recovery",
+ "code" => code,
+ "client_id" => app.client_id,
+ "client_secret" => app.client_secret
+ })
+ |> json_response(:ok)
+
+ ap_id = user.ap_id
+
+ assert match?(
+ %{
+ "access_token" => _,
+ "expires_in" => 600,
+ "me" => ^ap_id,
+ "refresh_token" => _,
+ "scope" => "write",
+ "token_type" => "Bearer"
+ },
+ response
+ )
+
+ error_response =
+ conn
+ |> post("/oauth/mfa/challenge", %{
+ "mfa_token" => mfa_token.token,
+ "challenge_type" => "recovery",
+ "code" => code,
+ "client_id" => app.client_id,
+ "client_secret" => app.client_secret
+ })
+ |> json_response(400)
+
+ assert error_response == %{"error" => "Invalid code"}
+ end
+ end
+end
diff --git a/test/web/oauth/oauth_controller_test.exs b/test/web/oauth/oauth_controller_test.exs
index f2f98d768..7a107584d 100644
--- a/test/web/oauth/oauth_controller_test.exs
+++ b/test/web/oauth/oauth_controller_test.exs
@@ -6,6 +6,8 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
use Pleroma.Web.ConnCase
import Pleroma.Factory
+ alias Pleroma.MFA
+ alias Pleroma.MFA.TOTP
alias Pleroma.Repo
alias Pleroma.User
alias Pleroma.Web.OAuth.Authorization
@@ -604,6 +606,41 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
end
end
+ test "redirect to on two-factor auth page" do
+ otp_secret = TOTP.generate_secret()
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
+ }
+ )
+
+ app = insert(:oauth_app, scopes: ["read", "write", "follow"])
+
+ conn =
+ build_conn()
+ |> post("/oauth/authorize", %{
+ "authorization" => %{
+ "name" => user.nickname,
+ "password" => "test",
+ "client_id" => app.client_id,
+ "redirect_uri" => app.redirect_uris,
+ "scope" => "read write",
+ "state" => "statepassed"
+ }
+ })
+
+ result = html_response(conn, 200)
+
+ mfa_token = Repo.get_by(MFA.Token, user_id: user.id)
+ assert result =~ app.redirect_uris
+ assert result =~ "statepassed"
+ assert result =~ mfa_token.token
+ assert result =~ "Two-factor authentication"
+ end
+
test "returns 401 for wrong credentials", %{conn: conn} do
user = insert(:user)
app = insert(:oauth_app)
@@ -735,6 +772,46 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
assert token.scopes == app.scopes
end
+ test "issues a mfa token for `password` grant_type, when MFA enabled" do
+ password = "testpassword"
+ otp_secret = TOTP.generate_secret()
+
+ user =
+ insert(:user,
+ password_hash: Comeonin.Pbkdf2.hashpwsalt(password),
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
+ }
+ )
+
+ app = insert(:oauth_app, scopes: ["read", "write"])
+
+ response =
+ build_conn()
+ |> post("/oauth/token", %{
+ "grant_type" => "password",
+ "username" => user.nickname,
+ "password" => password,
+ "client_id" => app.client_id,
+ "client_secret" => app.client_secret
+ })
+ |> json_response(403)
+
+ assert match?(
+ %{
+ "supported_challenge_types" => "totp",
+ "mfa_token" => _,
+ "error" => "mfa_required"
+ },
+ response
+ )
+
+ token = Repo.get_by(MFA.Token, token: response["mfa_token"])
+ assert token.user_id == user.id
+ assert token.authorization_id
+ end
+
test "issues a token for request with HTTP basic auth client credentials" do
user = insert(:user)
app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])
diff --git a/test/web/pleroma_api/controllers/two_factor_authentication_controller_test.exs b/test/web/pleroma_api/controllers/two_factor_authentication_controller_test.exs
new file mode 100644
index 000000000..d23d08a00
--- /dev/null
+++ b/test/web/pleroma_api/controllers/two_factor_authentication_controller_test.exs
@@ -0,0 +1,260 @@
+defmodule Pleroma.Web.PleromaAPI.TwoFactorAuthenticationControllerTest do
+ use Pleroma.Web.ConnCase
+
+ import Pleroma.Factory
+ alias Pleroma.MFA.Settings
+ alias Pleroma.MFA.TOTP
+
+ describe "GET /api/pleroma/accounts/mfa/settings" do
+ test "returns user mfa settings for new user", %{conn: conn} do
+ token = insert(:oauth_token, scopes: ["read", "follow"])
+ token2 = insert(:oauth_token, scopes: ["write"])
+
+ assert conn
+ |> put_req_header("authorization", "Bearer #{token.token}")
+ |> get("/api/pleroma/accounts/mfa")
+ |> json_response(:ok) == %{
+ "settings" => %{"enabled" => false, "totp" => false}
+ }
+
+ assert conn
+ |> put_req_header("authorization", "Bearer #{token2.token}")
+ |> get("/api/pleroma/accounts/mfa")
+ |> json_response(403) == %{
+ "error" => "Insufficient permissions: read:security."
+ }
+ end
+
+ test "returns user mfa settings with enabled totp", %{conn: conn} do
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %Settings{
+ enabled: true,
+ totp: %Settings.TOTP{secret: "XXX", delivery_type: "app", confirmed: true}
+ }
+ )
+
+ token = insert(:oauth_token, scopes: ["read", "follow"], user: user)
+
+ assert conn
+ |> put_req_header("authorization", "Bearer #{token.token}")
+ |> get("/api/pleroma/accounts/mfa")
+ |> json_response(:ok) == %{
+ "settings" => %{"enabled" => true, "totp" => true}
+ }
+ end
+ end
+
+ describe "GET /api/pleroma/accounts/mfa/backup_codes" do
+ test "returns backup codes", %{conn: conn} do
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %Settings{
+ backup_codes: ["1", "2", "3"],
+ totp: %Settings.TOTP{secret: "secret"}
+ }
+ )
+
+ token = insert(:oauth_token, scopes: ["write", "follow"], user: user)
+ token2 = insert(:oauth_token, scopes: ["read"])
+
+ response =
+ conn
+ |> put_req_header("authorization", "Bearer #{token.token}")
+ |> get("/api/pleroma/accounts/mfa/backup_codes")
+ |> json_response(:ok)
+
+ assert [<<_::bytes-size(6)>>, <<_::bytes-size(6)>>] = response["codes"]
+ user = refresh_record(user)
+ mfa_settings = user.multi_factor_authentication_settings
+ assert mfa_settings.totp.secret == "secret"
+ refute mfa_settings.backup_codes == ["1", "2", "3"]
+ refute mfa_settings.backup_codes == []
+
+ assert conn
+ |> put_req_header("authorization", "Bearer #{token2.token}")
+ |> get("/api/pleroma/accounts/mfa/backup_codes")
+ |> json_response(403) == %{
+ "error" => "Insufficient permissions: write:security."
+ }
+ end
+ end
+
+ describe "GET /api/pleroma/accounts/mfa/setup/totp" do
+ test "return errors when method is invalid", %{conn: conn} do
+ user = insert(:user)
+ token = insert(:oauth_token, scopes: ["write", "follow"], user: user)
+
+ response =
+ conn
+ |> put_req_header("authorization", "Bearer #{token.token}")
+ |> get("/api/pleroma/accounts/mfa/setup/torf")
+ |> json_response(400)
+
+ assert response == %{"error" => "undefined method"}
+ end
+
+ test "returns key and provisioning_uri", %{conn: conn} do
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %Settings{backup_codes: ["1", "2", "3"]}
+ )
+
+ token = insert(:oauth_token, scopes: ["write", "follow"], user: user)
+ token2 = insert(:oauth_token, scopes: ["read"])
+
+ response =
+ conn
+ |> put_req_header("authorization", "Bearer #{token.token}")
+ |> get("/api/pleroma/accounts/mfa/setup/totp")
+ |> json_response(:ok)
+
+ user = refresh_record(user)
+ mfa_settings = user.multi_factor_authentication_settings
+ secret = mfa_settings.totp.secret
+ refute mfa_settings.enabled
+ assert mfa_settings.backup_codes == ["1", "2", "3"]
+
+ assert response == %{
+ "key" => secret,
+ "provisioning_uri" => TOTP.provisioning_uri(secret, "#{user.email}")
+ }
+
+ assert conn
+ |> put_req_header("authorization", "Bearer #{token2.token}")
+ |> get("/api/pleroma/accounts/mfa/setup/totp")
+ |> json_response(403) == %{
+ "error" => "Insufficient permissions: write:security."
+ }
+ end
+ end
+
+ describe "GET /api/pleroma/accounts/mfa/confirm/totp" do
+ test "returns success result", %{conn: conn} do
+ secret = TOTP.generate_secret()
+ code = TOTP.generate_token(secret)
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %Settings{
+ backup_codes: ["1", "2", "3"],
+ totp: %Settings.TOTP{secret: secret}
+ }
+ )
+
+ token = insert(:oauth_token, scopes: ["write", "follow"], user: user)
+ token2 = insert(:oauth_token, scopes: ["read"])
+
+ assert conn
+ |> put_req_header("authorization", "Bearer #{token.token}")
+ |> post("/api/pleroma/accounts/mfa/confirm/totp", %{password: "test", code: code})
+ |> json_response(:ok)
+
+ settings = refresh_record(user).multi_factor_authentication_settings
+ assert settings.enabled
+ assert settings.totp.secret == secret
+ assert settings.totp.confirmed
+ assert settings.backup_codes == ["1", "2", "3"]
+
+ assert conn
+ |> put_req_header("authorization", "Bearer #{token2.token}")
+ |> post("/api/pleroma/accounts/mfa/confirm/totp", %{password: "test", code: code})
+ |> json_response(403) == %{
+ "error" => "Insufficient permissions: write:security."
+ }
+ end
+
+ test "returns error if password incorrect", %{conn: conn} do
+ secret = TOTP.generate_secret()
+ code = TOTP.generate_token(secret)
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %Settings{
+ backup_codes: ["1", "2", "3"],
+ totp: %Settings.TOTP{secret: secret}
+ }
+ )
+
+ token = insert(:oauth_token, scopes: ["write", "follow"], user: user)
+
+ response =
+ conn
+ |> put_req_header("authorization", "Bearer #{token.token}")
+ |> post("/api/pleroma/accounts/mfa/confirm/totp", %{password: "xxx", code: code})
+ |> json_response(422)
+
+ settings = refresh_record(user).multi_factor_authentication_settings
+ refute settings.enabled
+ refute settings.totp.confirmed
+ assert settings.backup_codes == ["1", "2", "3"]
+ assert response == %{"error" => "Invalid password."}
+ end
+
+ test "returns error if code incorrect", %{conn: conn} do
+ secret = TOTP.generate_secret()
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %Settings{
+ backup_codes: ["1", "2", "3"],
+ totp: %Settings.TOTP{secret: secret}
+ }
+ )
+
+ token = insert(:oauth_token, scopes: ["write", "follow"], user: user)
+ token2 = insert(:oauth_token, scopes: ["read"])
+
+ response =
+ conn
+ |> put_req_header("authorization", "Bearer #{token.token}")
+ |> post("/api/pleroma/accounts/mfa/confirm/totp", %{password: "test", code: "code"})
+ |> json_response(422)
+
+ settings = refresh_record(user).multi_factor_authentication_settings
+ refute settings.enabled
+ refute settings.totp.confirmed
+ assert settings.backup_codes == ["1", "2", "3"]
+ assert response == %{"error" => "invalid_token"}
+
+ assert conn
+ |> put_req_header("authorization", "Bearer #{token2.token}")
+ |> post("/api/pleroma/accounts/mfa/confirm/totp", %{password: "test", code: "code"})
+ |> json_response(403) == %{
+ "error" => "Insufficient permissions: write:security."
+ }
+ end
+ end
+
+ describe "DELETE /api/pleroma/accounts/mfa/totp" do
+ test "returns success result", %{conn: conn} do
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %Settings{
+ backup_codes: ["1", "2", "3"],
+ totp: %Settings.TOTP{secret: "secret"}
+ }
+ )
+
+ token = insert(:oauth_token, scopes: ["write", "follow"], user: user)
+ token2 = insert(:oauth_token, scopes: ["read"])
+
+ assert conn
+ |> put_req_header("authorization", "Bearer #{token.token}")
+ |> delete("/api/pleroma/accounts/mfa/totp", %{password: "test"})
+ |> json_response(:ok)
+
+ settings = refresh_record(user).multi_factor_authentication_settings
+ refute settings.enabled
+ assert settings.totp.secret == nil
+ refute settings.totp.confirmed
+
+ assert conn
+ |> put_req_header("authorization", "Bearer #{token2.token}")
+ |> delete("/api/pleroma/accounts/mfa/totp", %{password: "test"})
+ |> json_response(403) == %{
+ "error" => "Insufficient permissions: write:security."
+ }
+ end
+ end
+end
diff --git a/test/web/twitter_api/remote_follow_controller_test.exs b/test/web/twitter_api/remote_follow_controller_test.exs
index 5ff8694a8..f7e54c26a 100644
--- a/test/web/twitter_api/remote_follow_controller_test.exs
+++ b/test/web/twitter_api/remote_follow_controller_test.exs
@@ -6,11 +6,14 @@ defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do
use Pleroma.Web.ConnCase
alias Pleroma.Config
+ alias Pleroma.MFA
+ alias Pleroma.MFA.TOTP
alias Pleroma.User
alias Pleroma.Web.CommonAPI
import ExUnit.CaptureLog
import Pleroma.Factory
+ import Ecto.Query
setup do
Tesla.Mock.mock(fn env -> apply(HttpRequestMock, :request, [env]) end)
@@ -160,6 +163,119 @@ defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do
end
end
+ describe "POST /ostatus_subscribe - follow/2 with enabled Two-Factor Auth " do
+ test "render the MFA login form", %{conn: conn} do
+ otp_secret = TOTP.generate_secret()
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
+ }
+ )
+
+ user2 = insert(:user)
+
+ response =
+ conn
+ |> post(remote_follow_path(conn, :do_follow), %{
+ "authorization" => %{"name" => user.nickname, "password" => "test", "id" => user2.id}
+ })
+ |> response(200)
+
+ mfa_token = Pleroma.Repo.one(from(q in Pleroma.MFA.Token, where: q.user_id == ^user.id))
+
+ assert response =~ "Two-factor authentication"
+ assert response =~ "Authentication code"
+ assert response =~ mfa_token.token
+ refute user2.follower_address in User.following(user)
+ end
+
+ test "returns error when password is incorrect", %{conn: conn} do
+ otp_secret = TOTP.generate_secret()
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
+ }
+ )
+
+ user2 = insert(:user)
+
+ response =
+ conn
+ |> post(remote_follow_path(conn, :do_follow), %{
+ "authorization" => %{"name" => user.nickname, "password" => "test1", "id" => user2.id}
+ })
+ |> response(200)
+
+ assert response =~ "Wrong username or password"
+ refute user2.follower_address in User.following(user)
+ end
+
+ test "follows", %{conn: conn} do
+ otp_secret = TOTP.generate_secret()
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
+ }
+ )
+
+ {:ok, %{token: token}} = MFA.Token.create_token(user)
+
+ user2 = insert(:user)
+ otp_token = TOTP.generate_token(otp_secret)
+
+ conn =
+ conn
+ |> post(
+ remote_follow_path(conn, :do_follow),
+ %{
+ "mfa" => %{"code" => otp_token, "token" => token, "id" => user2.id}
+ }
+ )
+
+ assert redirected_to(conn) == "/users/#{user2.id}"
+ assert user2.follower_address in User.following(user)
+ end
+
+ test "returns error when auth code is incorrect", %{conn: conn} do
+ otp_secret = TOTP.generate_secret()
+
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
+ }
+ )
+
+ {:ok, %{token: token}} = MFA.Token.create_token(user)
+
+ user2 = insert(:user)
+ otp_token = TOTP.generate_token(TOTP.generate_secret())
+
+ response =
+ conn
+ |> post(
+ remote_follow_path(conn, :do_follow),
+ %{
+ "mfa" => %{"code" => otp_token, "token" => token, "id" => user2.id}
+ }
+ )
+ |> response(200)
+
+ assert response =~ "Wrong authentication code"
+ refute user2.follower_address in User.following(user)
+ end
+ end
+
describe "POST /ostatus_subscribe - follow/2 without assigned user " do
test "follows", %{conn: conn} do
user = insert(:user)
--
cgit v1.2.3
From 9491ba3e49450e80cd1c21358c01e4e06e3d881d Mon Sep 17 00:00:00 2001
From: href
Date: Thu, 7 May 2020 09:13:32 +0000
Subject: Streamer rework
---
test/integration/mastodon_websocket_test.exs | 7 +-
test/notification_test.exs | 18 +-
test/support/builders/activity_builder.ex | 10 +-
test/support/conn_case.ex | 6 +-
test/support/data_case.ex | 6 +-
test/web/streamer/ping_test.exs | 36 --
test/web/streamer/state_test.exs | 54 ---
test/web/streamer/streamer_test.exs | 594 ++++++++++-----------------
8 files changed, 243 insertions(+), 488 deletions(-)
delete mode 100644 test/web/streamer/ping_test.exs
delete mode 100644 test/web/streamer/state_test.exs
(limited to 'test')
diff --git a/test/integration/mastodon_websocket_test.exs b/test/integration/mastodon_websocket_test.exs
index bd229c55f..109c7b4cb 100644
--- a/test/integration/mastodon_websocket_test.exs
+++ b/test/integration/mastodon_websocket_test.exs
@@ -12,17 +12,14 @@ defmodule Pleroma.Integration.MastodonWebsocketTest do
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.OAuth
+ @moduletag needs_streamer: true, capture_log: true
+
@path Pleroma.Web.Endpoint.url()
|> URI.parse()
|> Map.put(:scheme, "ws")
|> Map.put(:path, "/api/v1/streaming")
|> URI.to_string()
- setup_all do
- start_supervised(Pleroma.Web.Streamer.supervisor())
- :ok
- end
-
def start_socket(qs \\ nil, headers \\ []) do
path =
case qs do
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 601a6c0ca..5c85f3368 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -162,14 +162,18 @@ defmodule Pleroma.NotificationTest do
@tag needs_streamer: true
test "it creates a notification for user and send to the 'user' and the 'user:notification' stream" do
user = insert(:user)
- task = Task.async(fn -> assert_receive {:text, _}, 4_000 end)
- task_user_notification = Task.async(fn -> assert_receive {:text, _}, 4_000 end)
- Streamer.add_socket("user", %{transport_pid: task.pid, assigns: %{user: user}})
- Streamer.add_socket(
- "user:notification",
- %{transport_pid: task_user_notification.pid, assigns: %{user: user}}
- )
+ task =
+ Task.async(fn ->
+ Streamer.add_socket("user", user)
+ assert_receive {:render_with_user, _, _, _}, 4_000
+ end)
+
+ task_user_notification =
+ Task.async(fn ->
+ Streamer.add_socket("user:notification", user)
+ assert_receive {:render_with_user, _, _, _}, 4_000
+ end)
activity = insert(:note_activity)
diff --git a/test/support/builders/activity_builder.ex b/test/support/builders/activity_builder.ex
index 6e5a8e059..7c4950bfa 100644
--- a/test/support/builders/activity_builder.ex
+++ b/test/support/builders/activity_builder.ex
@@ -21,7 +21,15 @@ defmodule Pleroma.Builders.ActivityBuilder do
def insert(data \\ %{}, opts \\ %{}) do
activity = build(data, opts)
- ActivityPub.insert(activity)
+
+ case ActivityPub.insert(activity) do
+ ok = {:ok, activity} ->
+ ActivityPub.notify_and_stream(activity)
+ ok
+
+ error ->
+ error
+ end
end
def insert_list(times, data \\ %{}, opts \\ %{}) do
diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex
index 91c03b1a8..b23918dd1 100644
--- a/test/support/conn_case.ex
+++ b/test/support/conn_case.ex
@@ -139,7 +139,11 @@ defmodule Pleroma.Web.ConnCase do
end
if tags[:needs_streamer] do
- start_supervised(Pleroma.Web.Streamer.supervisor())
+ start_supervised(%{
+ id: Pleroma.Web.Streamer.registry(),
+ start:
+ {Registry, :start_link, [[keys: :duplicate, name: Pleroma.Web.Streamer.registry()]]}
+ })
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
diff --git a/test/support/data_case.ex b/test/support/data_case.ex
index 1669f2520..ba8848952 100644
--- a/test/support/data_case.ex
+++ b/test/support/data_case.ex
@@ -40,7 +40,11 @@ defmodule Pleroma.DataCase do
end
if tags[:needs_streamer] do
- start_supervised(Pleroma.Web.Streamer.supervisor())
+ start_supervised(%{
+ id: Pleroma.Web.Streamer.registry(),
+ start:
+ {Registry, :start_link, [[keys: :duplicate, name: Pleroma.Web.Streamer.registry()]]}
+ })
end
:ok
diff --git a/test/web/streamer/ping_test.exs b/test/web/streamer/ping_test.exs
deleted file mode 100644
index 5df6c1cc3..000000000
--- a/test/web/streamer/ping_test.exs
+++ /dev/null
@@ -1,36 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Web.PingTest do
- use Pleroma.DataCase
-
- import Pleroma.Factory
- alias Pleroma.Web.Streamer
-
- setup do
- start_supervised({Streamer.supervisor(), [ping_interval: 30]})
-
- :ok
- end
-
- describe "sockets" do
- setup do
- user = insert(:user)
- {:ok, %{user: user}}
- end
-
- test "it sends pings", %{user: user} do
- task =
- Task.async(fn ->
- assert_receive {:text, received_event}, 40
- assert_receive {:text, received_event}, 40
- assert_receive {:text, received_event}, 40
- end)
-
- Streamer.add_socket("public", %{transport_pid: task.pid, assigns: %{user: user}})
-
- Task.await(task)
- end
- end
-end
diff --git a/test/web/streamer/state_test.exs b/test/web/streamer/state_test.exs
deleted file mode 100644
index a755e75c0..000000000
--- a/test/web/streamer/state_test.exs
+++ /dev/null
@@ -1,54 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Web.StateTest do
- use Pleroma.DataCase
-
- import Pleroma.Factory
- alias Pleroma.Web.Streamer
- alias Pleroma.Web.Streamer.StreamerSocket
-
- @moduletag needs_streamer: true
-
- describe "sockets" do
- setup do
- user = insert(:user)
- user2 = insert(:user)
- {:ok, %{user: user, user2: user2}}
- end
-
- test "it can add a socket", %{user: user} do
- Streamer.add_socket("public", %{transport_pid: 1, assigns: %{user: user}})
-
- assert(%{"public" => [%StreamerSocket{transport_pid: 1}]} = Streamer.get_sockets())
- end
-
- test "it can add multiple sockets per user", %{user: user} do
- Streamer.add_socket("public", %{transport_pid: 1, assigns: %{user: user}})
- Streamer.add_socket("public", %{transport_pid: 2, assigns: %{user: user}})
-
- assert(
- %{
- "public" => [
- %StreamerSocket{transport_pid: 2},
- %StreamerSocket{transport_pid: 1}
- ]
- } = Streamer.get_sockets()
- )
- end
-
- test "it will not add a duplicate socket", %{user: user} do
- Streamer.add_socket("activity", %{transport_pid: 1, assigns: %{user: user}})
- Streamer.add_socket("activity", %{transport_pid: 1, assigns: %{user: user}})
-
- assert(
- %{
- "activity" => [
- %StreamerSocket{transport_pid: 1}
- ]
- } = Streamer.get_sockets()
- )
- end
- end
-end
diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs
index 3c0f240f5..ee530f4e9 100644
--- a/test/web/streamer/streamer_test.exs
+++ b/test/web/streamer/streamer_test.exs
@@ -12,13 +12,9 @@ defmodule Pleroma.Web.StreamerTest do
alias Pleroma.User
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.Streamer
- alias Pleroma.Web.Streamer.StreamerSocket
- alias Pleroma.Web.Streamer.Worker
@moduletag needs_streamer: true, capture_log: true
- @streamer_timeout 150
- @streamer_start_wait 10
setup do: clear_config([:instance, :skip_thread_containment])
describe "user streams" do
@@ -29,69 +25,35 @@ defmodule Pleroma.Web.StreamerTest do
end
test "it streams the user's post in the 'user' stream", %{user: user} do
- task =
- Task.async(fn ->
- assert_receive {:text, _}, @streamer_timeout
- end)
-
- Streamer.add_socket(
- "user",
- %{transport_pid: task.pid, assigns: %{user: user}}
- )
-
+ Streamer.add_socket("user", user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
-
- Streamer.stream("user", activity)
- Task.await(task)
+ assert_receive {:render_with_user, _, _, ^activity}
+ refute Streamer.filtered_by_user?(user, activity)
end
test "it streams boosts of the user in the 'user' stream", %{user: user} do
- task =
- Task.async(fn ->
- assert_receive {:text, _}, @streamer_timeout
- end)
-
- Streamer.add_socket(
- "user",
- %{transport_pid: task.pid, assigns: %{user: user}}
- )
+ Streamer.add_socket("user", user)
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "hey"})
{:ok, announce, _} = CommonAPI.repeat(activity.id, user)
- Streamer.stream("user", announce)
- Task.await(task)
+ assert_receive {:render_with_user, Pleroma.Web.StreamerView, "update.json", ^announce}
+ refute Streamer.filtered_by_user?(user, announce)
end
test "it sends notify to in the 'user' stream", %{user: user, notify: notify} do
- task =
- Task.async(fn ->
- assert_receive {:text, _}, @streamer_timeout
- end)
-
- Streamer.add_socket(
- "user",
- %{transport_pid: task.pid, assigns: %{user: user}}
- )
-
+ Streamer.add_socket("user", user)
Streamer.stream("user", notify)
- Task.await(task)
+ assert_receive {:render_with_user, _, _, ^notify}
+ refute Streamer.filtered_by_user?(user, notify)
end
test "it sends notify to in the 'user:notification' stream", %{user: user, notify: notify} do
- task =
- Task.async(fn ->
- assert_receive {:text, _}, @streamer_timeout
- end)
-
- Streamer.add_socket(
- "user:notification",
- %{transport_pid: task.pid, assigns: %{user: user}}
- )
-
+ Streamer.add_socket("user:notification", user)
Streamer.stream("user:notification", notify)
- Task.await(task)
+ assert_receive {:render_with_user, _, _, ^notify}
+ refute Streamer.filtered_by_user?(user, notify)
end
test "it doesn't send notify to the 'user:notification' stream when a user is blocked", %{
@@ -100,18 +62,12 @@ defmodule Pleroma.Web.StreamerTest do
blocked = insert(:user)
{:ok, _user_relationship} = User.block(user, blocked)
- task = Task.async(fn -> refute_receive {:text, _}, @streamer_timeout end)
-
- Streamer.add_socket(
- "user:notification",
- %{transport_pid: task.pid, assigns: %{user: user}}
- )
+ Streamer.add_socket("user:notification", user)
{:ok, activity} = CommonAPI.post(user, %{"status" => ":("})
- {:ok, notif} = CommonAPI.favorite(blocked, activity.id)
+ {:ok, _} = CommonAPI.favorite(blocked, activity.id)
- Streamer.stream("user:notification", notif)
- Task.await(task)
+ refute_receive _
end
test "it doesn't send notify to the 'user:notification' stream when a thread is muted", %{
@@ -119,45 +75,50 @@ defmodule Pleroma.Web.StreamerTest do
} do
user2 = insert(:user)
- task = Task.async(fn -> refute_receive {:text, _}, @streamer_timeout end)
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
+ {:ok, _} = CommonAPI.add_mute(user, activity)
- Streamer.add_socket(
- "user:notification",
- %{transport_pid: task.pid, assigns: %{user: user}}
- )
+ Streamer.add_socket("user:notification", user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
- {:ok, activity} = CommonAPI.add_mute(user, activity)
- {:ok, notif} = CommonAPI.favorite(user2, activity.id)
+ {:ok, favorite_activity} = CommonAPI.favorite(user2, activity.id)
- Streamer.stream("user:notification", notif)
- Task.await(task)
+ refute_receive _
+ assert Streamer.filtered_by_user?(user, favorite_activity)
end
- test "it doesn't send notify to the 'user:notification' stream' when a domain is blocked", %{
+ test "it sends favorite to 'user:notification' stream'", %{
user: user
} do
user2 = insert(:user, %{ap_id: "https://hecking-lewd-place.com/user/meanie"})
- task = Task.async(fn -> refute_receive {:text, _}, @streamer_timeout end)
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
+ Streamer.add_socket("user:notification", user)
+ {:ok, favorite_activity} = CommonAPI.favorite(user2, activity.id)
+
+ assert_receive {:render_with_user, _, "notification.json", notif}
+ assert notif.activity.id == favorite_activity.id
+ refute Streamer.filtered_by_user?(user, notif)
+ end
- Streamer.add_socket(
- "user:notification",
- %{transport_pid: task.pid, assigns: %{user: user}}
- )
+ test "it doesn't send the 'user:notification' stream' when a domain is blocked", %{
+ user: user
+ } do
+ user2 = insert(:user, %{ap_id: "https://hecking-lewd-place.com/user/meanie"})
{:ok, user} = User.block_domain(user, "hecking-lewd-place.com")
{:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
- {:ok, notif} = CommonAPI.favorite(user2, activity.id)
+ Streamer.add_socket("user:notification", user)
+ {:ok, favorite_activity} = CommonAPI.favorite(user2, activity.id)
- Streamer.stream("user:notification", notif)
- Task.await(task)
+ refute_receive _
+ assert Streamer.filtered_by_user?(user, favorite_activity)
end
test "it sends follow activities to the 'user:notification' stream", %{
user: user
} do
user_url = user.ap_id
+ user2 = insert(:user)
body =
File.read!("test/fixtures/users_mock/localhost.json")
@@ -169,47 +130,24 @@ defmodule Pleroma.Web.StreamerTest do
%Tesla.Env{status: 200, body: body}
end)
- user2 = insert(:user)
- task = Task.async(fn -> assert_receive {:text, _}, @streamer_timeout end)
-
- Process.sleep(@streamer_start_wait)
-
- Streamer.add_socket(
- "user:notification",
- %{transport_pid: task.pid, assigns: %{user: user}}
- )
+ Streamer.add_socket("user:notification", user)
+ {:ok, _follower, _followed, follow_activity} = CommonAPI.follow(user2, user)
- {:ok, _follower, _followed, _activity} = CommonAPI.follow(user2, user)
-
- # We don't directly pipe the notification to the streamer as it's already
- # generated as a side effect of CommonAPI.follow().
- Task.await(task)
+ assert_receive {:render_with_user, _, "notification.json", notif}
+ assert notif.activity.id == follow_activity.id
+ refute Streamer.filtered_by_user?(user, notif)
end
end
- test "it sends to public" do
+ test "it sends to public authenticated" do
user = insert(:user)
other_user = insert(:user)
- task =
- Task.async(fn ->
- assert_receive {:text, _}, @streamer_timeout
- end)
-
- fake_socket = %StreamerSocket{
- transport_pid: task.pid,
- user: user
- }
-
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "Test"})
+ Streamer.add_socket("public", other_user)
- topics = %{
- "public" => [fake_socket]
- }
-
- Worker.push_to_socket(topics, "public", activity)
-
- Task.await(task)
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "Test"})
+ assert_receive {:render_with_user, _, _, ^activity}
+ refute Streamer.filtered_by_user?(user, activity)
end
test "works for deletions" do
@@ -217,37 +155,32 @@ defmodule Pleroma.Web.StreamerTest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "Test"})
- task =
- Task.async(fn ->
- expected_event =
- %{
- "event" => "delete",
- "payload" => activity.id
- }
- |> Jason.encode!()
-
- assert_receive {:text, received_event}, @streamer_timeout
- assert received_event == expected_event
- end)
+ Streamer.add_socket("public", user)
- fake_socket = %StreamerSocket{
- transport_pid: task.pid,
- user: user
- }
+ {:ok, _} = CommonAPI.delete(activity.id, other_user)
+ activity_id = activity.id
+ assert_receive {:text, event}
+ assert %{"event" => "delete", "payload" => ^activity_id} = Jason.decode!(event)
+ end
- {:ok, activity} = CommonAPI.delete(activity.id, other_user)
+ test "it sends to public unauthenticated" do
+ user = insert(:user)
- topics = %{
- "public" => [fake_socket]
- }
+ Streamer.add_socket("public", nil)
- Worker.push_to_socket(topics, "public", activity)
+ {:ok, activity} = CommonAPI.post(user, %{"status" => "Test"})
+ activity_id = activity.id
+ assert_receive {:text, event}
+ assert %{"event" => "update", "payload" => payload} = Jason.decode!(event)
+ assert %{"id" => ^activity_id} = Jason.decode!(payload)
- Task.await(task)
+ {:ok, _} = CommonAPI.delete(activity.id, user)
+ assert_receive {:text, event}
+ assert %{"event" => "delete", "payload" => ^activity_id} = Jason.decode!(event)
end
describe "thread_containment" do
- test "it doesn't send to user if recipients invalid and thread containment is enabled" do
+ test "it filters to user if recipients invalid and thread containment is enabled" do
Pleroma.Config.put([:instance, :skip_thread_containment], false)
author = insert(:user)
user = insert(:user)
@@ -262,12 +195,10 @@ defmodule Pleroma.Web.StreamerTest do
)
)
- task = Task.async(fn -> refute_receive {:text, _}, 1_000 end)
- fake_socket = %StreamerSocket{transport_pid: task.pid, user: user}
- topics = %{"public" => [fake_socket]}
- Worker.push_to_socket(topics, "public", activity)
-
- Task.await(task)
+ Streamer.add_socket("public", user)
+ Streamer.stream("public", activity)
+ assert_receive {:render_with_user, _, _, ^activity}
+ assert Streamer.filtered_by_user?(user, activity)
end
test "it sends message if recipients invalid and thread containment is disabled" do
@@ -285,12 +216,11 @@ defmodule Pleroma.Web.StreamerTest do
)
)
- task = Task.async(fn -> assert_receive {:text, _}, 1_000 end)
- fake_socket = %StreamerSocket{transport_pid: task.pid, user: user}
- topics = %{"public" => [fake_socket]}
- Worker.push_to_socket(topics, "public", activity)
+ Streamer.add_socket("public", user)
+ Streamer.stream("public", activity)
- Task.await(task)
+ assert_receive {:render_with_user, _, _, ^activity}
+ refute Streamer.filtered_by_user?(user, activity)
end
test "it sends message if recipients invalid and thread containment is enabled but user's thread containment is disabled" do
@@ -308,255 +238,168 @@ defmodule Pleroma.Web.StreamerTest do
)
)
- task = Task.async(fn -> assert_receive {:text, _}, 1_000 end)
- fake_socket = %StreamerSocket{transport_pid: task.pid, user: user}
- topics = %{"public" => [fake_socket]}
- Worker.push_to_socket(topics, "public", activity)
+ Streamer.add_socket("public", user)
+ Streamer.stream("public", activity)
- Task.await(task)
+ assert_receive {:render_with_user, _, _, ^activity}
+ refute Streamer.filtered_by_user?(user, activity)
end
end
describe "blocks" do
- test "it doesn't send messages involving blocked users" do
+ test "it filters messages involving blocked users" do
user = insert(:user)
blocked_user = insert(:user)
{:ok, _user_relationship} = User.block(user, blocked_user)
+ Streamer.add_socket("public", user)
{:ok, activity} = CommonAPI.post(blocked_user, %{"status" => "Test"})
-
- task =
- Task.async(fn ->
- refute_receive {:text, _}, 1_000
- end)
-
- fake_socket = %StreamerSocket{
- transport_pid: task.pid,
- user: user
- }
-
- topics = %{
- "public" => [fake_socket]
- }
-
- Worker.push_to_socket(topics, "public", activity)
-
- Task.await(task)
+ assert_receive {:render_with_user, _, _, ^activity}
+ assert Streamer.filtered_by_user?(user, activity)
end
- test "it doesn't send messages transitively involving blocked users" do
+ test "it filters messages transitively involving blocked users" do
blocker = insert(:user)
blockee = insert(:user)
friend = insert(:user)
- task =
- Task.async(fn ->
- refute_receive {:text, _}, 1_000
- end)
-
- fake_socket = %StreamerSocket{
- transport_pid: task.pid,
- user: blocker
- }
-
- topics = %{
- "public" => [fake_socket]
- }
+ Streamer.add_socket("public", blocker)
{:ok, _user_relationship} = User.block(blocker, blockee)
{:ok, activity_one} = CommonAPI.post(friend, %{"status" => "hey! @#{blockee.nickname}"})
- Worker.push_to_socket(topics, "public", activity_one)
+ assert_receive {:render_with_user, _, _, ^activity_one}
+ assert Streamer.filtered_by_user?(blocker, activity_one)
{:ok, activity_two} = CommonAPI.post(blockee, %{"status" => "hey! @#{friend.nickname}"})
- Worker.push_to_socket(topics, "public", activity_two)
+ assert_receive {:render_with_user, _, _, ^activity_two}
+ assert Streamer.filtered_by_user?(blocker, activity_two)
{:ok, activity_three} = CommonAPI.post(blockee, %{"status" => "hey! @#{blocker.nickname}"})
- Worker.push_to_socket(topics, "public", activity_three)
-
- Task.await(task)
+ assert_receive {:render_with_user, _, _, ^activity_three}
+ assert Streamer.filtered_by_user?(blocker, activity_three)
end
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)
-
- {:ok, activity} =
- CommonAPI.post(user_b, %{
- "status" => "@#{user_c.nickname} Test",
- "visibility" => "direct"
- })
-
- task =
- Task.async(fn ->
- refute_receive {:text, _}, 1_000
- end)
-
- fake_socket = %StreamerSocket{
- transport_pid: task.pid,
- user: user_a
- }
-
- topics = %{
- "list:#{list.id}" => [fake_socket]
- }
-
- Worker.handle_call({:stream, "list", activity}, self(), topics)
-
- Task.await(task)
- end
-
- test "it doesn't send unwanted private posts to list" do
- user_a = insert(:user)
- user_b = insert(:user)
+ describe "lists" do
+ test "it doesn't send unwanted DMs to list" do
+ user_a = insert(:user)
+ user_b = insert(:user)
+ user_c = insert(:user)
- {:ok, list} = List.create("Test", user_a)
- {:ok, list} = List.follow(list, user_b)
+ {:ok, user_a} = User.follow(user_a, user_b)
- {:ok, activity} =
- CommonAPI.post(user_b, %{
- "status" => "Test",
- "visibility" => "private"
- })
+ {:ok, list} = List.create("Test", user_a)
+ {:ok, list} = List.follow(list, user_b)
- task =
- Task.async(fn ->
- refute_receive {:text, _}, 1_000
- end)
+ Streamer.add_socket("list:#{list.id}", user_a)
- fake_socket = %StreamerSocket{
- transport_pid: task.pid,
- user: user_a
- }
+ {:ok, _activity} =
+ CommonAPI.post(user_b, %{
+ "status" => "@#{user_c.nickname} Test",
+ "visibility" => "direct"
+ })
- topics = %{
- "list:#{list.id}" => [fake_socket]
- }
+ refute_receive _
+ end
- Worker.handle_call({:stream, "list", activity}, self(), topics)
+ test "it doesn't send unwanted private posts to list" do
+ user_a = insert(:user)
+ user_b = insert(:user)
- Task.await(task)
- end
+ {:ok, list} = List.create("Test", user_a)
+ {:ok, list} = List.follow(list, user_b)
- test "it sends wanted private posts to list" do
- user_a = insert(:user)
- user_b = insert(:user)
+ Streamer.add_socket("list:#{list.id}", user_a)
- {:ok, user_a} = User.follow(user_a, user_b)
+ {:ok, _activity} =
+ CommonAPI.post(user_b, %{
+ "status" => "Test",
+ "visibility" => "private"
+ })
- {:ok, list} = List.create("Test", user_a)
- {:ok, list} = List.follow(list, user_b)
+ refute_receive _
+ end
- {:ok, activity} =
- CommonAPI.post(user_b, %{
- "status" => "Test",
- "visibility" => "private"
- })
+ test "it sends wanted private posts to list" do
+ user_a = insert(:user)
+ user_b = insert(:user)
- task =
- Task.async(fn ->
- assert_receive {:text, _}, 1_000
- end)
+ {:ok, user_a} = User.follow(user_a, user_b)
- fake_socket = %StreamerSocket{
- transport_pid: task.pid,
- user: user_a
- }
+ {:ok, list} = List.create("Test", user_a)
+ {:ok, list} = List.follow(list, user_b)
- Streamer.add_socket(
- "list:#{list.id}",
- fake_socket
- )
+ Streamer.add_socket("list:#{list.id}", user_a)
- Worker.handle_call({:stream, "list", activity}, self(), %{})
+ {:ok, activity} =
+ CommonAPI.post(user_b, %{
+ "status" => "Test",
+ "visibility" => "private"
+ })
- Task.await(task)
+ assert_receive {:render_with_user, _, _, ^activity}
+ refute Streamer.filtered_by_user?(user_a, activity)
+ end
end
- test "it doesn't send muted reblogs" do
- user1 = insert(:user)
- user2 = insert(:user)
- user3 = insert(:user)
- CommonAPI.hide_reblogs(user1, user2)
-
- {:ok, create_activity} = CommonAPI.post(user3, %{"status" => "I'm kawen"})
- {:ok, announce_activity, _} = CommonAPI.repeat(create_activity.id, user2)
-
- task =
- Task.async(fn ->
- refute_receive {:text, _}, 1_000
- end)
-
- fake_socket = %StreamerSocket{
- transport_pid: task.pid,
- user: user1
- }
-
- topics = %{
- "public" => [fake_socket]
- }
-
- Worker.push_to_socket(topics, "public", announce_activity)
+ describe "muted reblogs" do
+ test "it filters muted reblogs" do
+ user1 = insert(:user)
+ user2 = insert(:user)
+ user3 = insert(:user)
+ CommonAPI.follow(user1, user2)
+ CommonAPI.hide_reblogs(user1, user2)
- Task.await(task)
- end
+ {:ok, create_activity} = CommonAPI.post(user3, %{"status" => "I'm kawen"})
- test "it does send non-reblog notification for reblog-muted actors" do
- user1 = insert(:user)
- user2 = insert(:user)
- user3 = insert(:user)
- CommonAPI.hide_reblogs(user1, user2)
+ Streamer.add_socket("user", user1)
+ {:ok, announce_activity, _} = CommonAPI.repeat(create_activity.id, user2)
+ assert_receive {:render_with_user, _, _, ^announce_activity}
+ assert Streamer.filtered_by_user?(user1, announce_activity)
+ end
- {:ok, create_activity} = CommonAPI.post(user3, %{"status" => "I'm kawen"})
- {:ok, favorite_activity} = CommonAPI.favorite(user2, create_activity.id)
+ test "it filters reblog notification for reblog-muted actors" do
+ user1 = insert(:user)
+ user2 = insert(:user)
+ CommonAPI.follow(user1, user2)
+ CommonAPI.hide_reblogs(user1, user2)
- task =
- Task.async(fn ->
- assert_receive {:text, _}, 1_000
- end)
+ {:ok, create_activity} = CommonAPI.post(user1, %{"status" => "I'm kawen"})
+ Streamer.add_socket("user", user1)
+ {:ok, _favorite_activity, _} = CommonAPI.repeat(create_activity.id, user2)
- fake_socket = %StreamerSocket{
- transport_pid: task.pid,
- user: user1
- }
+ assert_receive {:render_with_user, _, "notification.json", notif}
+ assert Streamer.filtered_by_user?(user1, notif)
+ end
- topics = %{
- "public" => [fake_socket]
- }
+ test "it send non-reblog notification for reblog-muted actors" do
+ user1 = insert(:user)
+ user2 = insert(:user)
+ CommonAPI.follow(user1, user2)
+ CommonAPI.hide_reblogs(user1, user2)
- Worker.push_to_socket(topics, "public", favorite_activity)
+ {:ok, create_activity} = CommonAPI.post(user1, %{"status" => "I'm kawen"})
+ Streamer.add_socket("user", user1)
+ {:ok, _favorite_activity} = CommonAPI.favorite(user2, create_activity.id)
- Task.await(task)
+ assert_receive {:render_with_user, _, "notification.json", notif}
+ refute Streamer.filtered_by_user?(user1, notif)
+ end
end
- test "it doesn't send posts from muted threads" do
+ test "it filters posts from muted threads" do
user = insert(:user)
user2 = insert(:user)
+ Streamer.add_socket("user", user2)
{:ok, user2, user, _activity} = CommonAPI.follow(user2, user)
-
{:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
-
- {:ok, activity} = CommonAPI.add_mute(user2, activity)
-
- task = Task.async(fn -> refute_receive {:text, _}, @streamer_timeout end)
-
- Streamer.add_socket(
- "user",
- %{transport_pid: task.pid, assigns: %{user: user2}}
- )
-
- Streamer.stream("user", activity)
- Task.await(task)
+ {:ok, _} = CommonAPI.add_mute(user2, activity)
+ assert_receive {:render_with_user, _, _, ^activity}
+ assert Streamer.filtered_by_user?(user2, activity)
end
describe "direct streams" do
@@ -568,22 +411,7 @@ defmodule Pleroma.Web.StreamerTest do
user = insert(:user)
another_user = insert(:user)
- task =
- Task.async(fn ->
- assert_receive {:text, received_event}, @streamer_timeout
-
- assert %{"event" => "conversation", "payload" => received_payload} =
- Jason.decode!(received_event)
-
- assert %{"last_status" => last_status} = Jason.decode!(received_payload)
- [participation] = Participation.for_user(user)
- assert last_status["pleroma"]["direct_conversation_id"] == participation.id
- end)
-
- Streamer.add_socket(
- "direct",
- %{transport_pid: task.pid, assigns: %{user: user}}
- )
+ Streamer.add_socket("direct", user)
{:ok, _create_activity} =
CommonAPI.post(another_user, %{
@@ -591,42 +419,47 @@ defmodule Pleroma.Web.StreamerTest do
"visibility" => "direct"
})
- Task.await(task)
+ assert_receive {:text, received_event}
+
+ assert %{"event" => "conversation", "payload" => received_payload} =
+ Jason.decode!(received_event)
+
+ assert %{"last_status" => last_status} = Jason.decode!(received_payload)
+ [participation] = Participation.for_user(user)
+ assert last_status["pleroma"]["direct_conversation_id"] == participation.id
end
test "it doesn't send conversation update to the 'direct' stream when the last message in the conversation is deleted" do
user = insert(:user)
another_user = insert(:user)
+ Streamer.add_socket("direct", user)
+
{:ok, create_activity} =
CommonAPI.post(another_user, %{
"status" => "hi @#{user.nickname}",
"visibility" => "direct"
})
- task =
- Task.async(fn ->
- assert_receive {:text, received_event}, @streamer_timeout
- assert %{"event" => "delete", "payload" => _} = Jason.decode!(received_event)
+ create_activity_id = create_activity.id
+ assert_receive {:render_with_user, _, _, ^create_activity}
+ assert_receive {:text, received_conversation1}
+ assert %{"event" => "conversation", "payload" => _} = Jason.decode!(received_conversation1)
- refute_receive {:text, _}, @streamer_timeout
- end)
+ {:ok, _} = CommonAPI.delete(create_activity_id, another_user)
- Process.sleep(@streamer_start_wait)
+ assert_receive {:text, received_event}
- Streamer.add_socket(
- "direct",
- %{transport_pid: task.pid, assigns: %{user: user}}
- )
+ assert %{"event" => "delete", "payload" => ^create_activity_id} =
+ Jason.decode!(received_event)
- {:ok, _} = CommonAPI.delete(create_activity.id, another_user)
-
- Task.await(task)
+ refute_receive _
end
test "it sends conversation update to the 'direct' stream when a message is deleted" do
user = insert(:user)
another_user = insert(:user)
+ Streamer.add_socket("direct", user)
{:ok, create_activity} =
CommonAPI.post(another_user, %{
@@ -636,35 +469,30 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, create_activity2} =
CommonAPI.post(another_user, %{
- "status" => "hi @#{user.nickname}",
+ "status" => "hi @#{user.nickname} 2",
"in_reply_to_status_id" => create_activity.id,
"visibility" => "direct"
})
- task =
- Task.async(fn ->
- assert_receive {:text, received_event}, @streamer_timeout
- assert %{"event" => "delete", "payload" => _} = Jason.decode!(received_event)
-
- assert_receive {:text, received_event}, @streamer_timeout
+ assert_receive {:render_with_user, _, _, ^create_activity}
+ assert_receive {:render_with_user, _, _, ^create_activity2}
+ assert_receive {:text, received_conversation1}
+ assert %{"event" => "conversation", "payload" => _} = Jason.decode!(received_conversation1)
+ assert_receive {:text, received_conversation1}
+ assert %{"event" => "conversation", "payload" => _} = Jason.decode!(received_conversation1)
- assert %{"event" => "conversation", "payload" => received_payload} =
- Jason.decode!(received_event)
-
- assert %{"last_status" => last_status} = Jason.decode!(received_payload)
- assert last_status["id"] == to_string(create_activity.id)
- end)
+ {:ok, _} = CommonAPI.delete(create_activity2.id, another_user)
- Process.sleep(@streamer_start_wait)
+ assert_receive {:text, received_event}
+ assert %{"event" => "delete", "payload" => _} = Jason.decode!(received_event)
- Streamer.add_socket(
- "direct",
- %{transport_pid: task.pid, assigns: %{user: user}}
- )
+ assert_receive {:text, received_event}
- {:ok, _} = CommonAPI.delete(create_activity2.id, another_user)
+ assert %{"event" => "conversation", "payload" => received_payload} =
+ Jason.decode!(received_event)
- Task.await(task)
+ assert %{"last_status" => last_status} = Jason.decode!(received_payload)
+ assert last_status["id"] == to_string(create_activity.id)
end
end
end
--
cgit v1.2.3
From dc4a448f4863e7d69c55d39273575fb3463c6c3c Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 7 May 2020 14:04:48 +0400
Subject: Add OpenAPI spec for SearchController
---
.../controllers/search_controller_test.exs | 78 +++++++++++-----------
1 file changed, 40 insertions(+), 38 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/search_controller_test.exs b/test/web/mastodon_api/controllers/search_controller_test.exs
index 11133ff66..02476acb6 100644
--- a/test/web/mastodon_api/controllers/search_controller_test.exs
+++ b/test/web/mastodon_api/controllers/search_controller_test.exs
@@ -27,8 +27,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
capture_log(fn ->
results =
conn
- |> get("/api/v2/search", %{"q" => "2hu"})
- |> json_response(200)
+ |> get("/api/v2/search?q=2hu")
+ |> json_response_and_validate_schema(200)
assert results["accounts"] == []
assert results["statuses"] == []
@@ -54,8 +54,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
results =
conn
- |> get("/api/v2/search", %{"q" => "2hu #private"})
- |> json_response(200)
+ |> get("/api/v2/search?#{URI.encode_query(%{q: "2hu #private"})}")
+ |> json_response_and_validate_schema(200)
[account | _] = results["accounts"]
assert account["id"] == to_string(user_three.id)
@@ -68,8 +68,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
assert status["id"] == to_string(activity.id)
results =
- get(conn, "/api/v2/search", %{"q" => "天子"})
- |> json_response(200)
+ get(conn, "/api/v2/search?q=天子")
+ |> json_response_and_validate_schema(200)
[status] = results["statuses"]
assert status["id"] == to_string(activity.id)
@@ -89,8 +89,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
conn
|> assign(:user, user)
|> assign(:token, insert(:oauth_token, user: user, scopes: ["read"]))
- |> get("/api/v2/search", %{"q" => "Agent"})
- |> json_response(200)
+ |> get("/api/v2/search?q=Agent")
+ |> json_response_and_validate_schema(200)
status_ids = Enum.map(results["statuses"], fn g -> g["id"] end)
@@ -107,8 +107,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
results =
conn
- |> get("/api/v1/accounts/search", %{"q" => "shp"})
- |> json_response(200)
+ |> get("/api/v1/accounts/search?q=shp")
+ |> json_response_and_validate_schema(200)
result_ids = for result <- results, do: result["acct"]
@@ -117,8 +117,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
results =
conn
- |> get("/api/v1/accounts/search", %{"q" => "2hu"})
- |> json_response(200)
+ |> get("/api/v1/accounts/search?q=2hu")
+ |> json_response_and_validate_schema(200)
result_ids = for result <- results, do: result["acct"]
@@ -130,8 +130,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
results =
conn
- |> get("/api/v1/accounts/search", %{"q" => "shp@shitposter.club xxx "})
- |> json_response(200)
+ |> get("/api/v1/accounts/search?q=shp@shitposter.club xxx")
+ |> json_response_and_validate_schema(200)
assert length(results) == 1
end
@@ -146,8 +146,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
capture_log(fn ->
results =
conn
- |> get("/api/v1/search", %{"q" => "2hu"})
- |> json_response(200)
+ |> get("/api/v1/search?q=2hu")
+ |> json_response_and_validate_schema(200)
assert results["accounts"] == []
assert results["statuses"] == []
@@ -173,8 +173,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
results =
conn
- |> get("/api/v1/search", %{"q" => "2hu"})
- |> json_response(200)
+ |> get("/api/v1/search?q=2hu")
+ |> json_response_and_validate_schema(200)
[account | _] = results["accounts"]
assert account["id"] == to_string(user_three.id)
@@ -194,8 +194,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
results =
conn
- |> get("/api/v1/search", %{"q" => "https://shitposter.club/notice/2827873"})
- |> json_response(200)
+ |> get("/api/v1/search?q=https://shitposter.club/notice/2827873")
+ |> json_response_and_validate_schema(200)
[status, %{"id" => ^activity_id}] = results["statuses"]
@@ -212,10 +212,12 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
})
capture_log(fn ->
+ q = Object.normalize(activity).data["id"]
+
results =
conn
- |> get("/api/v1/search", %{"q" => Object.normalize(activity).data["id"]})
- |> json_response(200)
+ |> get("/api/v1/search?q=#{q}")
+ |> json_response_and_validate_schema(200)
[] = results["statuses"]
end)
@@ -228,8 +230,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
conn
|> assign(:user, user)
|> assign(:token, insert(:oauth_token, user: user, scopes: ["read"]))
- |> get("/api/v1/search", %{"q" => "mike@osada.macgirvin.com", "resolve" => "true"})
- |> json_response(200)
+ |> get("/api/v1/search?q=mike@osada.macgirvin.com&resolve=true")
+ |> json_response_and_validate_schema(200)
[account] = results["accounts"]
assert account["acct"] == "mike@osada.macgirvin.com"
@@ -238,8 +240,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
test "search doesn't fetch remote accounts if resolve is false", %{conn: conn} do
results =
conn
- |> get("/api/v1/search", %{"q" => "mike@osada.macgirvin.com", "resolve" => "false"})
- |> json_response(200)
+ |> get("/api/v1/search?q=mike@osada.macgirvin.com&resolve=false")
+ |> json_response_and_validate_schema(200)
assert [] == results["accounts"]
end
@@ -254,16 +256,16 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
result =
conn
- |> get("/api/v1/search", %{"q" => "2hu", "limit" => 1})
+ |> get("/api/v1/search?q=2hu&limit=1")
- assert results = json_response(result, 200)
+ assert results = json_response_and_validate_schema(result, 200)
assert [%{"id" => activity_id1}] = results["statuses"]
assert [_] = results["accounts"]
results =
conn
- |> get("/api/v1/search", %{"q" => "2hu", "limit" => 1, "offset" => 1})
- |> json_response(200)
+ |> get("/api/v1/search?q=2hu&limit=1&offset=1")
+ |> json_response_and_validate_schema(200)
assert [%{"id" => activity_id2}] = results["statuses"]
assert [] = results["accounts"]
@@ -279,13 +281,13 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
assert %{"statuses" => [_activity], "accounts" => [], "hashtags" => []} =
conn
- |> get("/api/v1/search", %{"q" => "2hu", "type" => "statuses"})
- |> json_response(200)
+ |> get("/api/v1/search?q=2hu&type=statuses")
+ |> json_response_and_validate_schema(200)
assert %{"statuses" => [], "accounts" => [_user_two], "hashtags" => []} =
conn
- |> get("/api/v1/search", %{"q" => "2hu", "type" => "accounts"})
- |> json_response(200)
+ |> get("/api/v1/search?q=2hu&type=accounts")
+ |> json_response_and_validate_schema(200)
end
test "search uses account_id to filter statuses by the author", %{conn: conn} do
@@ -297,8 +299,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
results =
conn
- |> get("/api/v1/search", %{"q" => "2hu", "account_id" => user.id})
- |> json_response(200)
+ |> get("/api/v1/search?q=2hu&account_id=#{user.id}")
+ |> json_response_and_validate_schema(200)
assert [%{"id" => activity_id1}] = results["statuses"]
assert activity_id1 == activity1.id
@@ -306,8 +308,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
results =
conn
- |> get("/api/v1/search", %{"q" => "2hu", "account_id" => user_two.id})
- |> json_response(200)
+ |> get("/api/v1/search?q=2hu&account_id=#{user_two.id}")
+ |> json_response_and_validate_schema(200)
assert [%{"id" => activity_id2}] = results["statuses"]
assert activity_id2 == activity2.id
--
cgit v1.2.3
From f57fa2a00df2d93eba53c1ff3ab5c7d5fabb8308 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 7 May 2020 12:43:30 +0200
Subject: Notifications: Simplify recipient calculation for some Activities.
Fixes the 'getting notfications for other people's posts' bug.
---
test/notification_test.exs | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 5c85f3368..509ca0b0b 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -12,6 +12,8 @@ defmodule Pleroma.NotificationTest do
alias Pleroma.Notification
alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
+ alias Pleroma.Web.ActivityPub.ActivityPub
+ alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.Transmogrifier
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.MastodonAPI.NotificationView
@@ -601,6 +603,28 @@ defmodule Pleroma.NotificationTest do
assert other_user not in enabled_receivers
end
+ test "it only notifies the post's author in likes" do
+ user = insert(:user)
+ other_user = insert(:user)
+ third_user = insert(:user)
+
+ {:ok, activity_one} =
+ CommonAPI.post(user, %{
+ "status" => "hey @#{other_user.nickname}!"
+ })
+
+ {:ok, like_data, _} = Builder.like(third_user, activity_one.object)
+
+ {:ok, like, _} =
+ like_data
+ |> Map.put("to", [other_user.ap_id | like_data["to"]])
+ |> ActivityPub.persist(local: true)
+
+ {enabled_receivers, _disabled_receivers} = Notification.get_notified_from_activity(like)
+
+ assert other_user not in enabled_receivers
+ end
+
test "it does not send notification to mentioned users in announces" do
user = insert(:user)
other_user = insert(:user)
--
cgit v1.2.3
From 788b7e7bbd2732e2af72adad1a660cf363486c6b Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 7 May 2020 14:52:37 +0200
Subject: Merge fixes.
---
test/web/activity_pub/object_validator_test.exs | 1 -
test/web/activity_pub/transmogrifier_test.exs | 107 ------------------------
2 files changed, 108 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 4d90a0cf3..174be5ec6 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -107,7 +107,6 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
{:error, cng} = ObjectValidator.validate(missing_object, [])
assert {:object, {"can't find object", []}} in cng.errors
- assert length(cng.errors) == 1
end
test "it's invalid if the actor of the object and the actor of delete are from different domains",
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index ae5d3bf92..4fd6c8b00 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -685,113 +685,6 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert user.locked == true
end
- test "it works for incoming deletes" do
- activity = insert(:note_activity)
- deleting_user = insert(:user)
-
- data =
- File.read!("test/fixtures/mastodon-delete.json")
- |> Poison.decode!()
-
- object =
- data["object"]
- |> Map.put("id", activity.data["object"])
-
- data =
- data
- |> Map.put("object", object)
- |> Map.put("actor", deleting_user.ap_id)
-
- {:ok, %Activity{actor: actor, local: false, data: %{"id" => id}}} =
- Transmogrifier.handle_incoming(data)
-
- assert id == data["id"]
- refute Activity.get_by_id(activity.id)
- assert actor == deleting_user.ap_id
- end
-
- test "it fails for incoming deletes with spoofed origin" do
- activity = insert(:note_activity)
-
- data =
- File.read!("test/fixtures/mastodon-delete.json")
- |> Poison.decode!()
-
- object =
- data["object"]
- |> Map.put("id", activity.data["object"])
-
- data =
- data
- |> Map.put("object", object)
-
- assert capture_log(fn ->
- :error = Transmogrifier.handle_incoming(data)
- end) =~
- "[error] Could not decode user at fetch http://mastodon.example.org/users/gargron, {:error, :nxdomain}"
-
- assert Activity.get_by_id(activity.id)
- end
-
- @tag capture_log: true
- test "it works for incoming user deletes" do
- %{ap_id: ap_id} =
- insert(:user, ap_id: "http://mastodon.example.org/users/admin", local: false)
-
- data =
- File.read!("test/fixtures/mastodon-delete-user.json")
- |> Poison.decode!()
-
- {:ok, _} = Transmogrifier.handle_incoming(data)
- ObanHelpers.perform_all()
-
- refute User.get_cached_by_ap_id(ap_id)
- end
-
- test "it fails for incoming user deletes with spoofed origin" do
- %{ap_id: ap_id} = insert(:user)
-
- data =
- File.read!("test/fixtures/mastodon-delete-user.json")
- |> Poison.decode!()
- |> Map.put("actor", ap_id)
-
- assert capture_log(fn ->
- assert :error == Transmogrifier.handle_incoming(data)
- end) =~ "Object containment failed"
-
- assert User.get_cached_by_ap_id(ap_id)
- end
-
- test "it works for incoming unannounces with an existing notice" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
-
- announce_data =
- File.read!("test/fixtures/mastodon-announce.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- {:ok, %Activity{data: announce_data, local: false}} =
- Transmogrifier.handle_incoming(announce_data)
-
- data =
- File.read!("test/fixtures/mastodon-undo-announce.json")
- |> Poison.decode!()
- |> Map.put("object", announce_data)
- |> Map.put("actor", announce_data["actor"])
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["type"] == "Undo"
- assert object_data = data["object"]
- assert object_data["type"] == "Announce"
- assert object_data["object"] == activity.data["object"]
-
- assert object_data["id"] ==
- "http://mastodon.example.org/users/admin/statuses/99542391527669785/activity"
- end
-
test "it works for incomming unfollows with an existing follow" do
user = insert(:user)
--
cgit v1.2.3
From ea01e647df4466975b9382f123f0a2aa35ebfe76 Mon Sep 17 00:00:00 2001
From: Mark Felder
Date: Thu, 7 May 2020 09:13:43 -0500
Subject: Test Direct, Public, and Favorite notifications with privacy option
---
test/web/push/impl_test.exs | 60 +++++++++++++++++++++++++++++++++++++++++++--
1 file changed, 58 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/push/impl_test.exs b/test/web/push/impl_test.exs
index 3de911810..b855d72ba 100644
--- a/test/web/push/impl_test.exs
+++ b/test/web/push/impl_test.exs
@@ -193,7 +193,7 @@ defmodule Pleroma.Web.Push.ImplTest do
end
describe "build_content/3" do
- test "returns info content for direct message with enabled privacy option" do
+ test "hides details for notifications when privacy option enabled" do
user = insert(:user, nickname: "Bob")
user2 = insert(:user, nickname: "Rob", notification_settings: %{privacy_option: true})
@@ -211,9 +211,35 @@ defmodule Pleroma.Web.Push.ImplTest do
assert Impl.build_content(notif, actor, object) == %{
body: "New Direct Message"
}
+
+ {:ok, activity} =
+ CommonAPI.post(user, %{
+ "visibility" => "public",
+ "status" => " "public",
+ "status" =>
+ "Lorem ipsum dolor sit amet, consectetur :firefox: adipiscing elit. Fusce sagittis finibus turpis."
+ })
+
+ notif = insert(:notification, user: user2, activity: activity)
+
+ actor = User.get_cached_by_ap_id(notif.activity.data["actor"])
+ object = Object.normalize(activity)
+
+ assert Impl.build_content(notif, actor, object) == %{
+ body:
+ "@Bob: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sagittis fini...",
+ title: "New Mention"
+ }
+
+ {:ok, activity} = CommonAPI.favorite(user, activity.id)
+
+ notif = insert(:notification, user: user2, activity: activity)
+
+ actor = User.get_cached_by_ap_id(notif.activity.data["actor"])
+ object = Object.normalize(activity)
+
+ assert Impl.build_content(notif, actor, object) == %{
+ body: "@Bob has favorited your post",
+ title: "New Favorite"
+ }
end
end
end
--
cgit v1.2.3
From 4d71c4b8051d5cf54f37903091aed7f4d5c1ddd9 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Fri, 8 May 2020 12:33:01 +0300
Subject: fixed 'source' object in verify_credentials
---
test/web/mastodon_api/views/account_view_test.exs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index 5fb162141..375f0103a 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -31,7 +31,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
nickname: "shp@shitposter.club",
name: ":karjalanpiirakka: shp",
bio:
- "valid html. a
b
c
d
f",
+ "valid html. a
b
c
d
f '&<>\"",
inserted_at: ~N[2017-08-15 15:47:06.597036],
emoji: %{"karjalanpiirakka" => "/file.png"}
})
@@ -46,7 +46,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
followers_count: 3,
following_count: 0,
statuses_count: 5,
- note: "valid html. a
b
c
d
f",
+ note: "valid html. a
b
c
d
f '&<>"",
url: user.ap_id,
avatar: "http://localhost:4001/images/avi.png",
avatar_static: "http://localhost:4001/images/avi.png",
@@ -63,7 +63,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
fields: [],
bot: false,
source: %{
- note: "valid html. a\nb\nc\nd\nf",
+ note: "valid html. a\nb\nc\nd\nf '&<>\"",
sensitive: false,
pleroma: %{
actor_type: "Person",
--
cgit v1.2.3
From f1274c3326207ecba5086ee28f721b43a29eb14c Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 8 May 2020 11:41:13 +0200
Subject: Transmogrifier tests: Remove double tests.
---
test/web/activity_pub/transmogrifier_test.exs | 81 ---------------------------
1 file changed, 81 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 14c0f57ae..d783f57d2 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -325,87 +325,6 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert object_data["cc"] == to
end
- test "it works for incoming emoji reaction undos" do
- user = insert(:user)
-
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
- {:ok, reaction_activity} = CommonAPI.react_with_emoji(activity.id, user, "👌")
-
- data =
- File.read!("test/fixtures/mastodon-undo-like.json")
- |> Poison.decode!()
- |> Map.put("object", reaction_activity.data["id"])
- |> Map.put("actor", user.ap_id)
-
- {:ok, activity} = Transmogrifier.handle_incoming(data)
-
- assert activity.actor == user.ap_id
- assert activity.data["id"] == data["id"]
- assert activity.data["type"] == "Undo"
- end
-
- test "it returns an error for incoming unlikes wihout a like activity" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
-
- data =
- File.read!("test/fixtures/mastodon-undo-like.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- assert Transmogrifier.handle_incoming(data) == :error
- end
-
- test "it works for incoming unlikes with an existing like activity" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
-
- like_data =
- File.read!("test/fixtures/mastodon-like.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- {:ok, %Activity{data: like_data, local: false}} = Transmogrifier.handle_incoming(like_data)
-
- data =
- File.read!("test/fixtures/mastodon-undo-like.json")
- |> Poison.decode!()
- |> Map.put("object", like_data)
- |> Map.put("actor", like_data["actor"])
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == "http://mastodon.example.org/users/admin"
- assert data["type"] == "Undo"
- assert data["id"] == "http://mastodon.example.org/users/admin#likes/2/undo"
- assert data["object"] == "http://mastodon.example.org/users/admin#likes/2"
- end
-
- test "it works for incoming unlikes with an existing like activity and a compact object" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
-
- like_data =
- File.read!("test/fixtures/mastodon-like.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- {:ok, %Activity{data: like_data, local: false}} = Transmogrifier.handle_incoming(like_data)
-
- data =
- File.read!("test/fixtures/mastodon-undo-like.json")
- |> Poison.decode!()
- |> Map.put("object", like_data["id"])
- |> Map.put("actor", like_data["actor"])
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == "http://mastodon.example.org/users/admin"
- assert data["type"] == "Undo"
- assert data["id"] == "http://mastodon.example.org/users/admin#likes/2/undo"
- assert data["object"] == "http://mastodon.example.org/users/admin#likes/2"
- end
-
test "it works for incoming emoji reactions" do
user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
--
cgit v1.2.3
From 7e9aaa0d0221311d831161d977c8b0e2a55b3439 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 8 May 2020 11:43:07 +0200
Subject: Transmogrifier tests: Remove more double tests.
---
test/web/activity_pub/transmogrifier_test.exs | 37 ---------------------------
1 file changed, 37 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index d783f57d2..2914c90ea 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -325,43 +325,6 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert object_data["cc"] == to
end
- test "it works for incoming emoji reactions" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
-
- data =
- File.read!("test/fixtures/emoji-reaction.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == "http://mastodon.example.org/users/admin"
- assert data["type"] == "EmojiReact"
- assert data["id"] == "http://mastodon.example.org/users/admin#reactions/2"
- assert data["object"] == activity.data["object"]
- assert data["content"] == "👌"
- end
-
- test "it reject invalid emoji reactions" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
-
- data =
- File.read!("test/fixtures/emoji-reaction-too-long.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- assert {:error, _} = Transmogrifier.handle_incoming(data)
-
- data =
- File.read!("test/fixtures/emoji-reaction-no-emoji.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- assert {:error, _} = Transmogrifier.handle_incoming(data)
- end
-
test "it works for incoming announces" do
data = File.read!("test/fixtures/mastodon-announce.json") |> Poison.decode!()
--
cgit v1.2.3
From 287f781808c88f43f5689508b5aa21f6639b9d16 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Fri, 8 May 2020 16:54:53 +0300
Subject: user deletion
---
test/user_test.exs | 27 +++++++++++++++++++++++++++
test/web/activity_pub/side_effects_test.exs | 25 +++++++++++++++++++++++++
2 files changed, 52 insertions(+)
(limited to 'test')
diff --git a/test/user_test.exs b/test/user_test.exs
index a3c75aa9b..96116fca6 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -1171,6 +1171,33 @@ defmodule Pleroma.UserTest do
end
end
+ describe "delete/1 when confirmation is pending" do
+ setup do
+ user = insert(:user, confirmation_pending: true)
+ {:ok, user: user}
+ end
+
+ test "deletes user from database when activation required", %{user: user} do
+ clear_config([:instance, :account_activation_required], true)
+
+ {:ok, job} = User.delete(user)
+ {:ok, _} = ObanHelpers.perform(job)
+
+ refute User.get_cached_by_id(user.id)
+ refute User.get_by_id(user.id)
+ end
+
+ test "deactivates user when activation is not required", %{user: user} do
+ clear_config([:instance, :account_activation_required], false)
+
+ {:ok, job} = User.delete(user)
+ {:ok, _} = ObanHelpers.perform(job)
+
+ assert %{deactivated: true} = User.get_cached_by_id(user.id)
+ assert %{deactivated: true} = User.get_by_id(user.id)
+ end
+ end
+
test "get_public_key_for_ap_id fetches a user that's not in the db" do
assert {:ok, _key} = User.get_public_key_for_ap_id("http://mastodon.example.org/users/admin")
end
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index b29a7a7be..5c06dc864 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -99,6 +99,31 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
end
end
+ describe "delete users with confirmation pending" do
+ setup do
+ user = insert(:user, confirmation_pending: true)
+ {:ok, delete_user_data, _meta} = Builder.delete(user, user.ap_id)
+ {:ok, delete_user, _meta} = ActivityPub.persist(delete_user_data, local: true)
+ {:ok, delete: delete_user, user: user}
+ end
+
+ test "when activation is not required", %{delete: delete, user: user} do
+ clear_config([:instance, :account_activation_required], false)
+ {:ok, _, _} = SideEffects.handle(delete)
+ ObanHelpers.perform_all()
+
+ assert User.get_cached_by_id(user.id).deactivated
+ end
+
+ test "when activation is required", %{delete: delete, user: user} do
+ clear_config([:instance, :account_activation_required], true)
+ {:ok, _, _} = SideEffects.handle(delete)
+ ObanHelpers.perform_all()
+
+ refute User.get_cached_by_id(user.id)
+ end
+ end
+
describe "Undo objects" do
setup do
poster = insert(:user)
--
cgit v1.2.3
From 14a49a04837b0dc5a0d72dd7c5b4dfa482801e7c Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Sat, 9 May 2020 18:05:44 +0300
Subject: [#2456] Dropped support for embedded `pleroma/account/relationship`
in statuses and notifications.
---
.../controllers/timeline_controller_test.exs | 80 +---------------------
1 file changed, 1 insertion(+), 79 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/timeline_controller_test.exs b/test/web/mastodon_api/controllers/timeline_controller_test.exs
index b8bb83af7..47541979d 100644
--- a/test/web/mastodon_api/controllers/timeline_controller_test.exs
+++ b/test/web/mastodon_api/controllers/timeline_controller_test.exs
@@ -20,7 +20,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
describe "home" do
setup do: oauth_access(["read:statuses"])
- test "does NOT render account/pleroma/relationship by default", %{
+ test "does NOT embed account/pleroma/relationship in statuses", %{
user: user,
conn: conn
} do
@@ -39,84 +39,6 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
end)
end
- test "embeds account relationships with `with_relationships=true`", %{user: user, conn: conn} do
- uri = "/api/v1/timelines/home?with_relationships=true"
-
- following = insert(:user, nickname: "followed")
- third_user = insert(:user, nickname: "repeated")
-
- {:ok, _activity} = CommonAPI.post(following, %{"status" => "post"})
- {:ok, activity} = CommonAPI.post(third_user, %{"status" => "repeated post"})
- {:ok, _, _} = CommonAPI.repeat(activity.id, following)
-
- ret_conn = get(conn, uri)
-
- assert Enum.empty?(json_response(ret_conn, :ok))
-
- {:ok, _user} = User.follow(user, following)
-
- ret_conn = get(conn, uri)
-
- assert [
- %{
- "reblog" => %{
- "content" => "repeated post",
- "account" => %{
- "pleroma" => %{
- "relationship" => %{"following" => false, "followed_by" => false}
- }
- }
- },
- "account" => %{
- "pleroma" => %{
- "relationship" => %{"following" => true}
- }
- }
- },
- %{
- "content" => "post",
- "account" => %{
- "acct" => "followed",
- "pleroma" => %{
- "relationship" => %{"following" => true}
- }
- }
- }
- ] = json_response(ret_conn, :ok)
-
- {:ok, _user} = User.follow(third_user, user)
-
- ret_conn = get(conn, uri)
-
- assert [
- %{
- "reblog" => %{
- "content" => "repeated post",
- "account" => %{
- "acct" => "repeated",
- "pleroma" => %{
- "relationship" => %{"following" => false, "followed_by" => true}
- }
- }
- },
- "account" => %{
- "pleroma" => %{
- "relationship" => %{"following" => true}
- }
- }
- },
- %{
- "content" => "post",
- "account" => %{
- "acct" => "followed",
- "pleroma" => %{
- "relationship" => %{"following" => true}
- }
- }
- }
- ] = json_response(ret_conn, :ok)
- end
-
test "the home timeline when the direct messages are excluded", %{user: user, conn: conn} do
{:ok, public_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "public"})
{:ok, direct_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
--
cgit v1.2.3
From aee88d11be898921d79ad7f1481ab055190f4dfd Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Sun, 10 May 2020 09:16:48 +0300
Subject: [#2456] Removed support for embedded relationships in account view.
---
test/web/mastodon_api/views/account_view_test.exs | 76 ----------------------
.../mastodon_api/views/notification_view_test.exs | 21 ++----
2 files changed, 7 insertions(+), 90 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index 5fb162141..3c1aeb6d5 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -295,82 +295,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
end
end
- test "represent an embedded relationship" do
- user =
- insert(:user, %{
- follower_count: 0,
- note_count: 5,
- actor_type: "Service",
- nickname: "shp@shitposter.club",
- inserted_at: ~N[2017-08-15 15:47:06.597036]
- })
-
- other_user = insert(:user)
- {:ok, other_user} = User.follow(other_user, user)
- {:ok, _user_relationship} = User.block(other_user, user)
- {:ok, _} = User.follow(insert(:user), user)
-
- expected = %{
- id: to_string(user.id),
- username: "shp",
- acct: user.nickname,
- display_name: user.name,
- locked: false,
- created_at: "2017-08-15T15:47:06.000Z",
- followers_count: 1,
- following_count: 0,
- statuses_count: 5,
- note: user.bio,
- url: user.ap_id,
- avatar: "http://localhost:4001/images/avi.png",
- avatar_static: "http://localhost:4001/images/avi.png",
- header: "http://localhost:4001/images/banner.png",
- header_static: "http://localhost:4001/images/banner.png",
- emojis: [],
- fields: [],
- bot: true,
- source: %{
- note: user.bio,
- sensitive: false,
- pleroma: %{
- actor_type: "Service",
- discoverable: false
- },
- fields: []
- },
- pleroma: %{
- background_image: nil,
- confirmation_pending: false,
- tags: [],
- is_admin: false,
- is_moderator: false,
- hide_favorites: true,
- hide_followers: false,
- hide_follows: false,
- hide_followers_count: false,
- hide_follows_count: false,
- relationship: %{
- id: to_string(user.id),
- following: false,
- followed_by: false,
- blocking: true,
- blocked_by: false,
- subscribing: false,
- muting: false,
- muting_notifications: false,
- requested: false,
- domain_blocking: false,
- showing_reblogs: true,
- endorsed: false
- },
- skip_thread_containment: false
- }
- }
-
- assert expected ==
- AccountView.render("show.json", %{user: refresh_record(user), for: other_user})
- end
-
test "returns the settings store if the requesting user is the represented user and it's requested specifically" do
user = insert(:user, pleroma_settings_store: %{fe: "test"})
diff --git a/test/web/mastodon_api/views/notification_view_test.exs b/test/web/mastodon_api/views/notification_view_test.exs
index 61e6e3ae5..7cdba2fe0 100644
--- a/test/web/mastodon_api/views/notification_view_test.exs
+++ b/test/web/mastodon_api/views/notification_view_test.exs
@@ -45,8 +45,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
account:
AccountView.render("show.json", %{
user: user,
- for: mentioned_user,
- skip_relationships: true
+ for: mentioned_user
}),
status: StatusView.render("show.json", %{activity: activity, for: mentioned_user}),
created_at: Utils.to_masto_date(notification.inserted_at)
@@ -67,8 +66,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
id: to_string(notification.id),
pleroma: %{is_seen: false},
type: "favourite",
- account:
- AccountView.render("show.json", %{user: another_user, for: user, skip_relationships: true}),
+ account: AccountView.render("show.json", %{user: another_user, for: user}),
status: StatusView.render("show.json", %{activity: create_activity, for: user}),
created_at: Utils.to_masto_date(notification.inserted_at)
}
@@ -88,8 +86,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
id: to_string(notification.id),
pleroma: %{is_seen: false},
type: "reblog",
- account:
- AccountView.render("show.json", %{user: another_user, for: user, skip_relationships: true}),
+ account: AccountView.render("show.json", %{user: another_user, for: user}),
status: StatusView.render("show.json", %{activity: reblog_activity, for: user}),
created_at: Utils.to_masto_date(notification.inserted_at)
}
@@ -107,8 +104,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
id: to_string(notification.id),
pleroma: %{is_seen: false},
type: "follow",
- account:
- AccountView.render("show.json", %{user: follower, for: followed, skip_relationships: true}),
+ account: AccountView.render("show.json", %{user: follower, for: followed}),
created_at: Utils.to_masto_date(notification.inserted_at)
}
@@ -151,10 +147,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
id: to_string(notification.id),
pleroma: %{is_seen: false},
type: "move",
- account:
- AccountView.render("show.json", %{user: old_user, for: follower, skip_relationships: true}),
- target:
- AccountView.render("show.json", %{user: new_user, for: follower, skip_relationships: true}),
+ account: AccountView.render("show.json", %{user: old_user, for: follower}),
+ target: AccountView.render("show.json", %{user: new_user, for: follower}),
created_at: Utils.to_masto_date(notification.inserted_at)
}
@@ -179,8 +173,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
pleroma: %{is_seen: false},
type: "pleroma:emoji_reaction",
emoji: "☕",
- account:
- AccountView.render("show.json", %{user: other_user, for: user, skip_relationships: true}),
+ account: AccountView.render("show.json", %{user: other_user, for: user}),
status: StatusView.render("show.json", %{activity: activity, for: user}),
created_at: Utils.to_masto_date(notification.inserted_at)
}
--
cgit v1.2.3
From 3bde0fa3f668d42c03ce83174325920551960de3 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 11 May 2020 15:24:59 +0400
Subject: Add OpenAPI spec for TimelineController
---
.../controllers/timeline_controller_test.exs | 114 ++++++++++-----------
1 file changed, 57 insertions(+), 57 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/timeline_controller_test.exs b/test/web/mastodon_api/controllers/timeline_controller_test.exs
index 06efdc901..5e0d92f28 100644
--- a/test/web/mastodon_api/controllers/timeline_controller_test.exs
+++ b/test/web/mastodon_api/controllers/timeline_controller_test.exs
@@ -34,7 +34,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
conn
|> assign(:user, user)
|> get("/api/v1/timelines/home")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert Enum.all?(response, fn n ->
get_in(n, ["account", "pleroma", "relationship"]) == %{}
@@ -42,7 +42,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
end
test "the home timeline", %{user: user, conn: conn} do
- uri = "/api/v1/timelines/home?with_relationships=true"
+ uri = "/api/v1/timelines/home?with_relationships=1"
following = insert(:user, nickname: "followed")
third_user = insert(:user, nickname: "repeated")
@@ -53,7 +53,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
ret_conn = get(conn, uri)
- assert Enum.empty?(json_response(ret_conn, :ok))
+ assert Enum.empty?(json_response_and_validate_schema(ret_conn, :ok))
{:ok, _user} = User.follow(user, following)
@@ -78,7 +78,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
"pleroma" => %{"relationship" => %{"following" => true}}
}
}
- ] = json_response(ret_conn, :ok)
+ ] = json_response_and_validate_schema(ret_conn, :ok)
{:ok, _user} = User.follow(third_user, user)
@@ -104,7 +104,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
"pleroma" => %{"relationship" => %{"following" => true}}
}
}
- ] = json_response(ret_conn, :ok)
+ ] = json_response_and_validate_schema(ret_conn, :ok)
end
test "the home timeline when the direct messages are excluded", %{user: user, conn: conn} do
@@ -117,9 +117,9 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
{:ok, private_activity} =
CommonAPI.post(user, %{"status" => ".", "visibility" => "private"})
- conn = get(conn, "/api/v1/timelines/home", %{"exclude_visibilities" => ["direct"]})
+ conn = get(conn, "/api/v1/timelines/home?exclude_visibilities[]=direct")
- assert status_ids = json_response(conn, :ok) |> Enum.map(& &1["id"])
+ assert status_ids = json_response_and_validate_schema(conn, :ok) |> Enum.map(& &1["id"])
assert public_activity.id in status_ids
assert unlisted_activity.id in status_ids
assert private_activity.id in status_ids
@@ -136,17 +136,17 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
_activity = insert(:note_activity, local: false)
- conn = get(conn, "/api/v1/timelines/public", %{"local" => "False"})
+ conn = get(conn, "/api/v1/timelines/public?local=False")
- assert length(json_response(conn, :ok)) == 2
+ assert length(json_response_and_validate_schema(conn, :ok)) == 2
- conn = get(build_conn(), "/api/v1/timelines/public", %{"local" => "True"})
+ conn = get(build_conn(), "/api/v1/timelines/public?local=True")
- assert [%{"content" => "test"}] = json_response(conn, :ok)
+ assert [%{"content" => "test"}] = json_response_and_validate_schema(conn, :ok)
- conn = get(build_conn(), "/api/v1/timelines/public", %{"local" => "1"})
+ conn = get(build_conn(), "/api/v1/timelines/public?local=1")
- assert [%{"content" => "test"}] = json_response(conn, :ok)
+ assert [%{"content" => "test"}] = json_response_and_validate_schema(conn, :ok)
end
test "the public timeline includes only public statuses for an authenticated user" do
@@ -158,7 +158,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
{:ok, _activity} = CommonAPI.post(user, %{"status" => "test", "visibility" => "direct"})
res_conn = get(conn, "/api/v1/timelines/public")
- assert length(json_response(res_conn, 200)) == 1
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
end
end
@@ -176,15 +176,15 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
setup do: clear_config([:restrict_unauthenticated, :timelines, :federated], true)
test "if user is unauthenticated", %{conn: conn} do
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"})
+ res_conn = get(conn, "/api/v1/timelines/public?local=true")
- assert json_response(res_conn, :unauthorized) == %{
+ assert json_response_and_validate_schema(res_conn, :unauthorized) == %{
"error" => "authorization required for timeline view"
}
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"})
+ res_conn = get(conn, "/api/v1/timelines/public?local=false")
- assert json_response(res_conn, :unauthorized) == %{
+ assert json_response_and_validate_schema(res_conn, :unauthorized) == %{
"error" => "authorization required for timeline view"
}
end
@@ -192,11 +192,11 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
test "if user is authenticated" do
%{conn: conn} = oauth_access(["read:statuses"])
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"})
- assert length(json_response(res_conn, 200)) == 1
+ res_conn = get(conn, "/api/v1/timelines/public?local=true")
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"})
- assert length(json_response(res_conn, 200)) == 2
+ res_conn = get(conn, "/api/v1/timelines/public?local=false")
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 2
end
end
@@ -206,24 +206,24 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
setup do: clear_config([:restrict_unauthenticated, :timelines, :local], true)
test "if user is unauthenticated", %{conn: conn} do
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"})
+ res_conn = get(conn, "/api/v1/timelines/public?local=true")
- assert json_response(res_conn, :unauthorized) == %{
+ assert json_response_and_validate_schema(res_conn, :unauthorized) == %{
"error" => "authorization required for timeline view"
}
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"})
- assert length(json_response(res_conn, 200)) == 2
+ res_conn = get(conn, "/api/v1/timelines/public?local=false")
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 2
end
test "if user is authenticated", %{conn: _conn} do
%{conn: conn} = oauth_access(["read:statuses"])
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"})
- assert length(json_response(res_conn, 200)) == 1
+ res_conn = get(conn, "/api/v1/timelines/public?local=true")
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"})
- assert length(json_response(res_conn, 200)) == 2
+ res_conn = get(conn, "/api/v1/timelines/public?local=false")
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 2
end
end
@@ -233,12 +233,12 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
setup do: clear_config([:restrict_unauthenticated, :timelines, :federated], true)
test "if user is unauthenticated", %{conn: conn} do
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"})
- assert length(json_response(res_conn, 200)) == 1
+ res_conn = get(conn, "/api/v1/timelines/public?local=true")
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"})
+ res_conn = get(conn, "/api/v1/timelines/public?local=false")
- assert json_response(res_conn, :unauthorized) == %{
+ assert json_response_and_validate_schema(res_conn, :unauthorized) == %{
"error" => "authorization required for timeline view"
}
end
@@ -246,11 +246,11 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
test "if user is authenticated", %{conn: _conn} do
%{conn: conn} = oauth_access(["read:statuses"])
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"})
- assert length(json_response(res_conn, 200)) == 1
+ res_conn = get(conn, "/api/v1/timelines/public?local=true")
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 1
- res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"})
- assert length(json_response(res_conn, 200)) == 2
+ res_conn = get(conn, "/api/v1/timelines/public?local=false")
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 2
end
end
@@ -281,7 +281,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
# Only direct should be visible here
res_conn = get(conn_user_two, "api/v1/timelines/direct")
- [status] = json_response(res_conn, :ok)
+ assert [status] = json_response_and_validate_schema(res_conn, :ok)
assert %{"visibility" => "direct"} = status
assert status["url"] != direct.data["id"]
@@ -293,14 +293,14 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
|> assign(:token, insert(:oauth_token, user: user_one, scopes: ["read:statuses"]))
|> get("api/v1/timelines/direct")
- [status] = json_response(res_conn, :ok)
+ [status] = json_response_and_validate_schema(res_conn, :ok)
assert %{"visibility" => "direct"} = status
# Both should be visible here
res_conn = get(conn_user_two, "api/v1/timelines/home")
- [_s1, _s2] = json_response(res_conn, :ok)
+ [_s1, _s2] = json_response_and_validate_schema(res_conn, :ok)
# Test pagination
Enum.each(1..20, fn _ ->
@@ -313,13 +313,14 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
res_conn = get(conn_user_two, "api/v1/timelines/direct")
- statuses = json_response(res_conn, :ok)
+ statuses = json_response_and_validate_schema(res_conn, :ok)
assert length(statuses) == 20
- res_conn =
- get(conn_user_two, "api/v1/timelines/direct", %{max_id: List.last(statuses)["id"]})
+ max_id = List.last(statuses)["id"]
+
+ res_conn = get(conn_user_two, "api/v1/timelines/direct?max_id=#{max_id}")
- [status] = json_response(res_conn, :ok)
+ assert [status] = json_response_and_validate_schema(res_conn, :ok)
assert status["url"] != direct.data["id"]
end
@@ -344,7 +345,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
res_conn = get(conn, "api/v1/timelines/direct")
- [status] = json_response(res_conn, :ok)
+ [status] = json_response_and_validate_schema(res_conn, :ok)
assert status["id"] == direct.id
end
end
@@ -361,7 +362,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
conn = get(conn, "/api/v1/timelines/list/#{list.id}")
- assert [%{"id" => id}] = json_response(conn, :ok)
+ assert [%{"id" => id}] = json_response_and_validate_schema(conn, :ok)
assert id == to_string(activity_two.id)
end
@@ -384,7 +385,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
conn = get(conn, "/api/v1/timelines/list/#{list.id}")
- assert [%{"id" => id}] = json_response(conn, :ok)
+ assert [%{"id" => id}] = json_response_and_validate_schema(conn, :ok)
assert id == to_string(activity_one.id)
end
@@ -401,14 +402,14 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
nconn = get(conn, "/api/v1/timelines/tag/2hu")
- assert [%{"id" => id}] = json_response(nconn, :ok)
+ assert [%{"id" => id}] = json_response_and_validate_schema(nconn, :ok)
assert id == to_string(activity.id)
# works for different capitalization too
nconn = get(conn, "/api/v1/timelines/tag/2HU")
- assert [%{"id" => id}] = json_response(nconn, :ok)
+ assert [%{"id" => id}] = json_response_and_validate_schema(nconn, :ok)
assert id == to_string(activity.id)
end
@@ -420,22 +421,21 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
{:ok, activity_test1} = CommonAPI.post(user, %{"status" => "#test #test1"})
{:ok, activity_none} = CommonAPI.post(user, %{"status" => "#test #none"})
- any_test = get(conn, "/api/v1/timelines/tag/test", %{"any" => ["test1"]})
+ any_test = get(conn, "/api/v1/timelines/tag/test?any[]=test1")
- [status_none, status_test1, status_test] = json_response(any_test, :ok)
+ [status_none, status_test1, status_test] = json_response_and_validate_schema(any_test, :ok)
assert to_string(activity_test.id) == status_test["id"]
assert to_string(activity_test1.id) == status_test1["id"]
assert to_string(activity_none.id) == status_none["id"]
- restricted_test =
- get(conn, "/api/v1/timelines/tag/test", %{"all" => ["test1"], "none" => ["none"]})
+ restricted_test = get(conn, "/api/v1/timelines/tag/test?all[]=test1&none[]=none")
- assert [status_test1] == json_response(restricted_test, :ok)
+ assert [status_test1] == json_response_and_validate_schema(restricted_test, :ok)
- all_test = get(conn, "/api/v1/timelines/tag/test", %{"all" => ["none"]})
+ all_test = get(conn, "/api/v1/timelines/tag/test?all[]=none")
- assert [status_none] == json_response(all_test, :ok)
+ assert [status_none] == json_response_and_validate_schema(all_test, :ok)
end
end
end
--
cgit v1.2.3
From 5367a00257c6f862a4a8080e0176f676ce491e4d Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 11 May 2020 15:06:23 +0200
Subject: Deletion: Handle the case of pruned objects.
---
test/tasks/user_test.exs | 25 +++++++++++++++++++
test/web/activity_pub/side_effects_test.exs | 29 ++++++++++++++++++++++
.../transmogrifier/delete_handling_test.exs | 28 +++++++++++++++++++++
test/web/common_api/common_api_test.exs | 18 ++++++++++++++
4 files changed, 100 insertions(+)
(limited to 'test')
diff --git a/test/tasks/user_test.exs b/test/tasks/user_test.exs
index e0fee7290..b4f68d494 100644
--- a/test/tasks/user_test.exs
+++ b/test/tasks/user_test.exs
@@ -3,9 +3,12 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Mix.Tasks.Pleroma.UserTest do
+ alias Pleroma.Activity
+ alias Pleroma.Object
alias Pleroma.Repo
alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
+ alias Pleroma.Web.CommonAPI
alias Pleroma.Web.OAuth.Authorization
alias Pleroma.Web.OAuth.Token
@@ -103,6 +106,28 @@ defmodule Mix.Tasks.Pleroma.UserTest do
end
end
+ test "a remote user's create activity is deleted when the object has been pruned" do
+ user = insert(:user)
+
+ {:ok, post} = CommonAPI.post(user, %{"status" => "uguu"})
+ object = Object.normalize(post)
+ Object.prune(object)
+
+ with_mock Pleroma.Web.Federator,
+ publish: fn _ -> nil end do
+ Mix.Tasks.Pleroma.User.run(["rm", user.nickname])
+ ObanHelpers.perform_all()
+
+ assert_received {:mix_shell, :info, [message]}
+ assert message =~ " deleted"
+ assert %{deactivated: true} = User.get_by_nickname(user.nickname)
+
+ assert called(Pleroma.Web.Federator.publish(:_))
+ end
+
+ refute Activity.get_by_id(post.id)
+ end
+
test "no user to delete" do
Mix.Tasks.Pleroma.User.run(["rm", "nonexistent"])
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index b29a7a7be..aa3e40be1 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -64,6 +64,35 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
assert object.data["repliesCount"] == 0
end
+ test "it handles object deletions when the object itself has been pruned", %{
+ delete: delete,
+ post: post,
+ object: object,
+ user: user,
+ op: op
+ } do
+ with_mock Pleroma.Web.ActivityPub.ActivityPub, [:passthrough],
+ stream_out: fn _ -> nil end,
+ stream_out_participations: fn _, _ -> nil end do
+ {:ok, delete, _} = SideEffects.handle(delete)
+ user = User.get_cached_by_ap_id(object.data["actor"])
+
+ assert called(Pleroma.Web.ActivityPub.ActivityPub.stream_out(delete))
+ assert called(Pleroma.Web.ActivityPub.ActivityPub.stream_out_participations(object, user))
+ end
+
+ object = Object.get_by_id(object.id)
+ assert object.data["type"] == "Tombstone"
+ refute Activity.get_by_id(post.id)
+
+ user = User.get_by_id(user.id)
+ assert user.note_count == 0
+
+ object = Object.normalize(op.data["object"], false)
+
+ assert object.data["repliesCount"] == 0
+ end
+
test "it handles user deletions", %{delete_user: delete, user: user} do
{:ok, _delete, _} = SideEffects.handle(delete)
ObanHelpers.perform_all()
diff --git a/test/web/activity_pub/transmogrifier/delete_handling_test.exs b/test/web/activity_pub/transmogrifier/delete_handling_test.exs
index f235a8e63..c9a53918c 100644
--- a/test/web/activity_pub/transmogrifier/delete_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/delete_handling_test.exs
@@ -44,6 +44,34 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do
assert object.data["type"] == "Tombstone"
end
+ test "it works for incoming when the object has been pruned" do
+ activity = insert(:note_activity)
+
+ {:ok, object} =
+ Object.normalize(activity.data["object"])
+ |> Repo.delete()
+
+ Cachex.del(:object_cache, "object:#{object.data["id"]}")
+
+ deleting_user = insert(:user)
+
+ data =
+ File.read!("test/fixtures/mastodon-delete.json")
+ |> Poison.decode!()
+ |> Map.put("actor", deleting_user.ap_id)
+ |> put_in(["object", "id"], activity.data["object"])
+
+ {:ok, %Activity{actor: actor, local: false, data: %{"id" => id}}} =
+ Transmogrifier.handle_incoming(data)
+
+ assert id == data["id"]
+
+ # We delete the Create activity because we base our timelines on it.
+ # This should be changed after we unify objects and activities
+ refute Activity.get_by_id(activity.id)
+ assert actor == deleting_user.ap_id
+ end
+
test "it fails for incoming deletes with spoofed origin" do
activity = insert(:note_activity)
%{ap_id: ap_id} = insert(:user, ap_id: "https://gensokyo.2hu/users/raymoo")
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index 2fd17a1b8..c524d1c0c 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -24,6 +24,24 @@ defmodule Pleroma.Web.CommonAPITest do
setup do: clear_config([:instance, :max_pinned_statuses])
describe "deletion" do
+ test "it works with pruned objects" do
+ user = insert(:user)
+
+ {:ok, post} = CommonAPI.post(user, %{"status" => "namu amida butsu"})
+
+ Object.normalize(post, false)
+ |> Object.prune()
+
+ with_mock Pleroma.Web.Federator,
+ publish: fn _ -> nil end do
+ assert {:ok, delete} = CommonAPI.delete(post.id, user)
+ assert delete.local
+ assert called(Pleroma.Web.Federator.publish(delete))
+ end
+
+ refute Activity.get_by_id(post.id)
+ end
+
test "it allows users to delete their posts" do
user = insert(:user)
--
cgit v1.2.3
From 679afb2de40b532d749485ca6f27656fc5b2f25f Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 11 May 2020 15:38:19 +0200
Subject: SideEffects test: Add test for favorite deletion.
---
test/web/activity_pub/side_effects_test.exs | 16 ++++++++++++++--
1 file changed, 14 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index aa3e40be1..6c5f8fc61 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -27,12 +27,22 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
{:ok, op} = CommonAPI.post(other_user, %{"status" => "big oof"})
{:ok, post} = CommonAPI.post(user, %{"status" => "hey", "in_reply_to_id" => op})
+ {:ok, favorite} = CommonAPI.favorite(user, post.id)
object = Object.normalize(post)
{:ok, delete_data, _meta} = Builder.delete(user, object.data["id"])
{:ok, delete_user_data, _meta} = Builder.delete(user, user.ap_id)
{:ok, delete, _meta} = ActivityPub.persist(delete_data, local: true)
{:ok, delete_user, _meta} = ActivityPub.persist(delete_user_data, local: true)
- %{user: user, delete: delete, post: post, object: object, delete_user: delete_user, op: op}
+
+ %{
+ user: user,
+ delete: delete,
+ post: post,
+ object: object,
+ delete_user: delete_user,
+ op: op,
+ favorite: favorite
+ }
end
test "it handles object deletions", %{
@@ -40,7 +50,8 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
post: post,
object: object,
user: user,
- op: op
+ op: op,
+ favorite: favorite
} do
with_mock Pleroma.Web.ActivityPub.ActivityPub, [:passthrough],
stream_out: fn _ -> nil end,
@@ -55,6 +66,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
object = Object.get_by_id(object.id)
assert object.data["type"] == "Tombstone"
refute Activity.get_by_id(post.id)
+ refute Activity.get_by_id(favorite.id)
user = User.get_by_id(user.id)
assert user.note_count == 0
--
cgit v1.2.3
From 63477d07adb614413a382a87f06af2bc2495b432 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Tue, 12 May 2020 06:44:33 +0300
Subject: unsubscribes of friends when user deactivated
---
test/tasks/user_test.exs | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/tasks/user_test.exs b/test/tasks/user_test.exs
index b4f68d494..4b3ab5a87 100644
--- a/test/tasks/user_test.exs
+++ b/test/tasks/user_test.exs
@@ -172,23 +172,23 @@ defmodule Mix.Tasks.Pleroma.UserTest do
describe "running unsubscribe" do
test "user is unsubscribed" do
followed = insert(:user)
+ remote_followed = insert(:user, local: false)
user = insert(:user)
+
User.follow(user, followed, :follow_accept)
+ User.follow(user, remote_followed, :follow_accept)
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_cached_by_nickname(user.nickname)
- assert Enum.empty?(User.get_friends(user))
+ assert Enum.empty?(Enum.filter(User.get_friends(user), & &1.local))
assert user.deactivated
end
--
cgit v1.2.3
From d0ba1844b031030cde5b5cf4a5714bb6ff483866 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 12 May 2020 10:52:46 +0200
Subject: ActivityPub: Fix non-federating blocks.
---
test/web/activity_pub/activity_pub_test.exs | 32 +++++++++++++++++++++++++----
1 file changed, 28 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 0739cbfef..59bdd53cd 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -1061,14 +1061,38 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
end
test "creates a block activity" do
+ clear_config([:instance, :federating], true)
blocker = insert(:user)
blocked = insert(:user)
- {:ok, activity} = ActivityPub.block(blocker, blocked)
+ with_mock Pleroma.Web.Federator,
+ publish: fn _ -> nil end do
+ {:ok, activity} = ActivityPub.block(blocker, blocked)
- assert activity.data["type"] == "Block"
- assert activity.data["actor"] == blocker.ap_id
- assert activity.data["object"] == blocked.ap_id
+ assert activity.data["type"] == "Block"
+ assert activity.data["actor"] == blocker.ap_id
+ assert activity.data["object"] == blocked.ap_id
+
+ assert called(Pleroma.Web.Federator.publish(activity))
+ end
+ end
+
+ test "works with outgoing blocks disabled, but doesn't federate" do
+ clear_config([:instance, :federating], true)
+ clear_config([:activitypub, :outgoing_blocks], false)
+ blocker = insert(:user)
+ blocked = insert(:user)
+
+ with_mock Pleroma.Web.Federator,
+ publish: fn _ -> nil end do
+ {:ok, activity} = ActivityPub.block(blocker, blocked)
+
+ assert activity.data["type"] == "Block"
+ assert activity.data["actor"] == blocker.ap_id
+ assert activity.data["object"] == blocked.ap_id
+
+ refute called(Pleroma.Web.Federator.publish(:_))
+ end
end
end
--
cgit v1.2.3
From ca31af473c556f8320914f0621d08d59c96d3bef Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 12 May 2020 12:29:37 +0200
Subject: Transmogrifier: On incoming follow accept, update follow counts.
---
test/web/activity_pub/transmogrifier_test.exs | 6 ++++++
1 file changed, 6 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 2914c90ea..7d39d9067 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -815,6 +815,12 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
follower = User.get_cached_by_id(follower.id)
assert User.following?(follower, followed) == true
+
+ follower = User.get_by_id(follower.id)
+ assert follower.following_count == 1
+
+ followed = User.get_by_id(followed.id)
+ assert followed.follower_count == 1
end
test "it fails for incoming accepts which cannot be correlated" do
--
cgit v1.2.3
From dfb90a1fd64cfb8f81707d939a87a02e8047dc3b Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 12 May 2020 12:50:48 +0200
Subject: Transmogrifier: Add tests for certain announces
---
test/web/activity_pub/transmogrifier_test.exs | 18 +++++++++++++++
.../controllers/account_controller_test.exs | 27 ++++++++++++++++++++++
2 files changed, 45 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 2914c90ea..34e77fa79 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -260,6 +260,24 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
"henlo from my Psion netBook
message sent from my Psion netBook
"
end
+ test "it works for incoming honk announces" do
+ _user = insert(:user, ap_id: "https://honktest/u/test", local: false)
+ other_user = insert(:user)
+ {:ok, post} = CommonAPI.post(other_user, %{"status" => "bonkeronk"})
+
+ announce = %{
+ "@context" => "https://www.w3.org/ns/activitystreams",
+ "actor" => "https://honktest/u/test",
+ "id" => "https://honktest/u/test/bonk/1793M7B9MQ48847vdx",
+ "object" => post.data["object"],
+ "published" => "2019-06-25T19:33:58Z",
+ "to" => "https://www.w3.org/ns/activitystreams#Public",
+ "type" => "Announce"
+ }
+
+ {:ok, %Activity{local: false}} = Transmogrifier.handle_incoming(announce)
+ end
+
test "it works for incoming announces with actor being inlined (kroeg)" do
data = File.read!("test/fixtures/kroeg-announce-with-inline-actor.json") |> Poison.decode!()
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 256a8b304..0d48ae4ae 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -222,6 +222,33 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
describe "user timelines" do
setup do: oauth_access(["read:statuses"])
+ test "works with announces that are just addressed to public", %{conn: conn} do
+ user = insert(:user, ap_id: "https://honktest/u/test", local: false)
+ other_user = insert(:user)
+
+ {:ok, post} = CommonAPI.post(other_user, %{"status" => "bonkeronk"})
+
+ {:ok, announce, _} =
+ %{
+ "@context" => "https://www.w3.org/ns/activitystreams",
+ "actor" => "https://honktest/u/test",
+ "id" => "https://honktest/u/test/bonk/1793M7B9MQ48847vdx",
+ "object" => post.data["object"],
+ "published" => "2019-06-25T19:33:58Z",
+ "to" => ["https://www.w3.org/ns/activitystreams#Public"],
+ "type" => "Announce"
+ }
+ |> ActivityPub.persist(local: false)
+
+ assert resp =
+ conn
+ |> get("/api/v1/accounts/#{user.id}/statuses")
+ |> json_response_and_validate_schema(200)
+
+ assert [%{"id" => id}] = resp
+ assert id == announce.id
+ end
+
test "respects blocks", %{user: user_one, conn: conn} do
user_two = insert(:user)
user_three = insert(:user)
--
cgit v1.2.3
From e6d8cacf2de4ba48b881a390b0ba4582981d17a5 Mon Sep 17 00:00:00 2001
From: href
Date: Tue, 12 May 2020 18:04:47 +0200
Subject: Expand and authorize streams in Streamer directly
---
test/integration/mastodon_websocket_test.exs | 12 +--
test/notification_test.exs | 4 +-
test/web/streamer/streamer_test.exs | 124 +++++++++++++++++++++------
3 files changed, 105 insertions(+), 35 deletions(-)
(limited to 'test')
diff --git a/test/integration/mastodon_websocket_test.exs b/test/integration/mastodon_websocket_test.exs
index 109c7b4cb..63f351a80 100644
--- a/test/integration/mastodon_websocket_test.exs
+++ b/test/integration/mastodon_websocket_test.exs
@@ -32,7 +32,7 @@ defmodule Pleroma.Integration.MastodonWebsocketTest do
test "refuses invalid requests" do
capture_log(fn ->
- assert {:error, {400, _}} = start_socket()
+ assert {:error, {404, _}} = start_socket()
assert {:error, {404, _}} = start_socket("?stream=ncjdk")
Process.sleep(30)
end)
@@ -40,8 +40,8 @@ defmodule Pleroma.Integration.MastodonWebsocketTest do
test "requires authentication and a valid token for protected streams" do
capture_log(fn ->
- assert {:error, {403, _}} = start_socket("?stream=user&access_token=aaaaaaaaaaaa")
- assert {:error, {403, _}} = start_socket("?stream=user")
+ assert {:error, {401, _}} = start_socket("?stream=user&access_token=aaaaaaaaaaaa")
+ assert {:error, {401, _}} = start_socket("?stream=user")
Process.sleep(30)
end)
end
@@ -100,7 +100,7 @@ defmodule Pleroma.Integration.MastodonWebsocketTest do
assert {:ok, _} = start_socket("?stream=user&access_token=#{token.token}")
assert capture_log(fn ->
- assert {:error, {403, "Forbidden"}} = start_socket("?stream=user")
+ assert {:error, {401, _}} = start_socket("?stream=user")
Process.sleep(30)
end) =~ ":badarg"
end
@@ -109,7 +109,7 @@ defmodule Pleroma.Integration.MastodonWebsocketTest do
assert {:ok, _} = start_socket("?stream=user:notification&access_token=#{token.token}")
assert capture_log(fn ->
- assert {:error, {403, "Forbidden"}} = start_socket("?stream=user:notification")
+ assert {:error, {401, _}} = start_socket("?stream=user:notification")
Process.sleep(30)
end) =~ ":badarg"
end
@@ -118,7 +118,7 @@ defmodule Pleroma.Integration.MastodonWebsocketTest do
assert {:ok, _} = start_socket("?stream=user", [{"Sec-WebSocket-Protocol", token.token}])
assert capture_log(fn ->
- assert {:error, {403, "Forbidden"}} =
+ assert {:error, {401, "Forbidden"}} =
start_socket("?stream=user", [{"Sec-WebSocket-Protocol", "I am a friend"}])
Process.sleep(30)
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 24e5f0c73..4dfbc1019 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -170,13 +170,13 @@ defmodule Pleroma.NotificationTest do
task =
Task.async(fn ->
- Streamer.add_socket("user", user)
+ Streamer.get_topic_and_add_socket("user", user)
assert_receive {:render_with_user, _, _, _}, 4_000
end)
task_user_notification =
Task.async(fn ->
- Streamer.add_socket("user:notification", user)
+ Streamer.get_topic_and_add_socket("user:notification", user)
assert_receive {:render_with_user, _, _, _}, 4_000
end)
diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs
index ee530f4e9..db07c5df5 100644
--- a/test/web/streamer/streamer_test.exs
+++ b/test/web/streamer/streamer_test.exs
@@ -17,6 +17,76 @@ defmodule Pleroma.Web.StreamerTest do
setup do: clear_config([:instance, :skip_thread_containment])
+ describe "get_topic without an user" do
+ test "allows public" do
+ assert {:ok, "public"} = Streamer.get_topic("public", nil)
+ assert {:ok, "public:local"} = Streamer.get_topic("public:local", nil)
+ assert {:ok, "public:media"} = Streamer.get_topic("public:media", nil)
+ assert {:ok, "public:local:media"} = Streamer.get_topic("public:local:media", nil)
+ end
+
+ test "allows hashtag streams" do
+ assert {:ok, "hashtag:cofe"} = Streamer.get_topic("hashtag", nil, %{"tag" => "cofe"})
+ end
+
+ test "disallows user streams" do
+ assert {:error, _} = Streamer.get_topic("user", nil)
+ assert {:error, _} = Streamer.get_topic("user:notification", nil)
+ assert {:error, _} = Streamer.get_topic("direct", nil)
+ end
+
+ test "disallows list streams" do
+ assert {:error, _} = Streamer.get_topic("list", nil, %{"list" => 42})
+ end
+ end
+
+ describe "get_topic with an user" do
+ setup do
+ user = insert(:user)
+ {:ok, %{user: user}}
+ end
+
+ test "allows public streams", %{user: user} do
+ assert {:ok, "public"} = Streamer.get_topic("public", user)
+ assert {:ok, "public:local"} = Streamer.get_topic("public:local", user)
+ assert {:ok, "public:media"} = Streamer.get_topic("public:media", user)
+ assert {:ok, "public:local:media"} = Streamer.get_topic("public:local:media", user)
+ end
+
+ test "allows user streams", %{user: user} do
+ expected_user_topic = "user:#{user.id}"
+ expected_notif_topic = "user:notification:#{user.id}"
+ expected_direct_topic = "direct:#{user.id}"
+ assert {:ok, ^expected_user_topic} = Streamer.get_topic("user", user)
+ assert {:ok, ^expected_notif_topic} = Streamer.get_topic("user:notification", user)
+ assert {:ok, ^expected_direct_topic} = Streamer.get_topic("direct", user)
+ end
+
+ test "allows hashtag streams", %{user: user} do
+ assert {:ok, "hashtag:cofe"} = Streamer.get_topic("hashtag", user, %{"tag" => "cofe"})
+ end
+
+ test "disallows registering to an user stream", %{user: user} do
+ another_user = insert(:user)
+ assert {:error, _} = Streamer.get_topic("user:#{another_user.id}", user)
+ assert {:error, _} = Streamer.get_topic("user:notification:#{another_user.id}", user)
+ assert {:error, _} = Streamer.get_topic("direct:#{another_user.id}", user)
+ end
+
+ test "allows list stream that are owned by the user", %{user: user} do
+ {:ok, list} = List.create("Test", user)
+ assert {:error, _} = Streamer.get_topic("list:#{list.id}", user)
+ assert {:ok, _} = Streamer.get_topic("list", user, %{"list" => list.id})
+ end
+
+ test "disallows list stream that are not owned by the user", %{user: user} do
+ another_user = insert(:user)
+ {:ok, list} = List.create("Test", another_user)
+ assert {:error, _} = Streamer.get_topic("list:#{list.id}", user)
+ assert {:error, _} = Streamer.get_topic("list", user, %{"list" => list.id})
+ end
+ end
+
describe "user streams" do
setup do
user = insert(:user)
@@ -25,14 +95,14 @@ defmodule Pleroma.Web.StreamerTest do
end
test "it streams the user's post in the 'user' stream", %{user: user} do
- Streamer.add_socket("user", user)
+ Streamer.get_topic_and_add_socket("user", user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
assert_receive {:render_with_user, _, _, ^activity}
refute Streamer.filtered_by_user?(user, activity)
end
test "it streams boosts of the user in the 'user' stream", %{user: user} do
- Streamer.add_socket("user", user)
+ Streamer.get_topic_and_add_socket("user", user)
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "hey"})
@@ -43,14 +113,14 @@ defmodule Pleroma.Web.StreamerTest do
end
test "it sends notify to in the 'user' stream", %{user: user, notify: notify} do
- Streamer.add_socket("user", user)
+ Streamer.get_topic_and_add_socket("user", user)
Streamer.stream("user", notify)
assert_receive {:render_with_user, _, _, ^notify}
refute Streamer.filtered_by_user?(user, notify)
end
test "it sends notify to in the 'user:notification' stream", %{user: user, notify: notify} do
- Streamer.add_socket("user:notification", user)
+ Streamer.get_topic_and_add_socket("user:notification", user)
Streamer.stream("user:notification", notify)
assert_receive {:render_with_user, _, _, ^notify}
refute Streamer.filtered_by_user?(user, notify)
@@ -62,7 +132,7 @@ defmodule Pleroma.Web.StreamerTest do
blocked = insert(:user)
{:ok, _user_relationship} = User.block(user, blocked)
- Streamer.add_socket("user:notification", user)
+ Streamer.get_topic_and_add_socket("user:notification", user)
{:ok, activity} = CommonAPI.post(user, %{"status" => ":("})
{:ok, _} = CommonAPI.favorite(blocked, activity.id)
@@ -78,7 +148,7 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
{:ok, _} = CommonAPI.add_mute(user, activity)
- Streamer.add_socket("user:notification", user)
+ Streamer.get_topic_and_add_socket("user:notification", user)
{:ok, favorite_activity} = CommonAPI.favorite(user2, activity.id)
@@ -92,7 +162,7 @@ defmodule Pleroma.Web.StreamerTest do
user2 = insert(:user, %{ap_id: "https://hecking-lewd-place.com/user/meanie"})
{:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
- Streamer.add_socket("user:notification", user)
+ Streamer.get_topic_and_add_socket("user:notification", user)
{:ok, favorite_activity} = CommonAPI.favorite(user2, activity.id)
assert_receive {:render_with_user, _, "notification.json", notif}
@@ -107,7 +177,7 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, user} = User.block_domain(user, "hecking-lewd-place.com")
{:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
- Streamer.add_socket("user:notification", user)
+ Streamer.get_topic_and_add_socket("user:notification", user)
{:ok, favorite_activity} = CommonAPI.favorite(user2, activity.id)
refute_receive _
@@ -130,7 +200,7 @@ defmodule Pleroma.Web.StreamerTest do
%Tesla.Env{status: 200, body: body}
end)
- Streamer.add_socket("user:notification", user)
+ Streamer.get_topic_and_add_socket("user:notification", user)
{:ok, _follower, _followed, follow_activity} = CommonAPI.follow(user2, user)
assert_receive {:render_with_user, _, "notification.json", notif}
@@ -143,7 +213,7 @@ defmodule Pleroma.Web.StreamerTest do
user = insert(:user)
other_user = insert(:user)
- Streamer.add_socket("public", other_user)
+ Streamer.get_topic_and_add_socket("public", other_user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "Test"})
assert_receive {:render_with_user, _, _, ^activity}
@@ -155,7 +225,7 @@ defmodule Pleroma.Web.StreamerTest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "Test"})
- Streamer.add_socket("public", user)
+ Streamer.get_topic_and_add_socket("public", user)
{:ok, _} = CommonAPI.delete(activity.id, other_user)
activity_id = activity.id
@@ -166,7 +236,7 @@ defmodule Pleroma.Web.StreamerTest do
test "it sends to public unauthenticated" do
user = insert(:user)
- Streamer.add_socket("public", nil)
+ Streamer.get_topic_and_add_socket("public", nil)
{:ok, activity} = CommonAPI.post(user, %{"status" => "Test"})
activity_id = activity.id
@@ -195,7 +265,7 @@ defmodule Pleroma.Web.StreamerTest do
)
)
- Streamer.add_socket("public", user)
+ Streamer.get_topic_and_add_socket("public", user)
Streamer.stream("public", activity)
assert_receive {:render_with_user, _, _, ^activity}
assert Streamer.filtered_by_user?(user, activity)
@@ -216,7 +286,7 @@ defmodule Pleroma.Web.StreamerTest do
)
)
- Streamer.add_socket("public", user)
+ Streamer.get_topic_and_add_socket("public", user)
Streamer.stream("public", activity)
assert_receive {:render_with_user, _, _, ^activity}
@@ -238,7 +308,7 @@ defmodule Pleroma.Web.StreamerTest do
)
)
- Streamer.add_socket("public", user)
+ Streamer.get_topic_and_add_socket("public", user)
Streamer.stream("public", activity)
assert_receive {:render_with_user, _, _, ^activity}
@@ -252,7 +322,7 @@ defmodule Pleroma.Web.StreamerTest do
blocked_user = insert(:user)
{:ok, _user_relationship} = User.block(user, blocked_user)
- Streamer.add_socket("public", user)
+ Streamer.get_topic_and_add_socket("public", user)
{:ok, activity} = CommonAPI.post(blocked_user, %{"status" => "Test"})
assert_receive {:render_with_user, _, _, ^activity}
assert Streamer.filtered_by_user?(user, activity)
@@ -263,7 +333,7 @@ defmodule Pleroma.Web.StreamerTest do
blockee = insert(:user)
friend = insert(:user)
- Streamer.add_socket("public", blocker)
+ Streamer.get_topic_and_add_socket("public", blocker)
{:ok, _user_relationship} = User.block(blocker, blockee)
@@ -295,7 +365,7 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, list} = List.create("Test", user_a)
{:ok, list} = List.follow(list, user_b)
- Streamer.add_socket("list:#{list.id}", user_a)
+ Streamer.get_topic_and_add_socket("list", user_a, %{"list" => list.id})
{:ok, _activity} =
CommonAPI.post(user_b, %{
@@ -313,7 +383,7 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, list} = List.create("Test", user_a)
{:ok, list} = List.follow(list, user_b)
- Streamer.add_socket("list:#{list.id}", user_a)
+ Streamer.get_topic_and_add_socket("list", user_a, %{"list" => list.id})
{:ok, _activity} =
CommonAPI.post(user_b, %{
@@ -333,7 +403,7 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, list} = List.create("Test", user_a)
{:ok, list} = List.follow(list, user_b)
- Streamer.add_socket("list:#{list.id}", user_a)
+ Streamer.get_topic_and_add_socket("list", user_a, %{"list" => list.id})
{:ok, activity} =
CommonAPI.post(user_b, %{
@@ -356,7 +426,7 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, create_activity} = CommonAPI.post(user3, %{"status" => "I'm kawen"})
- Streamer.add_socket("user", user1)
+ Streamer.get_topic_and_add_socket("user", user1)
{:ok, announce_activity, _} = CommonAPI.repeat(create_activity.id, user2)
assert_receive {:render_with_user, _, _, ^announce_activity}
assert Streamer.filtered_by_user?(user1, announce_activity)
@@ -369,7 +439,7 @@ defmodule Pleroma.Web.StreamerTest do
CommonAPI.hide_reblogs(user1, user2)
{:ok, create_activity} = CommonAPI.post(user1, %{"status" => "I'm kawen"})
- Streamer.add_socket("user", user1)
+ Streamer.get_topic_and_add_socket("user", user1)
{:ok, _favorite_activity, _} = CommonAPI.repeat(create_activity.id, user2)
assert_receive {:render_with_user, _, "notification.json", notif}
@@ -383,7 +453,7 @@ defmodule Pleroma.Web.StreamerTest do
CommonAPI.hide_reblogs(user1, user2)
{:ok, create_activity} = CommonAPI.post(user1, %{"status" => "I'm kawen"})
- Streamer.add_socket("user", user1)
+ Streamer.get_topic_and_add_socket("user", user1)
{:ok, _favorite_activity} = CommonAPI.favorite(user2, create_activity.id)
assert_receive {:render_with_user, _, "notification.json", notif}
@@ -394,7 +464,7 @@ defmodule Pleroma.Web.StreamerTest do
test "it filters posts from muted threads" do
user = insert(:user)
user2 = insert(:user)
- Streamer.add_socket("user", user2)
+ Streamer.get_topic_and_add_socket("user", user2)
{:ok, user2, user, _activity} = CommonAPI.follow(user2, user)
{:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
{:ok, _} = CommonAPI.add_mute(user2, activity)
@@ -411,7 +481,7 @@ defmodule Pleroma.Web.StreamerTest do
user = insert(:user)
another_user = insert(:user)
- Streamer.add_socket("direct", user)
+ Streamer.get_topic_and_add_socket("direct", user)
{:ok, _create_activity} =
CommonAPI.post(another_user, %{
@@ -433,7 +503,7 @@ defmodule Pleroma.Web.StreamerTest do
user = insert(:user)
another_user = insert(:user)
- Streamer.add_socket("direct", user)
+ Streamer.get_topic_and_add_socket("direct", user)
{:ok, create_activity} =
CommonAPI.post(another_user, %{
@@ -459,7 +529,7 @@ defmodule Pleroma.Web.StreamerTest do
test "it sends conversation update to the 'direct' stream when a message is deleted" do
user = insert(:user)
another_user = insert(:user)
- Streamer.add_socket("direct", user)
+ Streamer.get_topic_and_add_socket("direct", user)
{:ok, create_activity} =
CommonAPI.post(another_user, %{
--
cgit v1.2.3
From 620247a015f6cd894a119bb5173a3da7e5913064 Mon Sep 17 00:00:00 2001
From: Stephanie Wilde-Hobbs
Date: Tue, 12 May 2020 17:12:27 +0100
Subject: Add database configuration whitelist
---
test/web/admin_api/admin_api_controller_test.exs | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 4697af50e..31e73d6a5 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -2943,6 +2943,30 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
]
}
end
+
+ test "doesn't set keys not in the whitelist", %{conn: conn} do
+ clear_config(:database_config_whitelist, [
+ {:pleroma, :key1},
+ {:pleroma, :key2},
+ {:pleroma, Pleroma.Captcha.NotReal}
+ ])
+
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{group: ":pleroma", key: ":key1", value: "value1"},
+ %{group: ":pleroma", key: ":key2", value: "value2"},
+ %{group: ":pleroma", key: ":key3", value: "value3"},
+ %{group: ":pleroma", key: "Pleroma.Web.Endpoint.NotReal", value: "value4"},
+ %{group: ":pleroma", key: "Pleroma.Captcha.NotReal", value: "value5"}
+ ]
+ })
+
+ assert Application.get_env(:pleroma, :key1) == "value1"
+ assert Application.get_env(:pleroma, :key2) == "value2"
+ assert Application.get_env(:pleroma, :key3) == nil
+ assert Application.get_env(:pleroma, Pleroma.Web.Endpoint.NotReal) == nil
+ assert Application.get_env(:pleroma, Pleroma.Captcha.NotReal) == "value5"
+ end
end
describe "GET /api/pleroma/admin/restart" do
--
cgit v1.2.3
From 68cca29dcf87d68be82c0287f3803847abd54353 Mon Sep 17 00:00:00 2001
From: href
Date: Tue, 12 May 2020 18:51:10 +0200
Subject: Fix typo in test
---
test/integration/mastodon_websocket_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/integration/mastodon_websocket_test.exs b/test/integration/mastodon_websocket_test.exs
index 63f351a80..f61150cd2 100644
--- a/test/integration/mastodon_websocket_test.exs
+++ b/test/integration/mastodon_websocket_test.exs
@@ -118,7 +118,7 @@ defmodule Pleroma.Integration.MastodonWebsocketTest do
assert {:ok, _} = start_socket("?stream=user", [{"Sec-WebSocket-Protocol", token.token}])
assert capture_log(fn ->
- assert {:error, {401, "Forbidden"}} =
+ assert {:error, {401, _}} =
start_socket("?stream=user", [{"Sec-WebSocket-Protocol", "I am a friend"}])
Process.sleep(30)
--
cgit v1.2.3
From a2fcfc78c9dcf33081db47292d96ffa7c7709abb Mon Sep 17 00:00:00 2001
From: Stephanie Wilde-Hobbs
Date: Tue, 12 May 2020 21:07:33 +0100
Subject: Filter config descriptions by config whitelist
---
test/web/admin_api/admin_api_controller_test.exs | 51 +++++++++++++++++++-----
1 file changed, 41 insertions(+), 10 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 31e73d6a5..7d42a400c 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -3604,19 +3604,50 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
end
- test "GET /api/pleroma/admin/config/descriptions", %{conn: conn} do
- admin = insert(:user, is_admin: true)
+ describe "GET /api/pleroma/admin/config/descriptions" do
+ test "structure", %{conn: conn} do
+ admin = insert(:user, is_admin: true)
- conn =
- assign(conn, :user, admin)
- |> get("/api/pleroma/admin/config/descriptions")
+ conn =
+ assign(conn, :user, admin)
+ |> get("/api/pleroma/admin/config/descriptions")
+
+ assert [child | _others] = json_response(conn, 200)
- assert [child | _others] = json_response(conn, 200)
+ assert child["children"]
+ assert child["key"]
+ assert String.starts_with?(child["group"], ":")
+ assert child["description"]
+ end
- assert child["children"]
- assert child["key"]
- assert String.starts_with?(child["group"], ":")
- assert child["description"]
+ test "filters by database configuration whitelist", %{conn: conn} do
+ clear_config(:database_config_whitelist, [
+ {:pleroma, :instance},
+ {:pleroma, :activitypub},
+ {:pleroma, Pleroma.Upload}
+ ])
+
+ admin = insert(:user, is_admin: true)
+
+ conn =
+ assign(conn, :user, admin)
+ |> get("/api/pleroma/admin/config/descriptions")
+
+ children = json_response(conn, 200)
+
+ assert length(children) == 3
+
+ assert Enum.all?(children, fn c -> c["group"] == ":pleroma" end)
+
+ instance = Enum.find(children, fn c -> c["key"] == ":instance" end)
+ assert instance["children"]
+
+ activitypub = Enum.find(children, fn c -> c["key"] == ":activitypub" end)
+ assert activitypub["children"]
+
+ web_endpoint = Enum.find(children, fn c -> c["key"] == "Pleroma.Upload" end)
+ assert web_endpoint["children"]
+ end
end
describe "/api/pleroma/admin/stats" do
--
cgit v1.2.3
From 7803a85d2ced092fbd8e0f1bde0944bd27f8d649 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 12 May 2020 23:59:26 +0400
Subject: Add OpenAPI spec for StatusController
---
test/activity_test.exs | 8 +-
test/bbs/handler_test.exs | 6 +-
test/bookmark_test.exs | 6 +-
test/conversation/participation_test.exs | 72 +--
test/conversation_test.exs | 22 +-
test/html_test.exs | 14 +-
test/integration/mastodon_websocket_test.exs | 2 +-
test/notification_test.exs | 126 ++---
test/stats_test.exs | 22 +-
test/tasks/count_statuses_test.exs | 6 +-
test/tasks/database_test.exs | 6 +-
test/tasks/digest_test.exs | 2 +-
test/tasks/refresh_counter_cache_test.exs | 14 +-
test/tasks/user_test.exs | 2 +-
test/user_test.exs | 16 +-
.../activity_pub/activity_pub_controller_test.exs | 2 +-
test/web/activity_pub/activity_pub_test.exs | 248 +++++-----
test/web/activity_pub/object_validator_test.exs | 8 +-
test/web/activity_pub/side_effects_test.exs | 10 +-
.../transmogrifier/emoji_react_handling_test.exs | 4 +-
.../transmogrifier/like_handling_test.exs | 6 +-
.../transmogrifier/undo_handling_test.exs | 10 +-
test/web/activity_pub/transmogrifier_test.exs | 71 ++-
test/web/activity_pub/utils_test.exs | 26 +-
test/web/activity_pub/views/object_view_test.exs | 2 +-
test/web/activity_pub/views/user_view_test.exs | 2 +-
test/web/activity_pub/visibilty_test.exs | 12 +-
test/web/admin_api/admin_api_controller_test.exs | 46 +-
test/web/admin_api/views/report_view_test.exs | 2 +-
test/web/common_api/common_api_test.exs | 112 +++--
test/web/common_api/common_api_utils_test.exs | 14 +-
test/web/federator_test.exs | 4 +-
test/web/feed/tag_controller_test.exs | 12 +-
.../controllers/account_controller_test.exs | 29 +-
.../controllers/conversation_controller_test.exs | 58 +--
.../controllers/instance_controller_test.exs | 2 +-
.../controllers/notification_controller_test.exs | 77 ++--
.../controllers/poll_controller_test.exs | 38 +-
.../controllers/report_controller_test.exs | 2 +-
.../controllers/search_controller_test.exs | 38 +-
.../controllers/status_controller_test.exs | 513 +++++++++++++--------
.../controllers/timeline_controller_test.exs | 64 ++-
test/web/mastodon_api/mastodon_api_test.exs | 4 +-
test/web/mastodon_api/views/account_view_test.exs | 13 +-
.../mastodon_api/views/conversation_view_test.exs | 2 +-
.../mastodon_api/views/notification_view_test.exs | 8 +-
test/web/mastodon_api/views/poll_view_test.exs | 36 +-
.../views/scheduled_activity_view_test.exs | 4 +-
test/web/mastodon_api/views/status_view_test.exs | 53 ++-
test/web/metadata/twitter_card_test.exs | 6 +-
.../controllers/account_controller_test.exs | 8 +-
.../controllers/pleroma_api_controller_test.exs | 42 +-
test/web/push/impl_test.exs | 28 +-
test/web/rich_media/helpers_test.exs | 28 +-
test/web/static_fe/static_fe_controller_test.exs | 27 +-
test/web/streamer/streamer_test.exs | 64 +--
test/workers/cron/digest_emails_worker_test.exs | 2 +-
test/workers/cron/new_users_digest_worker_test.exs | 4 +-
58 files changed, 1099 insertions(+), 966 deletions(-)
(limited to 'test')
diff --git a/test/activity_test.exs b/test/activity_test.exs
index 0c19f481b..507027e5a 100644
--- a/test/activity_test.exs
+++ b/test/activity_test.exs
@@ -125,8 +125,8 @@ defmodule Pleroma.ActivityTest do
"to" => ["https://www.w3.org/ns/activitystreams#Public"]
}
- {:ok, local_activity} = Pleroma.Web.CommonAPI.post(user, %{"status" => "find me!"})
- {:ok, japanese_activity} = Pleroma.Web.CommonAPI.post(user, %{"status" => "更新情報"})
+ {:ok, local_activity} = Pleroma.Web.CommonAPI.post(user, %{status: "find me!"})
+ {:ok, japanese_activity} = Pleroma.Web.CommonAPI.post(user, %{status: "更新情報"})
{:ok, job} = Pleroma.Web.Federator.incoming_ap_doc(params)
{:ok, remote_activity} = ObanHelpers.perform(job)
@@ -225,8 +225,8 @@ defmodule Pleroma.ActivityTest do
test "all_by_actor_and_id/2" do
user = insert(:user)
- {:ok, %{id: id1}} = Pleroma.Web.CommonAPI.post(user, %{"status" => "cofe"})
- {:ok, %{id: id2}} = Pleroma.Web.CommonAPI.post(user, %{"status" => "cofefe"})
+ {:ok, %{id: id1}} = Pleroma.Web.CommonAPI.post(user, %{status: "cofe"})
+ {:ok, %{id: id2}} = Pleroma.Web.CommonAPI.post(user, %{status: "cofefe"})
assert [] == Activity.all_by_actor_and_id(user, [])
diff --git a/test/bbs/handler_test.exs b/test/bbs/handler_test.exs
index 74982547b..eb716486e 100644
--- a/test/bbs/handler_test.exs
+++ b/test/bbs/handler_test.exs
@@ -21,8 +21,8 @@ defmodule Pleroma.BBS.HandlerTest do
{:ok, user} = User.follow(user, followed)
- {:ok, _first} = CommonAPI.post(user, %{"status" => "hey"})
- {:ok, _second} = CommonAPI.post(followed, %{"status" => "hello"})
+ {:ok, _first} = CommonAPI.post(user, %{status: "hey"})
+ {:ok, _second} = CommonAPI.post(followed, %{status: "hello"})
output =
capture_io(fn ->
@@ -62,7 +62,7 @@ defmodule Pleroma.BBS.HandlerTest do
user = insert(:user)
another_user = insert(:user)
- {:ok, activity} = CommonAPI.post(another_user, %{"status" => "this is a test post"})
+ {:ok, activity} = CommonAPI.post(another_user, %{status: "this is a test post"})
activity_object = Object.normalize(activity)
output =
diff --git a/test/bookmark_test.exs b/test/bookmark_test.exs
index 021f79322..2726fe7cd 100644
--- a/test/bookmark_test.exs
+++ b/test/bookmark_test.exs
@@ -11,7 +11,7 @@ defmodule Pleroma.BookmarkTest do
describe "create/2" do
test "with valid params" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Some cool information"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "Some cool information"})
{:ok, bookmark} = Bookmark.create(user.id, activity.id)
assert bookmark.user_id == user.id
assert bookmark.activity_id == activity.id
@@ -32,7 +32,7 @@ defmodule Pleroma.BookmarkTest do
test "with valid params" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Some cool information"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "Some cool information"})
{:ok, _bookmark} = Bookmark.create(user.id, activity.id)
{:ok, _deleted_bookmark} = Bookmark.destroy(user.id, activity.id)
@@ -45,7 +45,7 @@ defmodule Pleroma.BookmarkTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" =>
+ status:
"Scientists Discover The Secret Behind Tenshi Eating A Corndog Being So Cute – Science Daily"
})
diff --git a/test/conversation/participation_test.exs b/test/conversation/participation_test.exs
index 3536842e8..59a1b6492 100644
--- a/test/conversation/participation_test.exs
+++ b/test/conversation/participation_test.exs
@@ -16,7 +16,7 @@ defmodule Pleroma.Conversation.ParticipationTest do
other_user = insert(:user)
{:ok, _activity} =
- CommonAPI.post(user, %{"status" => "Hey @#{other_user.nickname}.", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "Hey @#{other_user.nickname}.", visibility: "direct"})
[participation] = Participation.for_user(user)
@@ -30,7 +30,7 @@ defmodule Pleroma.Conversation.ParticipationTest do
other_user = insert(:user)
{:ok, _} =
- CommonAPI.post(user, %{"status" => "Hey @#{other_user.nickname}.", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "Hey @#{other_user.nickname}.", visibility: "direct"})
user = User.get_cached_by_id(user.id)
other_user = User.get_cached_by_id(other_user.id)
@@ -43,9 +43,9 @@ defmodule Pleroma.Conversation.ParticipationTest do
{:ok, _} =
CommonAPI.post(other_user, %{
- "status" => "Hey @#{user.nickname}.",
- "visibility" => "direct",
- "in_reply_to_conversation_id" => participation.id
+ status: "Hey @#{user.nickname}.",
+ visibility: "direct",
+ in_reply_to_conversation_id: participation.id
})
user = User.get_cached_by_id(user.id)
@@ -64,7 +64,7 @@ defmodule Pleroma.Conversation.ParticipationTest do
third_user = insert(:user)
{:ok, activity} =
- CommonAPI.post(user, %{"status" => "Hey @#{other_user.nickname}.", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "Hey @#{other_user.nickname}.", visibility: "direct"})
user = User.get_cached_by_id(user.id)
other_user = User.get_cached_by_id(other_user.id)
@@ -79,9 +79,9 @@ defmodule Pleroma.Conversation.ParticipationTest do
{:ok, _activity} =
CommonAPI.post(user, %{
- "in_reply_to_status_id" => activity.id,
- "status" => "Hey @#{third_user.nickname}.",
- "visibility" => "direct"
+ in_reply_to_status_id: activity.id,
+ status: "Hey @#{third_user.nickname}.",
+ visibility: "direct"
})
[participation] = Participation.for_user(user)
@@ -154,14 +154,14 @@ defmodule Pleroma.Conversation.ParticipationTest do
test "gets all the participations for a user, ordered by updated at descending" do
user = insert(:user)
- {:ok, activity_one} = CommonAPI.post(user, %{"status" => "x", "visibility" => "direct"})
- {:ok, activity_two} = CommonAPI.post(user, %{"status" => "x", "visibility" => "direct"})
+ {:ok, activity_one} = CommonAPI.post(user, %{status: "x", visibility: "direct"})
+ {:ok, activity_two} = CommonAPI.post(user, %{status: "x", visibility: "direct"})
{:ok, activity_three} =
CommonAPI.post(user, %{
- "status" => "x",
- "visibility" => "direct",
- "in_reply_to_status_id" => activity_one.id
+ status: "x",
+ visibility: "direct",
+ in_reply_to_status_id: activity_one.id
})
# Offset participations because the accuracy of updated_at is down to a second
@@ -201,7 +201,7 @@ defmodule Pleroma.Conversation.ParticipationTest do
test "Doesn't die when the conversation gets empty" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
+ {:ok, activity} = CommonAPI.post(user, %{status: ".", visibility: "direct"})
[participation] = Participation.for_user_with_last_activity_id(user)
assert participation.last_activity_id == activity.id
@@ -215,7 +215,7 @@ defmodule Pleroma.Conversation.ParticipationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, _activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
+ {:ok, _activity} = CommonAPI.post(user, %{status: ".", visibility: "direct"})
[participation] = Participation.for_user_with_last_activity_id(user)
participation = Repo.preload(participation, :recipients)
@@ -239,26 +239,26 @@ defmodule Pleroma.Conversation.ParticipationTest do
{:ok, _direct1} =
CommonAPI.post(third_user, %{
- "status" => "Hi @#{blocker.nickname}",
- "visibility" => "direct"
+ status: "Hi @#{blocker.nickname}",
+ visibility: "direct"
})
{:ok, _direct2} =
CommonAPI.post(third_user, %{
- "status" => "Hi @#{blocker.nickname}, @#{blocked.nickname}",
- "visibility" => "direct"
+ status: "Hi @#{blocker.nickname}, @#{blocked.nickname}",
+ visibility: "direct"
})
{:ok, _direct3} =
CommonAPI.post(blocked, %{
- "status" => "Hi @#{blocker.nickname}",
- "visibility" => "direct"
+ status: "Hi @#{blocker.nickname}",
+ visibility: "direct"
})
{:ok, _direct4} =
CommonAPI.post(blocked, %{
- "status" => "Hi @#{blocker.nickname}, @#{third_user.nickname}",
- "visibility" => "direct"
+ status: "Hi @#{blocker.nickname}, @#{third_user.nickname}",
+ visibility: "direct"
})
assert [%{read: false}, %{read: false}, %{read: false}, %{read: false}] =
@@ -293,8 +293,8 @@ defmodule Pleroma.Conversation.ParticipationTest do
# When the blocked user is the author
{:ok, _direct1} =
CommonAPI.post(blocked, %{
- "status" => "Hi @#{blocker.nickname}",
- "visibility" => "direct"
+ status: "Hi @#{blocker.nickname}",
+ visibility: "direct"
})
assert [%{read: true}] = Participation.for_user(blocker)
@@ -303,8 +303,8 @@ defmodule Pleroma.Conversation.ParticipationTest do
# When the blocked user is a recipient
{:ok, _direct2} =
CommonAPI.post(third_user, %{
- "status" => "Hi @#{blocker.nickname}, @#{blocked.nickname}",
- "visibility" => "direct"
+ status: "Hi @#{blocker.nickname}, @#{blocked.nickname}",
+ visibility: "direct"
})
assert [%{read: true}, %{read: true}] = Participation.for_user(blocker)
@@ -321,8 +321,8 @@ defmodule Pleroma.Conversation.ParticipationTest do
{:ok, _direct1} =
CommonAPI.post(blocker, %{
- "status" => "Hi @#{third_user.nickname}, @#{blocked.nickname}",
- "visibility" => "direct"
+ status: "Hi @#{third_user.nickname}, @#{blocked.nickname}",
+ visibility: "direct"
})
{:ok, _user_relationship} = User.block(blocker, blocked)
@@ -334,9 +334,9 @@ defmodule Pleroma.Conversation.ParticipationTest do
# When it's a reply from the blocked user
{:ok, _direct2} =
CommonAPI.post(blocked, %{
- "status" => "reply",
- "visibility" => "direct",
- "in_reply_to_conversation_id" => blocked_participation.id
+ status: "reply",
+ visibility: "direct",
+ in_reply_to_conversation_id: blocked_participation.id
})
assert [%{read: true}] = Participation.for_user(blocker)
@@ -347,9 +347,9 @@ defmodule Pleroma.Conversation.ParticipationTest do
# When it's a reply from the third user
{:ok, _direct3} =
CommonAPI.post(third_user, %{
- "status" => "reply",
- "visibility" => "direct",
- "in_reply_to_conversation_id" => third_user_participation.id
+ status: "reply",
+ visibility: "direct",
+ in_reply_to_conversation_id: third_user_participation.id
})
assert [%{read: true}] = Participation.for_user(blocker)
diff --git a/test/conversation_test.exs b/test/conversation_test.exs
index 056a0e920..359aa6840 100644
--- a/test/conversation_test.exs
+++ b/test/conversation_test.exs
@@ -18,7 +18,7 @@ defmodule Pleroma.ConversationTest do
other_user = insert(:user)
{:ok, _activity} =
- CommonAPI.post(user, %{"visibility" => "direct", "status" => "hey @#{other_user.nickname}"})
+ CommonAPI.post(user, %{visibility: "direct", status: "hey @#{other_user.nickname}"})
Pleroma.Tests.ObanHelpers.perform_all()
@@ -46,7 +46,7 @@ defmodule Pleroma.ConversationTest do
test "public posts don't create conversations" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Hey"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "Hey"})
object = Pleroma.Object.normalize(activity)
context = object.data["context"]
@@ -62,7 +62,7 @@ defmodule Pleroma.ConversationTest do
tridi = insert(:user)
{:ok, activity} =
- CommonAPI.post(har, %{"status" => "Hey @#{jafnhar.nickname}", "visibility" => "direct"})
+ CommonAPI.post(har, %{status: "Hey @#{jafnhar.nickname}", visibility: "direct"})
object = Pleroma.Object.normalize(activity)
context = object.data["context"]
@@ -81,9 +81,9 @@ defmodule Pleroma.ConversationTest do
{:ok, activity} =
CommonAPI.post(jafnhar, %{
- "status" => "Hey @#{har.nickname}",
- "visibility" => "direct",
- "in_reply_to_status_id" => activity.id
+ status: "Hey @#{har.nickname}",
+ visibility: "direct",
+ in_reply_to_status_id: activity.id
})
object = Pleroma.Object.normalize(activity)
@@ -105,9 +105,9 @@ defmodule Pleroma.ConversationTest do
{:ok, activity} =
CommonAPI.post(tridi, %{
- "status" => "Hey @#{har.nickname}",
- "visibility" => "direct",
- "in_reply_to_status_id" => activity.id
+ status: "Hey @#{har.nickname}",
+ visibility: "direct",
+ in_reply_to_status_id: activity.id
})
object = Pleroma.Object.normalize(activity)
@@ -149,14 +149,14 @@ defmodule Pleroma.ConversationTest do
jafnhar = insert(:user, local: false)
{:ok, activity} =
- CommonAPI.post(har, %{"status" => "Hey @#{jafnhar.nickname}", "visibility" => "direct"})
+ CommonAPI.post(har, %{status: "Hey @#{jafnhar.nickname}", visibility: "direct"})
{:ok, conversation} = Conversation.create_or_bump_for(activity)
assert length(conversation.participations) == 2
{:ok, activity} =
- CommonAPI.post(har, %{"status" => "Hey @#{jafnhar.nickname}", "visibility" => "public"})
+ CommonAPI.post(har, %{status: "Hey @#{jafnhar.nickname}", visibility: "public"})
assert {:error, _} = Conversation.create_or_bump_for(activity)
end
diff --git a/test/html_test.exs b/test/html_test.exs
index a006fd492..0a4b4ebbc 100644
--- a/test/html_test.exs
+++ b/test/html_test.exs
@@ -171,7 +171,7 @@ defmodule Pleroma.HTMLTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" =>
+ status:
"I think I just found the best github repo https://github.com/komeiji-satori/Dress"
})
@@ -186,7 +186,7 @@ defmodule Pleroma.HTMLTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" =>
+ status:
"@#{other_user.nickname} install misskey! https://github.com/syuilo/misskey/blob/develop/docs/setup.en.md"
})
@@ -203,8 +203,7 @@ defmodule Pleroma.HTMLTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" =>
- "#cofe https://www.pixiv.net/member_illust.php?mode=medium&illust_id=72255140"
+ status: "#cofe https://www.pixiv.net/member_illust.php?mode=medium&illust_id=72255140"
})
object = Object.normalize(activity)
@@ -218,9 +217,9 @@ defmodule Pleroma.HTMLTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" =>
+ status:
"#cofe https://www.pixiv.net/member_illust.php?mode=medium&illust_id=72255140",
- "content_type" => "text/html"
+ content_type: "text/html"
})
object = Object.normalize(activity)
@@ -232,8 +231,7 @@ defmodule Pleroma.HTMLTest do
test "does not crash when there is an HTML entity in a link" do
user = insert(:user)
- {:ok, activity} =
- CommonAPI.post(user, %{"status" => "\"http://cofe.com/?boomer=ok&foo=bar\""})
+ {:ok, activity} = CommonAPI.post(user, %{status: "\"http://cofe.com/?boomer=ok&foo=bar\""})
object = Object.normalize(activity)
diff --git a/test/integration/mastodon_websocket_test.exs b/test/integration/mastodon_websocket_test.exs
index f61150cd2..ea17e9feb 100644
--- a/test/integration/mastodon_websocket_test.exs
+++ b/test/integration/mastodon_websocket_test.exs
@@ -55,7 +55,7 @@ defmodule Pleroma.Integration.MastodonWebsocketTest do
test "receives well formatted events" do
user = insert(:user)
{:ok, _} = start_socket("?stream=public")
- {:ok, activity} = CommonAPI.post(user, %{"status" => "nice echo chamber"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "nice echo chamber"})
assert_receive {:text, raw_json}, 1_000
assert {:ok, json} = Jason.decode(raw_json)
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 4dfbc1019..111ff09f4 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -25,7 +25,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "yeah"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "yeah"})
{:ok, activity} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
{:ok, [notification]} = Notification.create_notifications(activity)
@@ -40,7 +40,7 @@ defmodule Pleroma.NotificationTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "hey @#{other_user.nickname} and @#{third_user.nickname}"
+ status: "hey @#{other_user.nickname} and @#{third_user.nickname}"
})
{:ok, [notification, other_notification]} = Notification.create_notifications(activity)
@@ -60,7 +60,7 @@ defmodule Pleroma.NotificationTest do
User.subscribe(subscriber, user)
- {:ok, status} = CommonAPI.post(user, %{"status" => "Akariiiin"})
+ {:ok, status} = CommonAPI.post(user, %{status: "Akariiiin"})
{:ok, [notification]} = Notification.create_notifications(status)
assert notification.user_id == subscriber.id
@@ -73,12 +73,12 @@ defmodule Pleroma.NotificationTest do
User.subscribe(subscriber, other_user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test post"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test post"})
{:ok, _reply_activity} =
CommonAPI.post(other_user, %{
- "status" => "test reply",
- "in_reply_to_status_id" => activity.id
+ status: "test reply",
+ in_reply_to_status_id: activity.id
})
user_notifications = Notification.for_user(user)
@@ -98,7 +98,7 @@ defmodule Pleroma.NotificationTest do
blocker = insert(:user)
{:ok, _user_relationship} = User.block(blocker, user)
- {:ok, _activity} = CommonAPI.post(user, %{"status" => "hey @#{blocker.nickname}!"})
+ {:ok, _activity} = CommonAPI.post(user, %{status: "hey @#{blocker.nickname}!"})
blocker_id = blocker.id
assert [%Notification{user_id: ^blocker_id}] = Repo.all(Notification)
@@ -113,7 +113,7 @@ defmodule Pleroma.NotificationTest do
muter = insert(:user)
{:ok, _user_relationships} = User.mute(muter, user)
- {:ok, _activity} = CommonAPI.post(user, %{"status" => "hey @#{muter.nickname}!"})
+ {:ok, _activity} = CommonAPI.post(user, %{status: "hey @#{muter.nickname}!"})
muter_id = muter.id
assert [%Notification{user_id: ^muter_id}] = Repo.all(Notification)
@@ -127,14 +127,14 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
thread_muter = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{thread_muter.nickname}!"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{thread_muter.nickname}!"})
{:ok, _} = CommonAPI.add_mute(thread_muter, activity)
{:ok, _same_context_activity} =
CommonAPI.post(user, %{
- "status" => "hey-hey-hey @#{thread_muter.nickname}!",
- "in_reply_to_status_id" => activity.id
+ status: "hey-hey-hey @#{thread_muter.nickname}!",
+ in_reply_to_status_id: activity.id
})
[pre_mute_notification, post_mute_notification] =
@@ -202,7 +202,7 @@ defmodule Pleroma.NotificationTest do
muted = insert(:user)
{:ok, _} = User.mute(muter, muted)
muter = Repo.get(User, muter.id)
- {:ok, activity} = CommonAPI.post(muted, %{"status" => "Hi @#{muter.nickname}"})
+ {:ok, activity} = CommonAPI.post(muted, %{status: "Hi @#{muter.nickname}"})
assert Notification.create_notification(activity, muter)
end
@@ -213,7 +213,7 @@ defmodule Pleroma.NotificationTest do
{:ok, _user_relationships} = User.mute(muter, muted, false)
- {:ok, activity} = CommonAPI.post(muted, %{"status" => "Hi @#{muter.nickname}"})
+ {:ok, activity} = CommonAPI.post(muted, %{status: "Hi @#{muter.nickname}"})
assert Notification.create_notification(activity, muter)
end
@@ -221,13 +221,13 @@ defmodule Pleroma.NotificationTest do
test "it creates a notification for an activity from a muted thread" do
muter = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(muter, %{"status" => "hey"})
+ {:ok, activity} = CommonAPI.post(muter, %{status: "hey"})
CommonAPI.add_mute(muter, activity)
{:ok, activity} =
CommonAPI.post(other_user, %{
- "status" => "Hi @#{muter.nickname}",
- "in_reply_to_status_id" => activity.id
+ status: "Hi @#{muter.nickname}",
+ in_reply_to_status_id: activity.id
})
assert Notification.create_notification(activity, muter)
@@ -240,7 +240,7 @@ defmodule Pleroma.NotificationTest do
insert(:user, notification_settings: %Pleroma.User.NotificationSetting{followers: false})
User.follow(follower, followed)
- {:ok, activity} = CommonAPI.post(follower, %{"status" => "hey @#{followed.nickname}"})
+ {:ok, activity} = CommonAPI.post(follower, %{status: "hey @#{followed.nickname}"})
refute Notification.create_notification(activity, followed)
end
@@ -252,7 +252,7 @@ defmodule Pleroma.NotificationTest do
notification_settings: %Pleroma.User.NotificationSetting{non_followers: false}
)
- {:ok, activity} = CommonAPI.post(follower, %{"status" => "hey @#{followed.nickname}"})
+ {:ok, activity} = CommonAPI.post(follower, %{status: "hey @#{followed.nickname}"})
refute Notification.create_notification(activity, followed)
end
@@ -263,7 +263,7 @@ defmodule Pleroma.NotificationTest do
followed = insert(:user)
User.follow(follower, followed)
follower = Repo.get(User, follower.id)
- {:ok, activity} = CommonAPI.post(followed, %{"status" => "hey @#{follower.nickname}"})
+ {:ok, activity} = CommonAPI.post(followed, %{status: "hey @#{follower.nickname}"})
refute Notification.create_notification(activity, follower)
end
@@ -272,7 +272,7 @@ defmodule Pleroma.NotificationTest do
insert(:user, notification_settings: %Pleroma.User.NotificationSetting{non_follows: false})
followed = insert(:user)
- {:ok, activity} = CommonAPI.post(followed, %{"status" => "hey @#{follower.nickname}"})
+ {:ok, activity} = CommonAPI.post(followed, %{status: "hey @#{follower.nickname}"})
refute Notification.create_notification(activity, follower)
end
@@ -289,7 +289,7 @@ defmodule Pleroma.NotificationTest do
{:ok, _, _, _} = CommonAPI.follow(subscriber, user)
User.subscribe(subscriber, user)
- {:ok, status} = CommonAPI.post(user, %{"status" => "Akariiiin"})
+ {:ok, status} = CommonAPI.post(user, %{status: "Akariiiin"})
{:ok, [_notif]} = Notification.create_notifications(status)
end
@@ -299,7 +299,7 @@ defmodule Pleroma.NotificationTest do
User.subscribe(subscriber, user)
- {:ok, status} = CommonAPI.post(user, %{"status" => "inwisible", "visibility" => "direct"})
+ {:ok, status} = CommonAPI.post(user, %{status: "inwisible", visibility: "direct"})
assert {:ok, []} == Notification.create_notifications(status)
end
@@ -370,7 +370,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{other_user.nickname}"})
{:ok, [notification]} = Notification.create_notifications(activity)
{:ok, notification} = Notification.get(other_user, notification.id)
@@ -382,7 +382,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{other_user.nickname}"})
{:ok, [notification]} = Notification.create_notifications(activity)
{:error, _notification} = Notification.get(user, notification.id)
@@ -394,7 +394,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{other_user.nickname}"})
{:ok, [notification]} = Notification.create_notifications(activity)
{:ok, notification} = Notification.dismiss(other_user, notification.id)
@@ -406,7 +406,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{other_user.nickname}"})
{:ok, [notification]} = Notification.create_notifications(activity)
{:error, _notification} = Notification.dismiss(user, notification.id)
@@ -421,14 +421,14 @@ defmodule Pleroma.NotificationTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "hey @#{other_user.nickname} and @#{third_user.nickname} !"
+ status: "hey @#{other_user.nickname} and @#{third_user.nickname} !"
})
{:ok, _notifs} = Notification.create_notifications(activity)
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "hey again @#{other_user.nickname} and @#{third_user.nickname} !"
+ status: "hey again @#{other_user.nickname} and @#{third_user.nickname} !"
})
{:ok, _notifs} = Notification.create_notifications(activity)
@@ -446,12 +446,12 @@ defmodule Pleroma.NotificationTest do
{:ok, _activity} =
CommonAPI.post(user, %{
- "status" => "hey @#{other_user.nickname}!"
+ status: "hey @#{other_user.nickname}!"
})
{:ok, _activity} =
CommonAPI.post(user, %{
- "status" => "hey again @#{other_user.nickname}!"
+ status: "hey again @#{other_user.nickname}!"
})
[n2, n1] = notifs = Notification.for_user(other_user)
@@ -461,7 +461,7 @@ defmodule Pleroma.NotificationTest do
{:ok, _activity} =
CommonAPI.post(user, %{
- "status" => "hey yet again @#{other_user.nickname}!"
+ status: "hey yet again @#{other_user.nickname}!"
})
Notification.set_read_up_to(other_user, n2.id)
@@ -500,7 +500,7 @@ defmodule Pleroma.NotificationTest do
Enum.each(0..10, fn i ->
{:ok, _activity} =
CommonAPI.post(user1, %{
- "status" => "hey ##{i} @#{user2.nickname}!"
+ status: "hey ##{i} @#{user2.nickname}!"
})
end)
@@ -536,7 +536,7 @@ defmodule Pleroma.NotificationTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "hey @#{other_user.nickname}!"
+ status: "hey @#{other_user.nickname}!"
})
{enabled_receivers, _disabled_receivers} = Notification.get_notified_from_activity(activity)
@@ -605,7 +605,7 @@ defmodule Pleroma.NotificationTest do
{:ok, activity_one} =
CommonAPI.post(user, %{
- "status" => "hey @#{other_user.nickname}!"
+ status: "hey @#{other_user.nickname}!"
})
{:ok, activity_two} = CommonAPI.favorite(third_user, activity_one.id)
@@ -623,7 +623,7 @@ defmodule Pleroma.NotificationTest do
{:ok, activity_one} =
CommonAPI.post(user, %{
- "status" => "hey @#{other_user.nickname}!"
+ status: "hey @#{other_user.nickname}!"
})
{:ok, like_data, _} = Builder.like(third_user, activity_one.object)
@@ -645,7 +645,7 @@ defmodule Pleroma.NotificationTest do
{:ok, activity_one} =
CommonAPI.post(user, %{
- "status" => "hey @#{other_user.nickname}!"
+ status: "hey @#{other_user.nickname}!"
})
{:ok, activity_two, _} = CommonAPI.repeat(activity_one.id, third_user)
@@ -661,7 +661,7 @@ defmodule Pleroma.NotificationTest do
other_user = insert(:user)
{:ok, _user_relationship} = User.block(other_user, user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{other_user.nickname}!"})
{enabled_receivers, disabled_receivers} = Notification.get_notified_from_activity(activity)
@@ -674,7 +674,7 @@ defmodule Pleroma.NotificationTest do
other_user = insert(:user)
{:ok, _user_relationships} = User.mute(other_user, user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{other_user.nickname}!"})
{enabled_receivers, disabled_receivers} = Notification.get_notified_from_activity(activity)
@@ -686,14 +686,14 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{other_user.nickname}!"})
{:ok, _} = CommonAPI.add_mute(other_user, activity)
{:ok, same_context_activity} =
CommonAPI.post(user, %{
- "status" => "hey-hey-hey @#{other_user.nickname}!",
- "in_reply_to_status_id" => activity.id
+ status: "hey-hey-hey @#{other_user.nickname}!",
+ in_reply_to_status_id: activity.id
})
{enabled_receivers, disabled_receivers} =
@@ -710,7 +710,7 @@ defmodule Pleroma.NotificationTest do
{:ok, other_user} = User.block_domain(other_user, blocked_domain)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{other_user.nickname}!"})
{enabled_receivers, disabled_receivers} = Notification.get_notified_from_activity(activity)
@@ -726,7 +726,7 @@ defmodule Pleroma.NotificationTest do
{:ok, other_user} = User.block_domain(other_user, blocked_domain)
{:ok, other_user} = User.follow(other_user, user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{other_user.nickname}!"})
{enabled_receivers, disabled_receivers} = Notification.get_notified_from_activity(activity)
@@ -740,7 +740,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test post"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test post"})
assert Enum.empty?(Notification.for_user(user))
@@ -757,7 +757,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test post"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test post"})
assert Enum.empty?(Notification.for_user(user))
@@ -774,7 +774,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test post"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test post"})
assert Enum.empty?(Notification.for_user(user))
@@ -791,7 +791,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test post"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test post"})
assert Enum.empty?(Notification.for_user(user))
@@ -808,7 +808,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test post"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test post"})
assert Enum.empty?(Notification.for_user(user))
@@ -825,7 +825,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test post"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test post"})
assert Enum.empty?(Notification.for_user(user))
@@ -842,13 +842,13 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test post"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test post"})
{:ok, _deletion_activity} = CommonAPI.delete(activity.id, user)
{:ok, _reply_activity} =
CommonAPI.post(other_user, %{
- "status" => "test reply",
- "in_reply_to_status_id" => activity.id
+ status: "test reply",
+ in_reply_to_status_id: activity.id
})
assert Enum.empty?(Notification.for_user(user))
@@ -859,7 +859,7 @@ defmodule Pleroma.NotificationTest do
other_user = insert(:user)
{:ok, _activity} =
- CommonAPI.post(user, %{"status" => "hi @#{other_user.nickname}", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "hi @#{other_user.nickname}", visibility: "direct"})
refute Enum.empty?(Notification.for_user(other_user))
@@ -970,7 +970,7 @@ defmodule Pleroma.NotificationTest do
muted = insert(:user)
{:ok, _user_relationships} = User.mute(user, muted, false)
- {:ok, _activity} = CommonAPI.post(muted, %{"status" => "hey @#{user.nickname}"})
+ {:ok, _activity} = CommonAPI.post(muted, %{status: "hey @#{user.nickname}"})
assert length(Notification.for_user(user)) == 1
end
@@ -980,7 +980,7 @@ defmodule Pleroma.NotificationTest do
muted = insert(:user)
{:ok, _user_relationships} = User.mute(user, muted)
- {:ok, _activity} = CommonAPI.post(muted, %{"status" => "hey @#{user.nickname}"})
+ {:ok, _activity} = CommonAPI.post(muted, %{status: "hey @#{user.nickname}"})
assert Notification.for_user(user) == []
end
@@ -990,7 +990,7 @@ defmodule Pleroma.NotificationTest do
blocked = insert(:user)
{:ok, _user_relationship} = User.block(user, blocked)
- {:ok, _activity} = CommonAPI.post(blocked, %{"status" => "hey @#{user.nickname}"})
+ {:ok, _activity} = CommonAPI.post(blocked, %{status: "hey @#{user.nickname}"})
assert Notification.for_user(user) == []
end
@@ -1000,7 +1000,7 @@ defmodule Pleroma.NotificationTest do
blocked = insert(:user, ap_id: "http://some-domain.com")
{:ok, user} = User.block_domain(user, "some-domain.com")
- {:ok, _activity} = CommonAPI.post(blocked, %{"status" => "hey @#{user.nickname}"})
+ {:ok, _activity} = CommonAPI.post(blocked, %{status: "hey @#{user.nickname}"})
assert Notification.for_user(user) == []
end
@@ -1012,7 +1012,7 @@ defmodule Pleroma.NotificationTest do
{:ok, user} = User.block_domain(user, "some-domain.com")
{:ok, _} = User.follow(user, blocked)
- {:ok, _activity} = CommonAPI.post(blocked, %{"status" => "hey @#{user.nickname}"})
+ {:ok, _activity} = CommonAPI.post(blocked, %{status: "hey @#{user.nickname}"})
assert length(Notification.for_user(user)) == 1
end
@@ -1021,7 +1021,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
another_user = insert(:user)
- {:ok, activity} = CommonAPI.post(another_user, %{"status" => "hey @#{user.nickname}"})
+ {:ok, activity} = CommonAPI.post(another_user, %{status: "hey @#{user.nickname}"})
{:ok, _} = Pleroma.ThreadMute.add_mute(user.id, activity.data["context"])
assert Notification.for_user(user) == []
@@ -1032,7 +1032,7 @@ defmodule Pleroma.NotificationTest do
muted = insert(:user)
{:ok, _user_relationships} = User.mute(user, muted)
- {:ok, _activity} = CommonAPI.post(muted, %{"status" => "hey @#{user.nickname}"})
+ {:ok, _activity} = CommonAPI.post(muted, %{status: "hey @#{user.nickname}"})
assert length(Notification.for_user(user, %{with_muted: true})) == 1
end
@@ -1042,7 +1042,7 @@ defmodule Pleroma.NotificationTest do
blocked = insert(:user)
{:ok, _user_relationship} = User.block(user, blocked)
- {:ok, _activity} = CommonAPI.post(blocked, %{"status" => "hey @#{user.nickname}"})
+ {:ok, _activity} = CommonAPI.post(blocked, %{status: "hey @#{user.nickname}"})
assert Enum.empty?(Notification.for_user(user, %{with_muted: true}))
end
@@ -1053,7 +1053,7 @@ defmodule Pleroma.NotificationTest do
blocked = insert(:user, ap_id: "http://some-domain.com")
{:ok, user} = User.block_domain(user, "some-domain.com")
- {:ok, _activity} = CommonAPI.post(blocked, %{"status" => "hey @#{user.nickname}"})
+ {:ok, _activity} = CommonAPI.post(blocked, %{status: "hey @#{user.nickname}"})
assert Enum.empty?(Notification.for_user(user, %{with_muted: true}))
end
@@ -1062,7 +1062,7 @@ defmodule Pleroma.NotificationTest do
user = insert(:user)
another_user = insert(:user)
- {:ok, activity} = CommonAPI.post(another_user, %{"status" => "hey @#{user.nickname}"})
+ {:ok, activity} = CommonAPI.post(another_user, %{status: "hey @#{user.nickname}"})
{:ok, _} = Pleroma.ThreadMute.add_mute(user.id, activity.data["context"])
assert length(Notification.for_user(user, %{with_muted: true})) == 1
diff --git a/test/stats_test.exs b/test/stats_test.exs
index c1aeb2c7f..4b76e2e78 100644
--- a/test/stats_test.exs
+++ b/test/stats_test.exs
@@ -22,26 +22,26 @@ defmodule Pleroma.StatsTest do
user = insert(:user)
other_user = insert(:user)
- CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
+ CommonAPI.post(user, %{visibility: "public", status: "hey"})
Enum.each(0..1, fn _ ->
CommonAPI.post(user, %{
- "visibility" => "unlisted",
- "status" => "hey"
+ visibility: "unlisted",
+ status: "hey"
})
end)
Enum.each(0..2, fn _ ->
CommonAPI.post(user, %{
- "visibility" => "direct",
- "status" => "hey @#{other_user.nickname}"
+ visibility: "direct",
+ status: "hey @#{other_user.nickname}"
})
end)
Enum.each(0..3, fn _ ->
CommonAPI.post(user, %{
- "visibility" => "private",
- "status" => "hey"
+ visibility: "private",
+ status: "hey"
})
end)
@@ -51,7 +51,7 @@ defmodule Pleroma.StatsTest do
test "on status delete" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
+ {:ok, activity} = CommonAPI.post(user, %{visibility: "public", status: "hey"})
assert %{public: 1} = Pleroma.Stats.get_status_visibility_count()
CommonAPI.delete(activity.id, user)
assert %{public: 0} = Pleroma.Stats.get_status_visibility_count()
@@ -59,16 +59,16 @@ defmodule Pleroma.StatsTest do
test "on status visibility update" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
+ {:ok, activity} = CommonAPI.post(user, %{visibility: "public", status: "hey"})
assert %{public: 1, private: 0} = Pleroma.Stats.get_status_visibility_count()
- {:ok, _} = CommonAPI.update_activity_scope(activity.id, %{"visibility" => "private"})
+ {:ok, _} = CommonAPI.update_activity_scope(activity.id, %{visibility: "private"})
assert %{public: 0, private: 1} = Pleroma.Stats.get_status_visibility_count()
end
test "doesn't count unrelated activities" do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
+ {:ok, activity} = CommonAPI.post(user, %{visibility: "public", status: "hey"})
_ = CommonAPI.follow(user, other_user)
CommonAPI.favorite(other_user, activity.id)
CommonAPI.repeat(activity.id, other_user)
diff --git a/test/tasks/count_statuses_test.exs b/test/tasks/count_statuses_test.exs
index 73c2ea690..c5cd16960 100644
--- a/test/tasks/count_statuses_test.exs
+++ b/test/tasks/count_statuses_test.exs
@@ -13,11 +13,11 @@ defmodule Mix.Tasks.Pleroma.CountStatusesTest do
test "counts statuses" do
user = insert(:user)
- {:ok, _} = CommonAPI.post(user, %{"status" => "test"})
- {:ok, _} = CommonAPI.post(user, %{"status" => "test2"})
+ {:ok, _} = CommonAPI.post(user, %{status: "test"})
+ {:ok, _} = CommonAPI.post(user, %{status: "test2"})
user2 = insert(:user)
- {:ok, _} = CommonAPI.post(user2, %{"status" => "test3"})
+ {:ok, _} = CommonAPI.post(user2, %{status: "test3"})
user = refresh_record(user)
user2 = refresh_record(user2)
diff --git a/test/tasks/database_test.exs b/test/tasks/database_test.exs
index 7b05993d3..883828d77 100644
--- a/test/tasks/database_test.exs
+++ b/test/tasks/database_test.exs
@@ -26,7 +26,7 @@ defmodule Mix.Tasks.Pleroma.DatabaseTest do
describe "running remove_embedded_objects" do
test "it replaces objects with references" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test"})
new_data = Map.put(activity.data, "object", activity.object.data)
{:ok, activity} =
@@ -99,8 +99,8 @@ defmodule Mix.Tasks.Pleroma.DatabaseTest do
test "it turns OrderedCollection likes into empty arrays" do
[user, user2] = insert_pair(:user)
- {:ok, %{id: id, object: object}} = CommonAPI.post(user, %{"status" => "test"})
- {:ok, %{object: object2}} = CommonAPI.post(user, %{"status" => "test test"})
+ {:ok, %{id: id, object: object}} = CommonAPI.post(user, %{status: "test"})
+ {:ok, %{object: object2}} = CommonAPI.post(user, %{status: "test test"})
CommonAPI.favorite(user2, id)
diff --git a/test/tasks/digest_test.exs b/test/tasks/digest_test.exs
index 96d762685..eefbc8936 100644
--- a/test/tasks/digest_test.exs
+++ b/test/tasks/digest_test.exs
@@ -25,7 +25,7 @@ defmodule Mix.Tasks.Pleroma.DigestTest do
Enum.each(0..10, fn i ->
{:ok, _activity} =
CommonAPI.post(user1, %{
- "status" => "hey ##{i} @#{user2.nickname}!"
+ status: "hey ##{i} @#{user2.nickname}!"
})
end)
diff --git a/test/tasks/refresh_counter_cache_test.exs b/test/tasks/refresh_counter_cache_test.exs
index b63f44c08..851971a77 100644
--- a/test/tasks/refresh_counter_cache_test.exs
+++ b/test/tasks/refresh_counter_cache_test.exs
@@ -12,26 +12,26 @@ defmodule Mix.Tasks.Pleroma.RefreshCounterCacheTest do
user = insert(:user)
other_user = insert(:user)
- CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
+ CommonAPI.post(user, %{visibility: "public", status: "hey"})
Enum.each(0..1, fn _ ->
CommonAPI.post(user, %{
- "visibility" => "unlisted",
- "status" => "hey"
+ visibility: "unlisted",
+ status: "hey"
})
end)
Enum.each(0..2, fn _ ->
CommonAPI.post(user, %{
- "visibility" => "direct",
- "status" => "hey @#{other_user.nickname}"
+ visibility: "direct",
+ status: "hey @#{other_user.nickname}"
})
end)
Enum.each(0..3, fn _ ->
CommonAPI.post(user, %{
- "visibility" => "private",
- "status" => "hey"
+ visibility: "private",
+ status: "hey"
})
end)
diff --git a/test/tasks/user_test.exs b/test/tasks/user_test.exs
index b4f68d494..4aa873f0b 100644
--- a/test/tasks/user_test.exs
+++ b/test/tasks/user_test.exs
@@ -109,7 +109,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do
test "a remote user's create activity is deleted when the object has been pruned" do
user = insert(:user)
- {:ok, post} = CommonAPI.post(user, %{"status" => "uguu"})
+ {:ok, post} = CommonAPI.post(user, %{status: "uguu"})
object = Object.normalize(post)
Object.prune(object)
diff --git a/test/user_test.exs b/test/user_test.exs
index a3c75aa9b..6b9df60a4 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -990,7 +990,7 @@ defmodule Pleroma.UserTest do
actor = insert(:user)
user = insert(:user, local: true)
- {:ok, activity} = CommonAPI.post(actor, %{"status" => "hello"})
+ {:ok, activity} = CommonAPI.post(actor, %{status: "hello"})
{:ok, announce, _} = CommonAPI.repeat(activity.id, user)
recipients = User.get_recipients_from_activity(announce)
@@ -1007,7 +1007,7 @@ defmodule Pleroma.UserTest do
{:ok, activity} =
CommonAPI.post(actor, %{
- "status" => "hey @#{addressed.nickname} @#{addressed_remote.nickname}"
+ status: "hey @#{addressed.nickname} @#{addressed_remote.nickname}"
})
assert Enum.map([actor, addressed], & &1.ap_id) --
@@ -1029,7 +1029,7 @@ defmodule Pleroma.UserTest do
{:ok, activity} =
CommonAPI.post(actor, %{
- "status" => "hey @#{addressed.nickname}"
+ status: "hey @#{addressed.nickname}"
})
assert Enum.map([actor, addressed], & &1.ap_id) --
@@ -1090,7 +1090,7 @@ defmodule Pleroma.UserTest do
{:ok, user2} = User.follow(user2, user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{user2.nickname}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{user2.nickname}"})
activity = Repo.preload(activity, :bookmark)
@@ -1126,7 +1126,7 @@ defmodule Pleroma.UserTest do
setup do: clear_config([:instance, :federating])
test ".delete_user_activities deletes all create activities", %{user: user} do
- {:ok, activity} = CommonAPI.post(user, %{"status" => "2hu"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "2hu"})
User.delete_user_activities(user)
@@ -1411,7 +1411,7 @@ defmodule Pleroma.UserTest do
{:ok, _} =
CommonAPI.post(user, %{
- "status" => "hey @#{to.nickname}"
+ status: "hey @#{to.nickname}"
})
end)
@@ -1443,12 +1443,12 @@ defmodule Pleroma.UserTest do
Enum.each(recipients, fn to ->
{:ok, _} =
CommonAPI.post(sender, %{
- "status" => "hey @#{to.nickname}"
+ status: "hey @#{to.nickname}"
})
{:ok, _} =
CommonAPI.post(sender, %{
- "status" => "hey again @#{to.nickname}"
+ status: "hey again @#{to.nickname}"
})
end)
diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs
index 776ddc8d4..c432c90e3 100644
--- a/test/web/activity_pub/activity_pub_controller_test.exs
+++ b/test/web/activity_pub/activity_pub_controller_test.exs
@@ -341,7 +341,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
test "cached purged after activity deletion", %{conn: conn} do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "cofe"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "cofe"})
uuid = String.split(activity.data["id"], "/") |> List.last()
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 59bdd53cd..56fde97e7 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -32,7 +32,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
describe "streaming out participations" do
test "it streams them out" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
+ {:ok, activity} = CommonAPI.post(user, %{status: ".", visibility: "direct"})
{:ok, conversation} = Pleroma.Conversation.create_or_bump_for(activity)
@@ -56,8 +56,8 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
stream: fn _, _ -> nil end do
{:ok, activity} =
CommonAPI.post(user_one, %{
- "status" => "@#{user_two.nickname}",
- "visibility" => "direct"
+ status: "@#{user_two.nickname}",
+ visibility: "direct"
})
conversation =
@@ -74,15 +74,13 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
test "it restricts by the appropriate visibility" do
user = insert(:user)
- {:ok, public_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "public"})
+ {:ok, public_activity} = CommonAPI.post(user, %{status: ".", visibility: "public"})
- {:ok, direct_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
+ {:ok, direct_activity} = CommonAPI.post(user, %{status: ".", visibility: "direct"})
- {:ok, unlisted_activity} =
- CommonAPI.post(user, %{"status" => ".", "visibility" => "unlisted"})
+ {:ok, unlisted_activity} = CommonAPI.post(user, %{status: ".", visibility: "unlisted"})
- {:ok, private_activity} =
- CommonAPI.post(user, %{"status" => ".", "visibility" => "private"})
+ {:ok, private_activity} = CommonAPI.post(user, %{status: ".", visibility: "private"})
activities =
ActivityPub.fetch_activities([], %{:visibility => "direct", "actor_id" => user.ap_id})
@@ -118,15 +116,13 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
test "it excludes by the appropriate visibility" do
user = insert(:user)
- {:ok, public_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "public"})
+ {:ok, public_activity} = CommonAPI.post(user, %{status: ".", visibility: "public"})
- {:ok, direct_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
+ {:ok, direct_activity} = CommonAPI.post(user, %{status: ".", visibility: "direct"})
- {:ok, unlisted_activity} =
- CommonAPI.post(user, %{"status" => ".", "visibility" => "unlisted"})
+ {:ok, unlisted_activity} = CommonAPI.post(user, %{status: ".", visibility: "unlisted"})
- {:ok, private_activity} =
- CommonAPI.post(user, %{"status" => ".", "visibility" => "private"})
+ {:ok, private_activity} = CommonAPI.post(user, %{status: ".", visibility: "private"})
activities =
ActivityPub.fetch_activities([], %{
@@ -193,9 +189,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
test "it fetches the appropriate tag-restricted posts" do
user = insert(:user)
- {:ok, status_one} = CommonAPI.post(user, %{"status" => ". #test"})
- {:ok, status_two} = CommonAPI.post(user, %{"status" => ". #essais"})
- {:ok, status_three} = CommonAPI.post(user, %{"status" => ". #test #reject"})
+ {:ok, status_one} = CommonAPI.post(user, %{status: ". #test"})
+ {:ok, status_two} = CommonAPI.post(user, %{status: ". #essais"})
+ {:ok, status_three} = CommonAPI.post(user, %{status: ". #test #reject"})
fetch_one = ActivityPub.fetch_activities([], %{"type" => "Create", "tag" => "test"})
@@ -432,26 +428,26 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, _} =
CommonAPI.post(User.get_cached_by_id(user.id), %{
- "status" => "1",
- "visibility" => "public"
+ status: "1",
+ visibility: "public"
})
{:ok, _} =
CommonAPI.post(User.get_cached_by_id(user.id), %{
- "status" => "2",
- "visibility" => "unlisted"
+ status: "2",
+ visibility: "unlisted"
})
{:ok, _} =
CommonAPI.post(User.get_cached_by_id(user.id), %{
- "status" => "2",
- "visibility" => "private"
+ status: "2",
+ visibility: "private"
})
{:ok, _} =
CommonAPI.post(User.get_cached_by_id(user.id), %{
- "status" => "3",
- "visibility" => "direct"
+ status: "3",
+ visibility: "direct"
})
user = User.get_cached_by_id(user.id)
@@ -462,27 +458,27 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
user = insert(:user)
user2 = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "1", "visibility" => "public"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "1", visibility: "public"})
ap_id = activity.data["id"]
- reply_data = %{"status" => "1", "in_reply_to_status_id" => activity.id}
+ reply_data = %{status: "1", in_reply_to_status_id: activity.id}
# public
- {:ok, _} = CommonAPI.post(user2, Map.put(reply_data, "visibility", "public"))
+ {:ok, _} = CommonAPI.post(user2, Map.put(reply_data, :visibility, "public"))
assert %{data: data, object: object} = Activity.get_by_ap_id_with_object(ap_id)
assert object.data["repliesCount"] == 1
# unlisted
- {:ok, _} = CommonAPI.post(user2, Map.put(reply_data, "visibility", "unlisted"))
+ {:ok, _} = CommonAPI.post(user2, Map.put(reply_data, :visibility, "unlisted"))
assert %{data: data, object: object} = Activity.get_by_ap_id_with_object(ap_id)
assert object.data["repliesCount"] == 2
# private
- {:ok, _} = CommonAPI.post(user2, Map.put(reply_data, "visibility", "private"))
+ {:ok, _} = CommonAPI.post(user2, Map.put(reply_data, :visibility, "private"))
assert %{data: data, object: object} = Activity.get_by_ap_id_with_object(ap_id)
assert object.data["repliesCount"] == 2
# direct
- {:ok, _} = CommonAPI.post(user2, Map.put(reply_data, "visibility", "direct"))
+ {:ok, _} = CommonAPI.post(user2, Map.put(reply_data, :visibility, "direct"))
assert %{data: data, object: object} = Activity.get_by_ap_id_with_object(ap_id)
assert object.data["repliesCount"] == 2
end
@@ -569,13 +565,13 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, _user_relationship} = User.block(blocker, blockee)
- {:ok, activity_one} = CommonAPI.post(friend, %{"status" => "hey!"})
+ {:ok, activity_one} = CommonAPI.post(friend, %{status: "hey!"})
- {:ok, activity_two} = CommonAPI.post(friend, %{"status" => "hey! @#{blockee.nickname}"})
+ {:ok, activity_two} = CommonAPI.post(friend, %{status: "hey! @#{blockee.nickname}"})
- {:ok, activity_three} = CommonAPI.post(blockee, %{"status" => "hey! @#{friend.nickname}"})
+ {:ok, activity_three} = CommonAPI.post(blockee, %{status: "hey! @#{friend.nickname}"})
- {:ok, activity_four} = CommonAPI.post(blockee, %{"status" => "hey! @#{blocker.nickname}"})
+ {:ok, activity_four} = CommonAPI.post(blockee, %{status: "hey! @#{blocker.nickname}"})
activities = ActivityPub.fetch_activities([], %{"blocking_user" => blocker})
@@ -592,9 +588,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, _user_relationship} = User.block(blocker, blockee)
- {:ok, activity_one} = CommonAPI.post(friend, %{"status" => "hey!"})
+ {:ok, activity_one} = CommonAPI.post(friend, %{status: "hey!"})
- {:ok, activity_two} = CommonAPI.post(blockee, %{"status" => "hey! @#{friend.nickname}"})
+ {:ok, activity_two} = CommonAPI.post(blockee, %{status: "hey! @#{friend.nickname}"})
{:ok, activity_three, _} = CommonAPI.repeat(activity_two.id, friend)
@@ -774,10 +770,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
test "doesn't retrieve unlisted activities" do
user = insert(:user)
- {:ok, _unlisted_activity} =
- CommonAPI.post(user, %{"status" => "yeah", "visibility" => "unlisted"})
+ {:ok, _unlisted_activity} = CommonAPI.post(user, %{status: "yeah", visibility: "unlisted"})
- {:ok, listed_activity} = CommonAPI.post(user, %{"status" => "yeah"})
+ {:ok, listed_activity} = CommonAPI.post(user, %{status: "yeah"})
[activity] = ActivityPub.fetch_public_activities()
@@ -912,7 +907,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
describe "announcing a private object" do
test "adds an announce activity to the db if the audience is not widened" do
user = insert(:user)
- {:ok, note_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "private"})
+ {:ok, note_activity} = CommonAPI.post(user, %{status: ".", visibility: "private"})
object = Object.normalize(note_activity)
{:ok, announce_activity, object} = ActivityPub.announce(user, object, nil, true, false)
@@ -926,7 +921,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
test "does not add an announce activity to the db if the audience is widened" do
user = insert(:user)
- {:ok, note_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "private"})
+ {:ok, note_activity} = CommonAPI.post(user, %{status: ".", visibility: "private"})
object = Object.normalize(note_activity)
assert {:error, _} = ActivityPub.announce(user, object, nil, true, true)
@@ -935,7 +930,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
test "does not add an announce activity to the db if the announcer is not the author" do
user = insert(:user)
announcer = insert(:user)
- {:ok, note_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "private"})
+ {:ok, note_activity} = CommonAPI.post(user, %{status: ".", visibility: "private"})
object = Object.normalize(note_activity)
assert {:error, _} = ActivityPub.announce(announcer, object, nil, true, false)
@@ -1111,23 +1106,22 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, user3} = User.follow(user3, user2)
assert User.following?(user3, user2)
- {:ok, public_activity} = CommonAPI.post(user3, %{"status" => "hi 1"})
+ {:ok, public_activity} = CommonAPI.post(user3, %{status: "hi 1"})
- {:ok, private_activity_1} =
- CommonAPI.post(user3, %{"status" => "hi 2", "visibility" => "private"})
+ {:ok, private_activity_1} = CommonAPI.post(user3, %{status: "hi 2", visibility: "private"})
{:ok, private_activity_2} =
CommonAPI.post(user2, %{
- "status" => "hi 3",
- "visibility" => "private",
- "in_reply_to_status_id" => private_activity_1.id
+ status: "hi 3",
+ visibility: "private",
+ in_reply_to_status_id: private_activity_1.id
})
{:ok, private_activity_3} =
CommonAPI.post(user3, %{
- "status" => "hi 4",
- "visibility" => "private",
- "in_reply_to_status_id" => private_activity_2.id
+ status: "hi 4",
+ visibility: "private",
+ in_reply_to_status_id: private_activity_2.id
})
activities =
@@ -1177,9 +1171,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
Config.put([:instance, :max_pinned_statuses], 3)
user = insert(:user)
- {:ok, activity_one} = CommonAPI.post(user, %{"status" => "HI!!!"})
- {:ok, activity_two} = CommonAPI.post(user, %{"status" => "HI!!!"})
- {:ok, activity_three} = CommonAPI.post(user, %{"status" => "HI!!!"})
+ {:ok, activity_one} = CommonAPI.post(user, %{status: "HI!!!"})
+ {:ok, activity_two} = CommonAPI.post(user, %{status: "HI!!!"})
+ {:ok, activity_three} = CommonAPI.post(user, %{status: "HI!!!"})
CommonAPI.pin(activity_one.id, user)
user = refresh_record(user)
@@ -1200,7 +1194,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
reporter = insert(:user)
target_account = insert(:user)
content = "foobar"
- {:ok, activity} = CommonAPI.post(target_account, %{"status" => content})
+ {:ok, activity} = CommonAPI.post(target_account, %{status: content})
context = Utils.generate_context_id()
reporter_ap_id = reporter.ap_id
@@ -1296,8 +1290,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, list} = Pleroma.List.create("foo", user)
{:ok, list} = Pleroma.List.follow(list, member)
- {:ok, activity} =
- CommonAPI.post(user, %{"status" => "foobar", "visibility" => "list:#{list.id}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "foobar", visibility: "list:#{list.id}"})
activity = Repo.preload(activity, :bookmark)
activity = %Activity{activity | thread_muted?: !!activity.thread_muted?}
@@ -1315,8 +1308,8 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "thought I looked cute might delete later :3",
- "visibility" => "private"
+ status: "thought I looked cute might delete later :3",
+ visibility: "private"
})
[result] = ActivityPub.fetch_activities_bounded([user.follower_address], [])
@@ -1325,12 +1318,12 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
test "fetches only public posts for other users" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe", "visibility" => "public"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "#cofe", visibility: "public"})
{:ok, _private_activity} =
CommonAPI.post(user, %{
- "status" => "why is tenshi eating a corndog so cute?",
- "visibility" => "private"
+ status: "why is tenshi eating a corndog so cute?",
+ visibility: "private"
})
[result] = ActivityPub.fetch_activities_bounded([], [user.follower_address])
@@ -1458,11 +1451,11 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
other_user = insert(:user)
user1 = insert(:user)
user2 = insert(:user)
- {:ok, a1} = CommonAPI.post(user1, %{"status" => "bla"})
- {:ok, _a2} = CommonAPI.post(user2, %{"status" => "traps are happy"})
- {:ok, a3} = CommonAPI.post(user2, %{"status" => "Trees Are "})
- {:ok, a4} = CommonAPI.post(user2, %{"status" => "Agent Smith "})
- {:ok, a5} = CommonAPI.post(user1, %{"status" => "Red or Blue "})
+ {:ok, a1} = CommonAPI.post(user1, %{status: "bla"})
+ {:ok, _a2} = CommonAPI.post(user2, %{status: "traps are happy"})
+ {:ok, a3} = CommonAPI.post(user2, %{status: "Trees Are "})
+ {:ok, a4} = CommonAPI.post(user2, %{status: "Agent Smith "})
+ {:ok, a5} = CommonAPI.post(user1, %{status: "Red or Blue "})
{:ok, _} = CommonAPI.favorite(user, a4.id)
{:ok, _} = CommonAPI.favorite(other_user, a3.id)
@@ -1542,10 +1535,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
test "doesn't retrieve replies activities with exclude_replies" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "yeah"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "yeah"})
- {:ok, _reply} =
- CommonAPI.post(user, %{"status" => "yeah", "in_reply_to_status_id" => activity.id})
+ {:ok, _reply} = CommonAPI.post(user, %{status: "yeah", in_reply_to_status_id: activity.id})
[result] = ActivityPub.fetch_public_activities(%{"exclude_replies" => "true"})
@@ -1858,84 +1850,84 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, u2} = User.follow(u2, u3)
{:ok, u3} = User.follow(u3, u2)
- {:ok, a1} = CommonAPI.post(u1, %{"status" => "Status"})
+ {:ok, a1} = CommonAPI.post(u1, %{status: "Status"})
{:ok, r1_1} =
CommonAPI.post(u2, %{
- "status" => "@#{u1.nickname} reply from u2 to u1",
- "in_reply_to_status_id" => a1.id
+ status: "@#{u1.nickname} reply from u2 to u1",
+ in_reply_to_status_id: a1.id
})
{:ok, r1_2} =
CommonAPI.post(u3, %{
- "status" => "@#{u1.nickname} reply from u3 to u1",
- "in_reply_to_status_id" => a1.id
+ status: "@#{u1.nickname} reply from u3 to u1",
+ in_reply_to_status_id: a1.id
})
{:ok, r1_3} =
CommonAPI.post(u4, %{
- "status" => "@#{u1.nickname} reply from u4 to u1",
- "in_reply_to_status_id" => a1.id
+ status: "@#{u1.nickname} reply from u4 to u1",
+ in_reply_to_status_id: a1.id
})
- {:ok, a2} = CommonAPI.post(u2, %{"status" => "Status"})
+ {:ok, a2} = CommonAPI.post(u2, %{status: "Status"})
{:ok, r2_1} =
CommonAPI.post(u1, %{
- "status" => "@#{u2.nickname} reply from u1 to u2",
- "in_reply_to_status_id" => a2.id
+ status: "@#{u2.nickname} reply from u1 to u2",
+ in_reply_to_status_id: a2.id
})
{:ok, r2_2} =
CommonAPI.post(u3, %{
- "status" => "@#{u2.nickname} reply from u3 to u2",
- "in_reply_to_status_id" => a2.id
+ status: "@#{u2.nickname} reply from u3 to u2",
+ in_reply_to_status_id: a2.id
})
{:ok, r2_3} =
CommonAPI.post(u4, %{
- "status" => "@#{u2.nickname} reply from u4 to u2",
- "in_reply_to_status_id" => a2.id
+ status: "@#{u2.nickname} reply from u4 to u2",
+ in_reply_to_status_id: a2.id
})
- {:ok, a3} = CommonAPI.post(u3, %{"status" => "Status"})
+ {:ok, a3} = CommonAPI.post(u3, %{status: "Status"})
{:ok, r3_1} =
CommonAPI.post(u1, %{
- "status" => "@#{u3.nickname} reply from u1 to u3",
- "in_reply_to_status_id" => a3.id
+ status: "@#{u3.nickname} reply from u1 to u3",
+ in_reply_to_status_id: a3.id
})
{:ok, r3_2} =
CommonAPI.post(u2, %{
- "status" => "@#{u3.nickname} reply from u2 to u3",
- "in_reply_to_status_id" => a3.id
+ status: "@#{u3.nickname} reply from u2 to u3",
+ in_reply_to_status_id: a3.id
})
{:ok, r3_3} =
CommonAPI.post(u4, %{
- "status" => "@#{u3.nickname} reply from u4 to u3",
- "in_reply_to_status_id" => a3.id
+ status: "@#{u3.nickname} reply from u4 to u3",
+ in_reply_to_status_id: a3.id
})
- {:ok, a4} = CommonAPI.post(u4, %{"status" => "Status"})
+ {:ok, a4} = CommonAPI.post(u4, %{status: "Status"})
{:ok, r4_1} =
CommonAPI.post(u1, %{
- "status" => "@#{u4.nickname} reply from u1 to u4",
- "in_reply_to_status_id" => a4.id
+ status: "@#{u4.nickname} reply from u1 to u4",
+ in_reply_to_status_id: a4.id
})
{:ok, r4_2} =
CommonAPI.post(u2, %{
- "status" => "@#{u4.nickname} reply from u2 to u4",
- "in_reply_to_status_id" => a4.id
+ status: "@#{u4.nickname} reply from u2 to u4",
+ in_reply_to_status_id: a4.id
})
{:ok, r4_3} =
CommonAPI.post(u3, %{
- "status" => "@#{u4.nickname} reply from u3 to u4",
- "in_reply_to_status_id" => a4.id
+ status: "@#{u4.nickname} reply from u3 to u4",
+ in_reply_to_status_id: a4.id
})
{:ok,
@@ -1959,68 +1951,68 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, u2} = User.follow(u2, u3)
{:ok, u3} = User.follow(u3, u2)
- {:ok, a1} = CommonAPI.post(u1, %{"status" => "Status", "visibility" => "private"})
+ {:ok, a1} = CommonAPI.post(u1, %{status: "Status", visibility: "private"})
{:ok, r1_1} =
CommonAPI.post(u2, %{
- "status" => "@#{u1.nickname} reply from u2 to u1",
- "in_reply_to_status_id" => a1.id,
- "visibility" => "private"
+ status: "@#{u1.nickname} reply from u2 to u1",
+ in_reply_to_status_id: a1.id,
+ visibility: "private"
})
{:ok, r1_2} =
CommonAPI.post(u3, %{
- "status" => "@#{u1.nickname} reply from u3 to u1",
- "in_reply_to_status_id" => a1.id,
- "visibility" => "private"
+ status: "@#{u1.nickname} reply from u3 to u1",
+ in_reply_to_status_id: a1.id,
+ visibility: "private"
})
{:ok, r1_3} =
CommonAPI.post(u4, %{
- "status" => "@#{u1.nickname} reply from u4 to u1",
- "in_reply_to_status_id" => a1.id,
- "visibility" => "private"
+ status: "@#{u1.nickname} reply from u4 to u1",
+ in_reply_to_status_id: a1.id,
+ visibility: "private"
})
- {:ok, a2} = CommonAPI.post(u2, %{"status" => "Status", "visibility" => "private"})
+ {:ok, a2} = CommonAPI.post(u2, %{status: "Status", visibility: "private"})
{:ok, r2_1} =
CommonAPI.post(u1, %{
- "status" => "@#{u2.nickname} reply from u1 to u2",
- "in_reply_to_status_id" => a2.id,
- "visibility" => "private"
+ status: "@#{u2.nickname} reply from u1 to u2",
+ in_reply_to_status_id: a2.id,
+ visibility: "private"
})
{:ok, r2_2} =
CommonAPI.post(u3, %{
- "status" => "@#{u2.nickname} reply from u3 to u2",
- "in_reply_to_status_id" => a2.id,
- "visibility" => "private"
+ status: "@#{u2.nickname} reply from u3 to u2",
+ in_reply_to_status_id: a2.id,
+ visibility: "private"
})
- {:ok, a3} = CommonAPI.post(u3, %{"status" => "Status", "visibility" => "private"})
+ {:ok, a3} = CommonAPI.post(u3, %{status: "Status", visibility: "private"})
{:ok, r3_1} =
CommonAPI.post(u1, %{
- "status" => "@#{u3.nickname} reply from u1 to u3",
- "in_reply_to_status_id" => a3.id,
- "visibility" => "private"
+ status: "@#{u3.nickname} reply from u1 to u3",
+ in_reply_to_status_id: a3.id,
+ visibility: "private"
})
{:ok, r3_2} =
CommonAPI.post(u2, %{
- "status" => "@#{u3.nickname} reply from u2 to u3",
- "in_reply_to_status_id" => a3.id,
- "visibility" => "private"
+ status: "@#{u3.nickname} reply from u2 to u3",
+ in_reply_to_status_id: a3.id,
+ visibility: "private"
})
- {:ok, a4} = CommonAPI.post(u4, %{"status" => "Status", "visibility" => "private"})
+ {:ok, a4} = CommonAPI.post(u4, %{status: "Status", visibility: "private"})
{:ok, r4_1} =
CommonAPI.post(u1, %{
- "status" => "@#{u4.nickname} reply from u1 to u4",
- "in_reply_to_status_id" => a4.id,
- "visibility" => "private"
+ status: "@#{u4.nickname} reply from u1 to u4",
+ in_reply_to_status_id: a4.id,
+ visibility: "private"
})
{:ok,
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index f382adf3e..96eff1c30 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -13,7 +13,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
describe "EmojiReacts" do
setup do
user = insert(:user)
- {:ok, post_activity} = CommonAPI.post(user, %{"status" => "uguu"})
+ {:ok, post_activity} = CommonAPI.post(user, %{status: "uguu"})
object = Pleroma.Object.get_by_ap_id(post_activity.data["object"])
@@ -53,7 +53,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
describe "Undos" do
setup do
user = insert(:user)
- {:ok, post_activity} = CommonAPI.post(user, %{"status" => "uguu"})
+ {:ok, post_activity} = CommonAPI.post(user, %{status: "uguu"})
{:ok, like} = CommonAPI.favorite(user, post_activity.id)
{:ok, valid_like_undo, []} = Builder.undo(user, like)
@@ -93,7 +93,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
describe "deletes" do
setup do
user = insert(:user)
- {:ok, post_activity} = CommonAPI.post(user, %{"status" => "cancel me daddy"})
+ {:ok, post_activity} = CommonAPI.post(user, %{status: "cancel me daddy"})
{:ok, valid_post_delete, _} = Builder.delete(user, post_activity.data["object"])
{:ok, valid_user_delete, _} = Builder.delete(user, user.ap_id)
@@ -185,7 +185,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
describe "likes" do
setup do
user = insert(:user)
- {:ok, post_activity} = CommonAPI.post(user, %{"status" => "uguu"})
+ {:ok, post_activity} = CommonAPI.post(user, %{status: "uguu"})
valid_like = %{
"to" => [user.ap_id],
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index 6c5f8fc61..797f00d08 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -25,8 +25,8 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, op} = CommonAPI.post(other_user, %{"status" => "big oof"})
- {:ok, post} = CommonAPI.post(user, %{"status" => "hey", "in_reply_to_id" => op})
+ {:ok, op} = CommonAPI.post(other_user, %{status: "big oof"})
+ {:ok, post} = CommonAPI.post(user, %{status: "hey", in_reply_to_id: op})
{:ok, favorite} = CommonAPI.favorite(user, post.id)
object = Object.normalize(post)
{:ok, delete_data, _meta} = Builder.delete(user, object.data["id"])
@@ -118,7 +118,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
poster = insert(:user)
user = insert(:user)
- {:ok, post} = CommonAPI.post(poster, %{"status" => "hey"})
+ {:ok, post} = CommonAPI.post(poster, %{status: "hey"})
{:ok, emoji_react_data, []} = Builder.emoji_react(user, post.object, "👌")
{:ok, emoji_react, _meta} = ActivityPub.persist(emoji_react_data, local: true)
@@ -144,7 +144,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
setup do
poster = insert(:user)
user = insert(:user)
- {:ok, post} = CommonAPI.post(poster, %{"status" => "hey"})
+ {:ok, post} = CommonAPI.post(poster, %{status: "hey"})
{:ok, like} = CommonAPI.favorite(user, post.id)
{:ok, reaction} = CommonAPI.react_with_emoji(post.id, user, "👍")
{:ok, announce, _} = CommonAPI.repeat(post.id, user)
@@ -244,7 +244,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
setup do
poster = insert(:user)
user = insert(:user)
- {:ok, post} = CommonAPI.post(poster, %{"status" => "hey"})
+ {:ok, post} = CommonAPI.post(poster, %{status: "hey"})
{:ok, like_data, _meta} = Builder.like(user, post.object)
{:ok, like, _meta} = ActivityPub.persist(like_data, local: true)
diff --git a/test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs b/test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs
index 6988e3e0a..0fb056b50 100644
--- a/test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/emoji_react_handling_test.exs
@@ -15,7 +15,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.EmojiReactHandlingTest do
test "it works for incoming emoji reactions" do
user = insert(:user)
other_user = insert(:user, local: false)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hello"})
data =
File.read!("test/fixtures/emoji-reaction.json")
@@ -40,7 +40,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.EmojiReactHandlingTest do
test "it reject invalid emoji reactions" do
user = insert(:user)
other_user = insert(:user, local: false)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hello"})
data =
File.read!("test/fixtures/emoji-reaction-too-long.json")
diff --git a/test/web/activity_pub/transmogrifier/like_handling_test.exs b/test/web/activity_pub/transmogrifier/like_handling_test.exs
index 54a5c1dbc..53fe1d550 100644
--- a/test/web/activity_pub/transmogrifier/like_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/like_handling_test.exs
@@ -14,7 +14,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.LikeHandlingTest do
test "it works for incoming likes" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hello"})
data =
File.read!("test/fixtures/mastodon-like.json")
@@ -36,7 +36,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.LikeHandlingTest do
test "it works for incoming misskey likes, turning them into EmojiReacts" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hello"})
data =
File.read!("test/fixtures/misskey-like.json")
@@ -57,7 +57,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.LikeHandlingTest do
test "it works for incoming misskey likes that contain unicode emojis, turning them into EmojiReacts" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hello"})
data =
File.read!("test/fixtures/misskey-like.json")
diff --git a/test/web/activity_pub/transmogrifier/undo_handling_test.exs b/test/web/activity_pub/transmogrifier/undo_handling_test.exs
index eaf58adf7..01dd6c370 100644
--- a/test/web/activity_pub/transmogrifier/undo_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/undo_handling_test.exs
@@ -16,7 +16,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do
test "it works for incoming emoji reaction undos" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hello"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hello"})
{:ok, reaction_activity} = CommonAPI.react_with_emoji(activity.id, user, "👌")
data =
@@ -34,7 +34,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do
test "it returns an error for incoming unlikes wihout a like activity" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "leave a like pls"})
data =
File.read!("test/fixtures/mastodon-undo-like.json")
@@ -46,7 +46,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do
test "it works for incoming unlikes with an existing like activity" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "leave a like pls"})
like_data =
File.read!("test/fixtures/mastodon-like.json")
@@ -77,7 +77,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do
test "it works for incoming unlikes with an existing like activity and a compact object" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "leave a like pls"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "leave a like pls"})
like_data =
File.read!("test/fixtures/mastodon-like.json")
@@ -104,7 +104,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do
test "it works for incoming unannounces with an existing notice" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey"})
announce_data =
File.read!("test/fixtures/mastodon-announce.json")
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 3f908f867..0a54e3bb9 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -212,8 +212,8 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "suya...",
- "poll" => %{"options" => ["suya", "suya.", "suya.."], "expires_in" => 10}
+ status: "suya...",
+ poll: %{options: ["suya", "suya.", "suya.."], expires_in: 10}
})
object = Object.normalize(activity)
@@ -263,7 +263,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "it works for incoming honk announces" do
_user = insert(:user, ap_id: "https://honktest/u/test", local: false)
other_user = insert(:user)
- {:ok, post} = CommonAPI.post(other_user, %{"status" => "bonkeronk"})
+ {:ok, post} = CommonAPI.post(other_user, %{status: "bonkeronk"})
announce = %{
"@context" => "https://www.w3.org/ns/activitystreams",
@@ -362,7 +362,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "it works for incoming announces with an existing activity" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey"})
data =
File.read!("test/fixtures/mastodon-announce.json")
@@ -412,7 +412,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "it does not clobber the addressing on announce activities" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey"})
data =
File.read!("test/fixtures/mastodon-announce.json")
@@ -498,7 +498,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "it strips internal reactions" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
{:ok, _} = CommonAPI.react_with_emoji(activity.id, user, "📢")
%{object: object} = Activity.get_by_id_with_object(activity.id)
@@ -996,7 +996,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test post"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test post"})
object = Object.normalize(activity)
note_obj = %{
@@ -1140,13 +1140,13 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
setup do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "post1"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "post1"})
{:ok, reply1} =
- CommonAPI.post(user, %{"status" => "reply1", "in_reply_to_status_id" => activity.id})
+ CommonAPI.post(user, %{status: "reply1", in_reply_to_status_id: activity.id})
{:ok, reply2} =
- CommonAPI.post(user, %{"status" => "reply2", "in_reply_to_status_id" => activity.id})
+ CommonAPI.post(user, %{status: "reply2", in_reply_to_status_id: activity.id})
replies_uris = Enum.map([reply1, reply2], fn a -> a.object.data["id"] end)
@@ -1186,7 +1186,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "it inlines private announced objects" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey", "visibility" => "private"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey", visibility: "private"})
{:ok, announce_activity, _} = CommonAPI.repeat(activity.id, user)
@@ -1201,7 +1201,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
other_user = insert(:user)
{:ok, activity} =
- CommonAPI.post(user, %{"status" => "hey, @#{other_user.nickname}, how are ya? #2hu"})
+ CommonAPI.post(user, %{status: "hey, @#{other_user.nickname}, how are ya? #2hu"})
{:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
object = modified["object"]
@@ -1225,7 +1225,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "it adds the sensitive property" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "#nsfw hey"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "#nsfw hey"})
{:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
assert modified["object"]["sensitive"]
@@ -1234,7 +1234,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "it adds the json-ld context and the conversation property" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey"})
{:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
assert modified["@context"] ==
@@ -1246,7 +1246,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "it sets the 'attributedTo' property to the actor of the object if it doesn't have one" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey"})
{:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
assert modified["object"]["actor"] == modified["object"]["attributedTo"]
@@ -1255,7 +1255,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "it strips internal hashtag data" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "#2hu"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "#2hu"})
expected_tag = %{
"href" => Pleroma.Web.Endpoint.url() <> "/tags/2hu",
@@ -1271,7 +1271,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "it strips internal fields" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "#2hu :firefox:"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "#2hu :firefox:"})
{:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
@@ -1303,14 +1303,13 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "2hu :moominmamma:"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "2hu :moominmamma:"})
{:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
assert modified["directMessage"] == false
- {:ok, activity} =
- CommonAPI.post(user, %{"status" => "@#{other_user.nickname} :moominmamma:"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "@#{other_user.nickname} :moominmamma:"})
{:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
@@ -1318,8 +1317,8 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "@#{other_user.nickname} :moominmamma:",
- "visibility" => "direct"
+ status: "@#{other_user.nickname} :moominmamma:",
+ visibility: "direct"
})
{:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
@@ -1331,8 +1330,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
user = insert(:user)
{:ok, list} = Pleroma.List.create("foo", user)
- {:ok, activity} =
- CommonAPI.post(user, %{"status" => "foobar", "visibility" => "list:#{list.id}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "foobar", visibility: "list:#{list.id}"})
{:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
@@ -1367,8 +1365,8 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
user_two = insert(:user)
Pleroma.FollowingRelationship.follow(user_two, user, :follow_accept)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test"})
- {:ok, unrelated_activity} = CommonAPI.post(user_two, %{"status" => "test"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test"})
+ {:ok, unrelated_activity} = CommonAPI.post(user_two, %{status: "test"})
assert "http://localhost:4001/users/rye@niu.moe/followers" in activity.recipients
user = User.get_cached_by_id(user.id)
@@ -1534,8 +1532,8 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
{:ok, poll_activity} =
CommonAPI.post(user, %{
- "status" => "suya...",
- "poll" => %{"options" => ["suya", "suya.", "suya.."], "expires_in" => 10}
+ status: "suya...",
+ poll: %{options: ["suya", "suya.", "suya.."], expires_in: 10}
})
poll_object = Object.normalize(poll_activity)
@@ -1878,28 +1876,27 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
test "sets `replies` collection with a limited number of self-replies" do
[user, another_user] = insert_list(2, :user)
- {:ok, %{id: id1} = activity} = CommonAPI.post(user, %{"status" => "1"})
+ {:ok, %{id: id1} = activity} = CommonAPI.post(user, %{status: "1"})
{:ok, %{id: id2} = self_reply1} =
- CommonAPI.post(user, %{"status" => "self-reply 1", "in_reply_to_status_id" => id1})
+ CommonAPI.post(user, %{status: "self-reply 1", in_reply_to_status_id: id1})
{:ok, self_reply2} =
- CommonAPI.post(user, %{"status" => "self-reply 2", "in_reply_to_status_id" => id1})
+ CommonAPI.post(user, %{status: "self-reply 2", in_reply_to_status_id: id1})
# Assuming to _not_ be present in `replies` due to :note_replies_output_limit is set to 2
- {:ok, _} =
- CommonAPI.post(user, %{"status" => "self-reply 3", "in_reply_to_status_id" => id1})
+ {:ok, _} = CommonAPI.post(user, %{status: "self-reply 3", in_reply_to_status_id: id1})
{:ok, _} =
CommonAPI.post(user, %{
- "status" => "self-reply to self-reply",
- "in_reply_to_status_id" => id2
+ status: "self-reply to self-reply",
+ in_reply_to_status_id: id2
})
{:ok, _} =
CommonAPI.post(another_user, %{
- "status" => "another user's reply",
- "in_reply_to_status_id" => id1
+ status: "another user's reply",
+ in_reply_to_status_id: id1
})
object = Object.normalize(activity)
diff --git a/test/web/activity_pub/utils_test.exs b/test/web/activity_pub/utils_test.exs
index b8d811c73..9e0a0f1c4 100644
--- a/test/web/activity_pub/utils_test.exs
+++ b/test/web/activity_pub/utils_test.exs
@@ -120,7 +120,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" =>
+ status:
"hey @#{other_user.nickname}, @#{third_user.nickname} how about beering together this weekend?"
})
@@ -139,8 +139,8 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "@#{other_user.nickname} @#{third_user.nickname} bought a new swimsuit!",
- "visibility" => "private"
+ status: "@#{other_user.nickname} @#{third_user.nickname} bought a new swimsuit!",
+ visibility: "private"
})
%{"to" => to, "cc" => cc} = Utils.make_like_data(other_user, activity, nil)
@@ -168,11 +168,11 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "How do I pronounce LaTeX?",
- "poll" => %{
- "options" => ["laytekh", "lahtekh", "latex"],
- "expires_in" => 20,
- "multiple" => true
+ status: "How do I pronounce LaTeX?",
+ poll: %{
+ options: ["laytekh", "lahtekh", "latex"],
+ expires_in: 20,
+ multiple: true
}
})
@@ -187,10 +187,10 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "Are we living in a society?",
- "poll" => %{
- "options" => ["yes", "no"],
- "expires_in" => 20
+ status: "Are we living in a society?",
+ poll: %{
+ options: ["yes", "no"],
+ expires_in: 20
}
})
@@ -469,7 +469,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do
test "returns map with Flag object" do
reporter = insert(:user)
target_account = insert(:user)
- {:ok, activity} = CommonAPI.post(target_account, %{"status" => "foobar"})
+ {:ok, activity} = CommonAPI.post(target_account, %{status: "foobar"})
context = Utils.generate_context_id()
content = "foobar"
diff --git a/test/web/activity_pub/views/object_view_test.exs b/test/web/activity_pub/views/object_view_test.exs
index 6c006206b..43f0617f0 100644
--- a/test/web/activity_pub/views/object_view_test.exs
+++ b/test/web/activity_pub/views/object_view_test.exs
@@ -44,7 +44,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectViewTest do
activity = insert(:note_activity, user: user)
{:ok, self_reply1} =
- CommonAPI.post(user, %{"status" => "self-reply 1", "in_reply_to_status_id" => activity.id})
+ CommonAPI.post(user, %{status: "self-reply 1", in_reply_to_status_id: activity.id})
replies_uris = [self_reply1.object.data["id"]]
result = ObjectView.render("object.json", %{object: refresh_record(activity)})
diff --git a/test/web/activity_pub/views/user_view_test.exs b/test/web/activity_pub/views/user_view_test.exs
index 8d00893a5..20b0f223c 100644
--- a/test/web/activity_pub/views/user_view_test.exs
+++ b/test/web/activity_pub/views/user_view_test.exs
@@ -164,7 +164,7 @@ defmodule Pleroma.Web.ActivityPub.UserViewTest do
posts =
for i <- 0..25 do
- {:ok, activity} = CommonAPI.post(user, %{"status" => "post #{i}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "post #{i}"})
activity
end
diff --git a/test/web/activity_pub/visibilty_test.exs b/test/web/activity_pub/visibilty_test.exs
index 5b91630d4..8e9354c65 100644
--- a/test/web/activity_pub/visibilty_test.exs
+++ b/test/web/activity_pub/visibilty_test.exs
@@ -21,21 +21,21 @@ defmodule Pleroma.Web.ActivityPub.VisibilityTest do
Pleroma.List.follow(list, unrelated)
{:ok, public} =
- CommonAPI.post(user, %{"status" => "@#{mentioned.nickname}", "visibility" => "public"})
+ CommonAPI.post(user, %{status: "@#{mentioned.nickname}", visibility: "public"})
{:ok, private} =
- CommonAPI.post(user, %{"status" => "@#{mentioned.nickname}", "visibility" => "private"})
+ CommonAPI.post(user, %{status: "@#{mentioned.nickname}", visibility: "private"})
{:ok, direct} =
- CommonAPI.post(user, %{"status" => "@#{mentioned.nickname}", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "@#{mentioned.nickname}", visibility: "direct"})
{:ok, unlisted} =
- CommonAPI.post(user, %{"status" => "@#{mentioned.nickname}", "visibility" => "unlisted"})
+ CommonAPI.post(user, %{status: "@#{mentioned.nickname}", visibility: "unlisted"})
{:ok, list} =
CommonAPI.post(user, %{
- "status" => "@#{mentioned.nickname}",
- "visibility" => "list:#{list.id}"
+ status: "@#{mentioned.nickname}",
+ visibility: "list:#{list.id}"
})
%{
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 4697af50e..ecf5465be 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -1747,7 +1747,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
test "change visibility flag", %{conn: conn, id: id, admin: admin} do
response =
conn
- |> put("/api/pleroma/admin/statuses/#{id}", %{"visibility" => "public"})
+ |> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "public"})
|> json_response(:ok)
assert response["visibility"] == "public"
@@ -1759,21 +1759,21 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
response =
conn
- |> put("/api/pleroma/admin/statuses/#{id}", %{"visibility" => "private"})
+ |> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "private"})
|> json_response(:ok)
assert response["visibility"] == "private"
response =
conn
- |> put("/api/pleroma/admin/statuses/#{id}", %{"visibility" => "unlisted"})
+ |> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "unlisted"})
|> json_response(:ok)
assert response["visibility"] == "unlisted"
end
test "returns 400 when visibility is unknown", %{conn: conn, id: id} do
- conn = put(conn, "/api/pleroma/admin/statuses/#{id}", %{"visibility" => "test"})
+ conn = put(conn, "/api/pleroma/admin/statuses/#{id}", %{visibility: "test"})
assert json_response(conn, :bad_request) == "Unsupported visibility"
end
@@ -2977,13 +2977,12 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
user = insert(:user)
User.block(admin, blocked)
- {:ok, _} =
- CommonAPI.post(user, %{"status" => "@#{admin.nickname}", "visibility" => "direct"})
+ {:ok, _} = CommonAPI.post(user, %{status: "@#{admin.nickname}", visibility: "direct"})
- {:ok, _} = CommonAPI.post(user, %{"status" => ".", "visibility" => "unlisted"})
- {:ok, _} = CommonAPI.post(user, %{"status" => ".", "visibility" => "private"})
- {:ok, _} = CommonAPI.post(user, %{"status" => ".", "visibility" => "public"})
- {:ok, _} = CommonAPI.post(blocked, %{"status" => ".", "visibility" => "public"})
+ {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "unlisted"})
+ {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "private"})
+ {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "public"})
+ {:ok, _} = CommonAPI.post(blocked, %{status: ".", visibility: "public"})
response =
conn
@@ -3011,11 +3010,10 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
test "returns private and direct statuses with godmode on", %{conn: conn, admin: admin} do
user = insert(:user)
- {:ok, _} =
- CommonAPI.post(user, %{"status" => "@#{admin.nickname}", "visibility" => "direct"})
+ {:ok, _} = CommonAPI.post(user, %{status: "@#{admin.nickname}", visibility: "direct"})
- {:ok, _} = CommonAPI.post(user, %{"status" => ".", "visibility" => "private"})
- {:ok, _} = CommonAPI.post(user, %{"status" => ".", "visibility" => "public"})
+ {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "private"})
+ {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "public"})
conn = get(conn, "/api/pleroma/admin/statuses?godmode=true")
assert json_response(conn, 200) |> length() == 3
end
@@ -3049,11 +3047,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
test "doesn't return private statuses by default", %{conn: conn, user: user} do
- {:ok, _private_status} =
- CommonAPI.post(user, %{"status" => "private", "visibility" => "private"})
+ {:ok, _private_status} = CommonAPI.post(user, %{status: "private", visibility: "private"})
- {:ok, _public_status} =
- CommonAPI.post(user, %{"status" => "public", "visibility" => "public"})
+ {:ok, _public_status} = CommonAPI.post(user, %{status: "public", visibility: "public"})
conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses")
@@ -3061,11 +3057,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
test "returns private statuses with godmode on", %{conn: conn, user: user} do
- {:ok, _private_status} =
- CommonAPI.post(user, %{"status" => "private", "visibility" => "private"})
+ {:ok, _private_status} = CommonAPI.post(user, %{status: "private", visibility: "private"})
- {:ok, _public_status} =
- CommonAPI.post(user, %{"status" => "public", "visibility" => "public"})
+ {:ok, _public_status} = CommonAPI.post(user, %{status: "public", visibility: "public"})
conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses?godmode=true")
@@ -3074,7 +3068,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
test "excludes reblogs by default", %{conn: conn, user: user} do
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "."})
+ {:ok, activity} = CommonAPI.post(user, %{status: "."})
{:ok, %Activity{}, _} = CommonAPI.repeat(activity.id, other_user)
conn_res = get(conn, "/api/pleroma/admin/users/#{other_user.nickname}/statuses")
@@ -3599,9 +3593,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
test "status visibility count", %{conn: conn} do
admin = insert(:user, is_admin: true)
user = insert(:user)
- CommonAPI.post(user, %{"visibility" => "public", "status" => "hey"})
- CommonAPI.post(user, %{"visibility" => "unlisted", "status" => "hey"})
- CommonAPI.post(user, %{"visibility" => "unlisted", "status" => "hey"})
+ CommonAPI.post(user, %{visibility: "public", status: "hey"})
+ CommonAPI.post(user, %{visibility: "unlisted", status: "hey"})
+ CommonAPI.post(user, %{visibility: "unlisted", status: "hey"})
response =
conn
diff --git a/test/web/admin_api/views/report_view_test.exs b/test/web/admin_api/views/report_view_test.exs
index 8cfa1dcfa..f00b0afb2 100644
--- a/test/web/admin_api/views/report_view_test.exs
+++ b/test/web/admin_api/views/report_view_test.exs
@@ -45,7 +45,7 @@ defmodule Pleroma.Web.AdminAPI.ReportViewTest do
test "includes reported statuses" do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "toot"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "toot"})
{:ok, report_activity} =
CommonAPI.report(user, %{account_id: other_user.id, status_ids: [activity.id]})
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index c524d1c0c..26e41c313 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -27,7 +27,7 @@ defmodule Pleroma.Web.CommonAPITest do
test "it works with pruned objects" do
user = insert(:user)
- {:ok, post} = CommonAPI.post(user, %{"status" => "namu amida butsu"})
+ {:ok, post} = CommonAPI.post(user, %{status: "namu amida butsu"})
Object.normalize(post, false)
|> Object.prune()
@@ -45,7 +45,7 @@ defmodule Pleroma.Web.CommonAPITest do
test "it allows users to delete their posts" do
user = insert(:user)
- {:ok, post} = CommonAPI.post(user, %{"status" => "namu amida butsu"})
+ {:ok, post} = CommonAPI.post(user, %{status: "namu amida butsu"})
with_mock Pleroma.Web.Federator,
publish: fn _ -> nil end do
@@ -61,7 +61,7 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
other_user = insert(:user)
- {:ok, post} = CommonAPI.post(user, %{"status" => "namu amida butsu"})
+ {:ok, post} = CommonAPI.post(user, %{status: "namu amida butsu"})
assert {:error, "Could not delete"} = CommonAPI.delete(post.id, other_user)
assert Activity.get_by_id(post.id)
@@ -71,7 +71,7 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
moderator = insert(:user, is_moderator: true)
- {:ok, post} = CommonAPI.post(user, %{"status" => "namu amida butsu"})
+ {:ok, post} = CommonAPI.post(user, %{status: "namu amida butsu"})
assert {:ok, delete} = CommonAPI.delete(post.id, moderator)
assert delete.local
@@ -83,7 +83,7 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
moderator = insert(:user, is_admin: true)
- {:ok, post} = CommonAPI.post(user, %{"status" => "namu amida butsu"})
+ {:ok, post} = CommonAPI.post(user, %{status: "namu amida butsu"})
assert {:ok, delete} = CommonAPI.delete(post.id, moderator)
assert delete.local
@@ -124,7 +124,7 @@ defmodule Pleroma.Web.CommonAPITest do
users_serial = insert_list(10, :user)
users = insert_list(10, :user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "."})
+ {:ok, activity} = CommonAPI.post(user, %{status: "."})
users_serial
|> Enum.map(fn user ->
@@ -151,7 +151,7 @@ defmodule Pleroma.Web.CommonAPITest do
users_serial = insert_list(10, :user)
users = insert_list(10, :user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "."})
+ {:ok, activity} = CommonAPI.post(user, %{status: "."})
users_serial
|> Enum.map(fn user ->
@@ -175,12 +175,12 @@ defmodule Pleroma.Web.CommonAPITest do
test "when replying to a conversation / participation, it will set the correct context id even if no explicit reply_to is given" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
+ {:ok, activity} = CommonAPI.post(user, %{status: ".", visibility: "direct"})
[participation] = Participation.for_user(user)
{:ok, convo_reply} =
- CommonAPI.post(user, %{"status" => ".", "in_reply_to_conversation_id" => participation.id})
+ CommonAPI.post(user, %{status: ".", in_reply_to_conversation_id: participation.id})
assert Visibility.is_direct?(convo_reply)
@@ -194,8 +194,8 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} =
CommonAPI.post(har, %{
- "status" => "@#{jafnhar.nickname} hey",
- "visibility" => "direct"
+ status: "@#{jafnhar.nickname} hey",
+ visibility: "direct"
})
assert har.ap_id in activity.recipients
@@ -205,10 +205,10 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} =
CommonAPI.post(har, %{
- "status" => "I don't really like @#{tridi.nickname}",
- "visibility" => "direct",
- "in_reply_to_status_id" => activity.id,
- "in_reply_to_conversation_id" => participation.id
+ status: "I don't really like @#{tridi.nickname}",
+ visibility: "direct",
+ in_reply_to_status_id: activity.id,
+ in_reply_to_conversation_id: participation.id
})
assert har.ap_id in activity.recipients
@@ -225,8 +225,8 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} =
CommonAPI.post(har, %{
- "status" => "@#{jafnhar.nickname} hey, i never want to see @#{tridi.nickname} again",
- "visibility" => "direct"
+ status: "@#{jafnhar.nickname} hey, i never want to see @#{tridi.nickname} again",
+ visibility: "direct"
})
refute tridi.ap_id in activity.recipients
@@ -235,7 +235,7 @@ defmodule Pleroma.Web.CommonAPITest do
test "it de-duplicates tags" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "#2hu #2HU"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "#2hu #2HU"})
object = Object.normalize(activity)
@@ -244,7 +244,7 @@ defmodule Pleroma.Web.CommonAPITest do
test "it adds emoji in the object" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => ":firefox:"})
+ {:ok, activity} = CommonAPI.post(user, %{status: ":firefox:"})
assert Object.normalize(activity).data["emoji"]["firefox"]
end
@@ -258,9 +258,9 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" =>
+ status:
"Hey, I think @#{user_three.nickname} is ugly. @#{user_four.nickname} is alright though.",
- "to" => [user_two.nickname, user_four.nickname, "nonexistent"]
+ to: [user_two.nickname, user_four.nickname, "nonexistent"]
})
assert user.ap_id in activity.recipients
@@ -276,8 +276,8 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => post,
- "content_type" => "text/html"
+ status: post,
+ content_type: "text/html"
})
object = Object.normalize(activity)
@@ -292,8 +292,8 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => post,
- "content_type" => "text/markdown"
+ status: post,
+ content_type: "text/markdown"
})
object = Object.normalize(activity)
@@ -304,21 +304,21 @@ defmodule Pleroma.Web.CommonAPITest do
test "it does not allow replies to direct messages that are not direct messages themselves" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "suya..", "visibility" => "direct"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "suya..", visibility: "direct"})
assert {:ok, _} =
CommonAPI.post(user, %{
- "status" => "suya..",
- "visibility" => "direct",
- "in_reply_to_status_id" => activity.id
+ status: "suya..",
+ visibility: "direct",
+ in_reply_to_status_id: activity.id
})
Enum.each(["public", "private", "unlisted"], fn visibility ->
assert {:error, "The message visibility must be direct"} =
CommonAPI.post(user, %{
- "status" => "suya..",
- "visibility" => visibility,
- "in_reply_to_status_id" => activity.id
+ status: "suya..",
+ visibility: visibility,
+ in_reply_to_status_id: activity.id
})
end)
end
@@ -327,8 +327,7 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
{:ok, list} = Pleroma.List.create("foo", user)
- {:ok, activity} =
- CommonAPI.post(user, %{"status" => "foobar", "visibility" => "list:#{list.id}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "foobar", visibility: "list:#{list.id}"})
assert activity.data["bcc"] == [list.ap_id]
assert activity.recipients == [list.ap_id, user.ap_id]
@@ -339,7 +338,7 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
assert {:error, "Cannot post an empty status without attachments"} =
- CommonAPI.post(user, %{"status" => ""})
+ CommonAPI.post(user, %{status: ""})
end
test "it validates character limits are correctly enforced" do
@@ -348,9 +347,9 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
assert {:error, "The status is over the character limit"} =
- CommonAPI.post(user, %{"status" => "foobar"})
+ CommonAPI.post(user, %{status: "foobar"})
- assert {:ok, activity} = CommonAPI.post(user, %{"status" => "12345"})
+ assert {:ok, activity} = CommonAPI.post(user, %{status: "12345"})
end
test "it can handle activities that expire" do
@@ -361,8 +360,7 @@ defmodule Pleroma.Web.CommonAPITest do
|> NaiveDateTime.truncate(:second)
|> NaiveDateTime.add(1_000_000, :second)
- assert {:ok, activity} =
- CommonAPI.post(user, %{"status" => "chai", "expires_in" => 1_000_000})
+ assert {:ok, activity} = CommonAPI.post(user, %{status: "chai", expires_in: 1_000_000})
assert expiration = Pleroma.ActivityExpiration.get_by_activity_id(activity.id)
assert expiration.scheduled_at == expires_at
@@ -374,14 +372,14 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
{:ok, reaction} = CommonAPI.react_with_emoji(activity.id, user, "👍")
assert reaction.data["actor"] == user.ap_id
assert reaction.data["content"] == "👍"
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
{:error, _} = CommonAPI.react_with_emoji(activity.id, user, ".")
end
@@ -390,7 +388,7 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
{:ok, reaction} = CommonAPI.react_with_emoji(activity.id, user, "👍")
{:ok, unreaction} = CommonAPI.unreact_with_emoji(activity.id, user, "👍")
@@ -404,7 +402,7 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
{:ok, %Activity{}, _} = CommonAPI.repeat(activity.id, user)
end
@@ -412,7 +410,7 @@ defmodule Pleroma.Web.CommonAPITest do
test "can't repeat a repeat" do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
{:ok, %Activity{} = announce, _} = CommonAPI.repeat(activity.id, other_user)
@@ -423,10 +421,10 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
{:ok, %Activity{} = announce_activity, _} =
- CommonAPI.repeat(activity.id, user, %{"visibility" => "private"})
+ CommonAPI.repeat(activity.id, user, %{visibility: "private"})
assert Visibility.is_private?(announce_activity)
end
@@ -435,7 +433,7 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
other_user = insert(:user)
- {:ok, post_activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
+ {:ok, post_activity} = CommonAPI.post(other_user, %{status: "cofe"})
{:ok, %Activity{data: data}} = CommonAPI.favorite(user, post_activity.id)
assert data["type"] == "Like"
@@ -447,7 +445,7 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
{:ok, %Activity{} = announce, object} = CommonAPI.repeat(activity.id, user)
{:ok, ^announce, ^object} = CommonAPI.repeat(activity.id, user)
end
@@ -456,7 +454,7 @@ defmodule Pleroma.Web.CommonAPITest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "cofe"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
{:ok, %Activity{}} = CommonAPI.favorite(user, activity.id)
assert {:ok, :already_liked} = CommonAPI.favorite(user, activity.id)
end
@@ -467,7 +465,7 @@ defmodule Pleroma.Web.CommonAPITest do
Pleroma.Config.put([:instance, :max_pinned_statuses], 1)
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "HI!!!"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "HI!!!"})
[user: user, activity: activity]
end
@@ -484,8 +482,8 @@ defmodule Pleroma.Web.CommonAPITest do
test "pin poll", %{user: user} do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "How is fediverse today?",
- "poll" => %{"options" => ["Absolutely outstanding", "Not good"], "expires_in" => 20}
+ status: "How is fediverse today?",
+ poll: %{options: ["Absolutely outstanding", "Not good"], expires_in: 20}
})
assert {:ok, ^activity} = CommonAPI.pin(activity.id, user)
@@ -497,7 +495,7 @@ defmodule Pleroma.Web.CommonAPITest do
end
test "unlisted statuses can be pinned", %{user: user} do
- {:ok, activity} = CommonAPI.post(user, %{"status" => "HI!!!", "visibility" => "unlisted"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "HI!!!", visibility: "unlisted"})
assert {:ok, ^activity} = CommonAPI.pin(activity.id, user)
end
@@ -508,7 +506,7 @@ defmodule Pleroma.Web.CommonAPITest do
end
test "max pinned statuses", %{user: user, activity: activity_one} do
- {:ok, activity_two} = CommonAPI.post(user, %{"status" => "HI!!!"})
+ {:ok, activity_two} = CommonAPI.post(user, %{status: "HI!!!"})
assert {:ok, ^activity_one} = CommonAPI.pin(activity_one.id, user)
@@ -576,7 +574,7 @@ defmodule Pleroma.Web.CommonAPITest do
reporter = insert(:user)
target_user = insert(:user)
- {:ok, activity} = CommonAPI.post(target_user, %{"status" => "foobar"})
+ {:ok, activity} = CommonAPI.post(target_user, %{status: "foobar"})
reporter_ap_id = reporter.ap_id
target_ap_id = target_user.ap_id
@@ -813,8 +811,8 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "Am I cute?",
- "poll" => %{"options" => ["Yes", "No"], "expires_in" => 20}
+ status: "Am I cute?",
+ poll: %{options: ["Yes", "No"], expires_in: 20}
})
object = Object.normalize(activity)
diff --git a/test/web/common_api/common_api_utils_test.exs b/test/web/common_api/common_api_utils_test.exs
index 18a3b3b87..5708db6a4 100644
--- a/test/web/common_api/common_api_utils_test.exs
+++ b/test/web/common_api/common_api_utils_test.exs
@@ -228,7 +228,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
user = insert(:user)
mentioned_user = insert(:user)
third_user = insert(:user)
- {:ok, activity} = CommonAPI.post(third_user, %{"status" => "uguu"})
+ {:ok, activity} = CommonAPI.post(third_user, %{status: "uguu"})
mentions = [mentioned_user.ap_id]
{to, cc} = Utils.get_to_and_cc(user, mentions, activity, "public", nil)
@@ -261,7 +261,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
user = insert(:user)
mentioned_user = insert(:user)
third_user = insert(:user)
- {:ok, activity} = CommonAPI.post(third_user, %{"status" => "uguu"})
+ {:ok, activity} = CommonAPI.post(third_user, %{status: "uguu"})
mentions = [mentioned_user.ap_id]
{to, cc} = Utils.get_to_and_cc(user, mentions, activity, "unlisted", nil)
@@ -292,7 +292,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
user = insert(:user)
mentioned_user = insert(:user)
third_user = insert(:user)
- {:ok, activity} = CommonAPI.post(third_user, %{"status" => "uguu"})
+ {:ok, activity} = CommonAPI.post(third_user, %{status: "uguu"})
mentions = [mentioned_user.ap_id]
{to, cc} = Utils.get_to_and_cc(user, mentions, activity, "private", nil)
@@ -322,7 +322,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
user = insert(:user)
mentioned_user = insert(:user)
third_user = insert(:user)
- {:ok, activity} = CommonAPI.post(third_user, %{"status" => "uguu"})
+ {:ok, activity} = CommonAPI.post(third_user, %{status: "uguu"})
mentions = [mentioned_user.ap_id]
{to, cc} = Utils.get_to_and_cc(user, mentions, activity, "direct", nil)
@@ -463,8 +463,8 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
desc = Jason.encode!(%{object.id => "test-desc"})
assert Utils.attachments_from_ids(%{
- "media_ids" => ["#{object.id}"],
- "descriptions" => desc
+ media_ids: ["#{object.id}"],
+ descriptions: desc
}) == [
Map.merge(object.data, %{"name" => "test-desc"})
]
@@ -472,7 +472,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
test "returns attachments without descs" do
object = insert(:note)
- assert Utils.attachments_from_ids(%{"media_ids" => ["#{object.id}"]}) == [object.data]
+ assert Utils.attachments_from_ids(%{media_ids: ["#{object.id}"]}) == [object.data]
end
test "returns [] when not pass media_ids" do
diff --git a/test/web/federator_test.exs b/test/web/federator_test.exs
index 261518ef0..de90aa6e0 100644
--- a/test/web/federator_test.exs
+++ b/test/web/federator_test.exs
@@ -29,7 +29,7 @@ defmodule Pleroma.Web.FederatorTest do
describe "Publish an activity" do
setup do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "HI"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "HI"})
relay_mock = {
Pleroma.Web.ActivityPub.Relay,
@@ -96,7 +96,7 @@ defmodule Pleroma.Web.FederatorTest do
Instances.set_consistently_unreachable(URI.parse(inbox2).host)
{:ok, _activity} =
- CommonAPI.post(user, %{"status" => "HI @nick1@domain.com, @nick2@domain2.com!"})
+ CommonAPI.post(user, %{status: "HI @nick1@domain.com, @nick2@domain2.com!"})
expected_dt = NaiveDateTime.to_iso8601(dt)
diff --git a/test/web/feed/tag_controller_test.exs b/test/web/feed/tag_controller_test.exs
index d95aac108..a54161bd4 100644
--- a/test/web/feed/tag_controller_test.exs
+++ b/test/web/feed/tag_controller_test.exs
@@ -21,7 +21,7 @@ defmodule Pleroma.Web.Feed.TagControllerTest do
)
user = insert(:user)
- {:ok, activity1} = CommonAPI.post(user, %{"status" => "yeah #PleromaArt"})
+ {:ok, activity1} = CommonAPI.post(user, %{status: "yeah #PleromaArt"})
object = Object.normalize(activity1)
@@ -43,9 +43,9 @@ defmodule Pleroma.Web.Feed.TagControllerTest do
|> Ecto.Changeset.change(data: object_data)
|> Pleroma.Repo.update()
- {:ok, activity2} = CommonAPI.post(user, %{"status" => "42 This is :moominmamma #PleromaArt"})
+ {:ok, activity2} = CommonAPI.post(user, %{status: "42 This is :moominmamma #PleromaArt"})
- {:ok, _activity3} = CommonAPI.post(user, %{"status" => "This is :moominmamma"})
+ {:ok, _activity3} = CommonAPI.post(user, %{status: "This is :moominmamma"})
response =
conn
@@ -88,7 +88,7 @@ defmodule Pleroma.Web.Feed.TagControllerTest do
)
user = insert(:user)
- {:ok, activity1} = CommonAPI.post(user, %{"status" => "yeah #PleromaArt"})
+ {:ok, activity1} = CommonAPI.post(user, %{status: "yeah #PleromaArt"})
object = Object.normalize(activity1)
@@ -110,9 +110,9 @@ defmodule Pleroma.Web.Feed.TagControllerTest do
|> Ecto.Changeset.change(data: object_data)
|> Pleroma.Repo.update()
- {:ok, activity2} = CommonAPI.post(user, %{"status" => "42 This is :moominmamma #PleromaArt"})
+ {:ok, activity2} = CommonAPI.post(user, %{status: "42 This is :moominmamma #PleromaArt"})
- {:ok, _activity3} = CommonAPI.post(user, %{"status" => "This is :moominmamma"})
+ {:ok, _activity3} = CommonAPI.post(user, %{status: "This is :moominmamma"})
response =
conn
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 0d48ae4ae..280bd6aca 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -226,7 +226,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
user = insert(:user, ap_id: "https://honktest/u/test", local: false)
other_user = insert(:user)
- {:ok, post} = CommonAPI.post(other_user, %{"status" => "bonkeronk"})
+ {:ok, post} = CommonAPI.post(other_user, %{status: "bonkeronk"})
{:ok, announce, _} =
%{
@@ -255,7 +255,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
User.block(user_one, user_two)
- {:ok, activity} = CommonAPI.post(user_two, %{"status" => "User one sux0rz"})
+ {:ok, activity} = CommonAPI.post(user_two, %{status: "User one sux0rz"})
{:ok, repeat, _} = CommonAPI.repeat(activity.id, user_three)
assert resp =
@@ -298,16 +298,16 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
{:ok, _user_three} = User.follow(user_three, user_one)
- {:ok, activity} = CommonAPI.post(user_one, %{"status" => "HI!!!"})
+ {:ok, activity} = CommonAPI.post(user_one, %{status: "HI!!!"})
{:ok, direct_activity} =
CommonAPI.post(user_one, %{
- "status" => "Hi, @#{user_two.nickname}.",
- "visibility" => "direct"
+ status: "Hi, @#{user_two.nickname}.",
+ visibility: "direct"
})
{:ok, private_activity} =
- CommonAPI.post(user_one, %{"status" => "private", "visibility" => "private"})
+ CommonAPI.post(user_one, %{status: "private", visibility: "private"})
# TODO!!!
resp =
@@ -362,8 +362,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
{:ok, %{id: media_id}} = ActivityPub.upload(file, actor: user.ap_id)
- {:ok, %{id: image_post_id}} =
- CommonAPI.post(user, %{"status" => "cofe", "media_ids" => [media_id]})
+ {:ok, %{id: image_post_id}} = CommonAPI.post(user, %{status: "cofe", media_ids: [media_id]})
conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?only_media=true")
@@ -375,7 +374,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
end
test "gets a user's statuses without reblogs", %{user: user, conn: conn} do
- {:ok, %{id: post_id}} = CommonAPI.post(user, %{"status" => "HI!!!"})
+ {:ok, %{id: post_id}} = CommonAPI.post(user, %{status: "HI!!!"})
{:ok, _, _} = CommonAPI.repeat(post_id, user)
conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?exclude_reblogs=true")
@@ -386,8 +385,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
end
test "filters user's statuses by a hashtag", %{user: user, conn: conn} do
- {:ok, %{id: post_id}} = CommonAPI.post(user, %{"status" => "#hashtag"})
- {:ok, _post} = CommonAPI.post(user, %{"status" => "hashtag"})
+ {:ok, %{id: post_id}} = CommonAPI.post(user, %{status: "#hashtag"})
+ {:ok, _post} = CommonAPI.post(user, %{status: "hashtag"})
conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?tagged=hashtag")
assert [%{"id" => ^post_id}] = json_response_and_validate_schema(conn, 200)
@@ -398,9 +397,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
conn: conn
} do
{:ok, %{id: public_activity_id}} =
- CommonAPI.post(user, %{"status" => ".", "visibility" => "public"})
+ CommonAPI.post(user, %{status: ".", visibility: "public"})
- {:ok, _direct_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
+ {:ok, _direct_activity} = CommonAPI.post(user, %{status: ".", visibility: "direct"})
conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?exclude_visibilities[]=direct")
assert [%{"id" => ^public_activity_id}] = json_response_and_validate_schema(conn, 200)
@@ -678,7 +677,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert %{"showing_reblogs" => false} = json_response_and_validate_schema(ret_conn, 200)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hey"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "hey"})
{:ok, %{id: reblog_id}, _} = CommonAPI.repeat(activity.id, followed)
assert [] ==
@@ -777,7 +776,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
describe "pinned statuses" do
setup do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "HI!!!"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "HI!!!"})
%{conn: conn} = oauth_access(["read:statuses"], user: user)
[conn: conn, user: user, activity: activity]
diff --git a/test/web/mastodon_api/controllers/conversation_controller_test.exs b/test/web/mastodon_api/controllers/conversation_controller_test.exs
index 04695572e..693ba51e5 100644
--- a/test/web/mastodon_api/controllers/conversation_controller_test.exs
+++ b/test/web/mastodon_api/controllers/conversation_controller_test.exs
@@ -22,16 +22,16 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
{:ok, direct} =
CommonAPI.post(user_one, %{
- "status" => "Hi @#{user_two.nickname}, @#{user_three.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{user_two.nickname}, @#{user_three.nickname}!",
+ visibility: "direct"
})
assert User.get_cached_by_id(user_two.id).unread_conversation_count == 1
{:ok, _follower_only} =
CommonAPI.post(user_one, %{
- "status" => "Hi @#{user_two.nickname}!",
- "visibility" => "private"
+ status: "Hi @#{user_two.nickname}!",
+ visibility: "private"
})
res_conn = get(conn, "/api/v1/conversations")
@@ -63,32 +63,32 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
{:ok, direct1} =
CommonAPI.post(user_one, %{
- "status" => "Hi @#{user_two.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{user_two.nickname}!",
+ visibility: "direct"
})
{:ok, _direct2} =
CommonAPI.post(user_one, %{
- "status" => "Hi @#{user_three.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{user_three.nickname}!",
+ visibility: "direct"
})
{:ok, direct3} =
CommonAPI.post(user_one, %{
- "status" => "Hi @#{user_two.nickname}, @#{user_three.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{user_two.nickname}, @#{user_three.nickname}!",
+ visibility: "direct"
})
{:ok, _direct4} =
CommonAPI.post(user_two, %{
- "status" => "Hi @#{user_three.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{user_three.nickname}!",
+ visibility: "direct"
})
{:ok, direct5} =
CommonAPI.post(user_two, %{
- "status" => "Hi @#{user_one.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{user_one.nickname}!",
+ visibility: "direct"
})
assert [conversation1, conversation2] =
@@ -112,15 +112,15 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
{:ok, direct} =
CommonAPI.post(user_one, %{
- "status" => "Hi @#{user_two.nickname}",
- "visibility" => "direct"
+ status: "Hi @#{user_two.nickname}",
+ visibility: "direct"
})
{:ok, direct_reply} =
CommonAPI.post(user_two, %{
- "status" => "reply",
- "visibility" => "direct",
- "in_reply_to_status_id" => direct.id
+ status: "reply",
+ visibility: "direct",
+ in_reply_to_status_id: direct.id
})
[%{"last_status" => res_last_status}] =
@@ -136,8 +136,8 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
{:ok, direct} =
CommonAPI.post(user_one, %{
- "status" => "Hi @#{user_two.nickname}",
- "visibility" => "direct"
+ status: "Hi @#{user_two.nickname}",
+ visibility: "direct"
})
assert User.get_cached_by_id(user_one.id).unread_conversation_count == 0
@@ -167,9 +167,9 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
# The conversation is marked as unread on reply
{:ok, _} =
CommonAPI.post(user_two, %{
- "status" => "reply",
- "visibility" => "direct",
- "in_reply_to_status_id" => direct.id
+ status: "reply",
+ visibility: "direct",
+ in_reply_to_status_id: direct.id
})
[%{"unread" => true}] =
@@ -183,9 +183,9 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
# A reply doesn't increment the user's unread_conversation_count if the conversation is unread
{:ok, _} =
CommonAPI.post(user_two, %{
- "status" => "reply",
- "visibility" => "direct",
- "in_reply_to_status_id" => direct.id
+ status: "reply",
+ visibility: "direct",
+ in_reply_to_status_id: direct.id
})
assert User.get_cached_by_id(user_one.id).unread_conversation_count == 1
@@ -197,8 +197,8 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
{:ok, direct} =
CommonAPI.post(user_one, %{
- "status" => "Hi @#{user_two.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{user_two.nickname}!",
+ visibility: "direct"
})
res_conn = get(conn, "/api/v1/statuses/#{direct.id}/context")
diff --git a/test/web/mastodon_api/controllers/instance_controller_test.exs b/test/web/mastodon_api/controllers/instance_controller_test.exs
index 90840d5ab..2c61dc5ba 100644
--- a/test/web/mastodon_api/controllers/instance_controller_test.exs
+++ b/test/web/mastodon_api/controllers/instance_controller_test.exs
@@ -50,7 +50,7 @@ defmodule Pleroma.Web.MastodonAPI.InstanceControllerTest do
insert(:user, %{local: false, nickname: "u@peer1.com"})
insert(:user, %{local: false, nickname: "u@peer2.com"})
- {:ok, _} = Pleroma.Web.CommonAPI.post(user, %{"status" => "cofe"})
+ {:ok, _} = Pleroma.Web.CommonAPI.post(user, %{status: "cofe"})
Pleroma.Stats.force_update()
diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs
index db380f76a..d9356a844 100644
--- a/test/web/mastodon_api/controllers/notification_controller_test.exs
+++ b/test/web/mastodon_api/controllers/notification_controller_test.exs
@@ -18,7 +18,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
%{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
{:ok, [_notification]} = Notification.create_notifications(activity)
response =
@@ -36,7 +36,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
%{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
{:ok, [_notification]} = Notification.create_notifications(activity)
@@ -60,7 +60,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
%{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
{:ok, [notification]} = Notification.create_notifications(activity)
@@ -79,7 +79,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
%{user: user, conn: conn} = oauth_access(["write:notifications"])
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
{:ok, [notification]} = Notification.create_notifications(activity)
@@ -96,7 +96,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
%{user: user, conn: conn} = oauth_access(["write:notifications"])
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
{:ok, [notification]} = Notification.create_notifications(activity)
@@ -112,7 +112,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
%{user: user, conn: conn} = oauth_access(["write:notifications", "read:notifications"])
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
{:ok, [_notification]} = Notification.create_notifications(activity)
@@ -130,10 +130,10 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
%{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user)
- {:ok, activity1} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
- {:ok, activity2} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
- {:ok, activity3} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
- {:ok, activity4} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
+ {:ok, activity1} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
+ {:ok, activity2} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
+ {:ok, activity3} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
+ {:ok, activity4} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
notification1_id = get_notification_id_by_activity(activity1)
notification2_id = get_notification_id_by_activity(activity2)
@@ -173,16 +173,16 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
other_user = insert(:user)
{:ok, public_activity} =
- CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "public"})
+ CommonAPI.post(other_user, %{status: "@#{user.nickname}", visibility: "public"})
{:ok, direct_activity} =
- CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "direct"})
+ CommonAPI.post(other_user, %{status: "@#{user.nickname}", visibility: "direct"})
{:ok, unlisted_activity} =
- CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "unlisted"})
+ CommonAPI.post(other_user, %{status: "@#{user.nickname}", visibility: "unlisted"})
{:ok, private_activity} =
- CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "private"})
+ CommonAPI.post(other_user, %{status: "@#{user.nickname}", visibility: "private"})
query = params_to_query(%{exclude_visibilities: ["public", "unlisted", "private"]})
conn_res = get(conn, "/api/v1/notifications?" <> query)
@@ -213,17 +213,15 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
user = insert(:user)
%{user: other_user, conn: conn} = oauth_access(["read:notifications"])
- {:ok, public_activity} =
- CommonAPI.post(other_user, %{"status" => ".", "visibility" => "public"})
+ {:ok, public_activity} = CommonAPI.post(other_user, %{status: ".", visibility: "public"})
{:ok, direct_activity} =
- CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "direct"})
+ CommonAPI.post(other_user, %{status: "@#{user.nickname}", visibility: "direct"})
{:ok, unlisted_activity} =
- CommonAPI.post(other_user, %{"status" => ".", "visibility" => "unlisted"})
+ CommonAPI.post(other_user, %{status: ".", visibility: "unlisted"})
- {:ok, private_activity} =
- CommonAPI.post(other_user, %{"status" => ".", "visibility" => "private"})
+ {:ok, private_activity} = CommonAPI.post(other_user, %{status: ".", visibility: "private"})
{:ok, _} = CommonAPI.favorite(user, public_activity.id)
{:ok, _} = CommonAPI.favorite(user, direct_activity.id)
@@ -279,11 +277,10 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
user = insert(:user)
%{user: other_user, conn: conn} = oauth_access(["read:notifications"])
- {:ok, public_activity} =
- CommonAPI.post(other_user, %{"status" => ".", "visibility" => "public"})
+ {:ok, public_activity} = CommonAPI.post(other_user, %{status: ".", visibility: "public"})
{:ok, unlisted_activity} =
- CommonAPI.post(other_user, %{"status" => ".", "visibility" => "unlisted"})
+ CommonAPI.post(other_user, %{status: ".", visibility: "unlisted"})
{:ok, _, _} = CommonAPI.repeat(public_activity.id, user)
{:ok, _, _} = CommonAPI.repeat(unlisted_activity.id, user)
@@ -303,8 +300,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
%{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user)
- {:ok, mention_activity} = CommonAPI.post(other_user, %{"status" => "hey @#{user.nickname}"})
- {:ok, create_activity} = CommonAPI.post(user, %{"status" => "hey"})
+ {:ok, mention_activity} = CommonAPI.post(other_user, %{status: "hey @#{user.nickname}"})
+ {:ok, create_activity} = CommonAPI.post(user, %{status: "hey"})
{:ok, favorite_activity} = CommonAPI.favorite(other_user, create_activity.id)
{:ok, reblog_activity, _} = CommonAPI.repeat(create_activity.id, other_user)
{:ok, _, _, follow_activity} = CommonAPI.follow(other_user, user)
@@ -341,8 +338,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
%{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user)
- {:ok, mention_activity} = CommonAPI.post(other_user, %{"status" => "hey @#{user.nickname}"})
- {:ok, create_activity} = CommonAPI.post(user, %{"status" => "hey"})
+ {:ok, mention_activity} = CommonAPI.post(other_user, %{status: "hey @#{user.nickname}"})
+ {:ok, create_activity} = CommonAPI.post(user, %{status: "hey"})
{:ok, favorite_activity} = CommonAPI.favorite(other_user, create_activity.id)
{:ok, reblog_activity, _} = CommonAPI.repeat(create_activity.id, other_user)
{:ok, _, _, follow_activity} = CommonAPI.follow(other_user, user)
@@ -388,10 +385,10 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
%{user: user, conn: conn} = oauth_access(["read:notifications", "write:notifications"])
other_user = insert(:user)
- {:ok, activity1} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
- {:ok, activity2} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
- {:ok, activity3} = CommonAPI.post(user, %{"status" => "hi @#{other_user.nickname}"})
- {:ok, activity4} = CommonAPI.post(user, %{"status" => "hi @#{other_user.nickname}"})
+ {:ok, activity1} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
+ {:ok, activity2} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
+ {:ok, activity3} = CommonAPI.post(user, %{status: "hi @#{other_user.nickname}"})
+ {:ok, activity4} = CommonAPI.post(user, %{status: "hi @#{other_user.nickname}"})
notification1_id = get_notification_id_by_activity(activity1)
notification2_id = get_notification_id_by_activity(activity2)
@@ -435,7 +432,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
user2 = insert(:user)
{:ok, _, _, _} = CommonAPI.follow(user, user2)
- {:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"})
+ {:ok, _} = CommonAPI.post(user2, %{status: "hey @#{user.nickname}"})
ret_conn = get(conn, "/api/v1/notifications")
@@ -453,7 +450,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
user2 = insert(:user)
{:ok, _, _, _} = CommonAPI.follow(user, user2)
- {:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"})
+ {:ok, _} = CommonAPI.post(user2, %{status: "hey @#{user.nickname}"})
ret_conn = get(conn, "/api/v1/notifications")
@@ -471,7 +468,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
user2 = insert(:user)
{:ok, _, _, _} = CommonAPI.follow(user, user2)
- {:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"})
+ {:ok, _} = CommonAPI.post(user2, %{status: "hey @#{user.nickname}"})
ret_conn = get(conn, "/api/v1/notifications")
@@ -518,14 +515,14 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
{:ok, activity1} =
CommonAPI.post(other_user, %{
- "status" => "hi @#{user.nickname}",
- "visibility" => "public"
+ status: "hi @#{user.nickname}",
+ visibility: "public"
})
{:ok, activity2} =
CommonAPI.post(other_user, %{
- "status" => "hi @#{user.nickname}",
- "visibility" => "public"
+ status: "hi @#{user.nickname}",
+ visibility: "public"
})
notification1 = Repo.get_by(Notification, activity_id: activity1.id)
@@ -550,8 +547,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
%{id: account_id} = other_user1 = insert(:user)
other_user2 = insert(:user)
- {:ok, _activity} = CommonAPI.post(other_user1, %{"status" => "hi @#{user.nickname}"})
- {:ok, _activity} = CommonAPI.post(other_user2, %{"status" => "bye @#{user.nickname}"})
+ {:ok, _activity} = CommonAPI.post(other_user1, %{status: "hi @#{user.nickname}"})
+ {:ok, _activity} = CommonAPI.post(other_user2, %{status: "bye @#{user.nickname}"})
assert [%{"account" => %{"id" => ^account_id}}] =
conn
diff --git a/test/web/mastodon_api/controllers/poll_controller_test.exs b/test/web/mastodon_api/controllers/poll_controller_test.exs
index d8f34aa86..f41de6448 100644
--- a/test/web/mastodon_api/controllers/poll_controller_test.exs
+++ b/test/web/mastodon_api/controllers/poll_controller_test.exs
@@ -16,8 +16,8 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
test "returns poll entity for object id", %{user: user, conn: conn} do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "Pleroma does",
- "poll" => %{"options" => ["what Mastodon't", "n't what Mastodoes"], "expires_in" => 20}
+ status: "Pleroma does",
+ poll: %{options: ["what Mastodon't", "n't what Mastodoes"], expires_in: 20}
})
object = Object.normalize(activity)
@@ -34,9 +34,9 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
{:ok, activity} =
CommonAPI.post(other_user, %{
- "status" => "Pleroma does",
- "poll" => %{"options" => ["what Mastodon't", "n't what Mastodoes"], "expires_in" => 20},
- "visibility" => "private"
+ status: "Pleroma does",
+ poll: %{options: ["what Mastodon't", "n't what Mastodoes"], expires_in: 20},
+ visibility: "private"
})
object = Object.normalize(activity)
@@ -55,11 +55,11 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
{:ok, activity} =
CommonAPI.post(other_user, %{
- "status" => "A very delicious sandwich",
- "poll" => %{
- "options" => ["Lettuce", "Grilled Bacon", "Tomato"],
- "expires_in" => 20,
- "multiple" => true
+ status: "A very delicious sandwich",
+ poll: %{
+ options: ["Lettuce", "Grilled Bacon", "Tomato"],
+ expires_in: 20,
+ multiple: true
}
})
@@ -81,8 +81,8 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
test "author can't vote", %{user: user, conn: conn} do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "Am I cute?",
- "poll" => %{"options" => ["Yes", "No"], "expires_in" => 20}
+ status: "Am I cute?",
+ poll: %{options: ["Yes", "No"], expires_in: 20}
})
object = Object.normalize(activity)
@@ -102,8 +102,8 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
{:ok, activity} =
CommonAPI.post(other_user, %{
- "status" => "The glass is",
- "poll" => %{"options" => ["half empty", "half full"], "expires_in" => 20}
+ status: "The glass is",
+ poll: %{options: ["half empty", "half full"], expires_in: 20}
})
object = Object.normalize(activity)
@@ -125,8 +125,8 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
{:ok, activity} =
CommonAPI.post(other_user, %{
- "status" => "Am I cute?",
- "poll" => %{"options" => ["Yes", "No"], "expires_in" => 20}
+ status: "Am I cute?",
+ poll: %{options: ["Yes", "No"], expires_in: 20}
})
object = Object.normalize(activity)
@@ -153,9 +153,9 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
{:ok, activity} =
CommonAPI.post(other_user, %{
- "status" => "Am I cute?",
- "poll" => %{"options" => ["Yes", "No"], "expires_in" => 20},
- "visibility" => "private"
+ status: "Am I cute?",
+ poll: %{options: ["Yes", "No"], expires_in: 20},
+ visibility: "private"
})
object = Object.normalize(activity)
diff --git a/test/web/mastodon_api/controllers/report_controller_test.exs b/test/web/mastodon_api/controllers/report_controller_test.exs
index 21b037237..6636cff96 100644
--- a/test/web/mastodon_api/controllers/report_controller_test.exs
+++ b/test/web/mastodon_api/controllers/report_controller_test.exs
@@ -14,7 +14,7 @@ defmodule Pleroma.Web.MastodonAPI.ReportControllerTest do
setup do
target_user = insert(:user)
- {:ok, activity} = CommonAPI.post(target_user, %{"status" => "foobar"})
+ {:ok, activity} = CommonAPI.post(target_user, %{status: "foobar"})
[target_user: target_user, activity: activity]
end
diff --git a/test/web/mastodon_api/controllers/search_controller_test.exs b/test/web/mastodon_api/controllers/search_controller_test.exs
index 02476acb6..6ad9a59fe 100644
--- a/test/web/mastodon_api/controllers/search_controller_test.exs
+++ b/test/web/mastodon_api/controllers/search_controller_test.exs
@@ -42,15 +42,15 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
user_two = insert(:user, %{nickname: "shp@shitposter.club"})
user_three = insert(:user, %{nickname: "shp@heldscal.la", name: "I love 2hu"})
- {:ok, activity} = CommonAPI.post(user, %{"status" => "This is about 2hu private 天子"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "This is about 2hu private 天子"})
{:ok, _activity} =
CommonAPI.post(user, %{
- "status" => "This is about 2hu, but private",
- "visibility" => "private"
+ status: "This is about 2hu, but private",
+ visibility: "private"
})
- {:ok, _} = CommonAPI.post(user_two, %{"status" => "This isn't"})
+ {:ok, _} = CommonAPI.post(user_two, %{status: "This isn't"})
results =
conn
@@ -80,9 +80,9 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
user_smith = insert(:user, %{nickname: "Agent", name: "I love 2hu"})
user_neo = insert(:user, %{nickname: "Agent Neo", name: "Agent"})
- {:ok, act1} = CommonAPI.post(user, %{"status" => "This is about 2hu private 天子"})
- {:ok, act2} = CommonAPI.post(user_smith, %{"status" => "Agent Smith"})
- {:ok, act3} = CommonAPI.post(user_neo, %{"status" => "Agent Smith"})
+ {:ok, act1} = CommonAPI.post(user, %{status: "This is about 2hu private 天子"})
+ {:ok, act2} = CommonAPI.post(user_smith, %{status: "Agent Smith"})
+ {:ok, act3} = CommonAPI.post(user_neo, %{status: "Agent Smith"})
Pleroma.User.block(user, user_smith)
results =
@@ -161,15 +161,15 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
user_two = insert(:user, %{nickname: "shp@shitposter.club"})
user_three = insert(:user, %{nickname: "shp@heldscal.la", name: "I love 2hu"})
- {:ok, activity} = CommonAPI.post(user, %{"status" => "This is about 2hu"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "This is about 2hu"})
{:ok, _activity} =
CommonAPI.post(user, %{
- "status" => "This is about 2hu, but private",
- "visibility" => "private"
+ status: "This is about 2hu, but private",
+ visibility: "private"
})
- {:ok, _} = CommonAPI.post(user_two, %{"status" => "This isn't"})
+ {:ok, _} = CommonAPI.post(user_two, %{status: "This isn't"})
results =
conn
@@ -189,7 +189,7 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
capture_log(fn ->
{:ok, %{id: activity_id}} =
CommonAPI.post(insert(:user), %{
- "status" => "check out https://shitposter.club/notice/2827873"
+ status: "check out https://shitposter.club/notice/2827873"
})
results =
@@ -207,8 +207,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
test "search doesn't show statuses that it shouldn't", %{conn: conn} do
{:ok, activity} =
CommonAPI.post(insert(:user), %{
- "status" => "This is about 2hu, but private",
- "visibility" => "private"
+ status: "This is about 2hu, but private",
+ visibility: "private"
})
capture_log(fn ->
@@ -251,8 +251,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
_user_two = insert(:user, %{nickname: "shp@shitposter.club"})
_user_three = insert(:user, %{nickname: "shp@heldscal.la", name: "I love 2hu"})
- {:ok, _activity1} = CommonAPI.post(user, %{"status" => "This is about 2hu"})
- {:ok, _activity2} = CommonAPI.post(user, %{"status" => "This is also about 2hu"})
+ {:ok, _activity1} = CommonAPI.post(user, %{status: "This is about 2hu"})
+ {:ok, _activity2} = CommonAPI.post(user, %{status: "This is also about 2hu"})
result =
conn
@@ -277,7 +277,7 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
user = insert(:user)
_user_two = insert(:user, %{nickname: "shp@heldscal.la", name: "I love 2hu"})
- {:ok, _activity} = CommonAPI.post(user, %{"status" => "This is about 2hu"})
+ {:ok, _activity} = CommonAPI.post(user, %{status: "This is about 2hu"})
assert %{"statuses" => [_activity], "accounts" => [], "hashtags" => []} =
conn
@@ -294,8 +294,8 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
user = insert(:user, %{nickname: "shp@shitposter.club"})
user_two = insert(:user, %{nickname: "shp@heldscal.la", name: "I love 2hu"})
- {:ok, activity1} = CommonAPI.post(user, %{"status" => "This is about 2hu"})
- {:ok, activity2} = CommonAPI.post(user_two, %{"status" => "This is also about 2hu"})
+ {:ok, activity1} = CommonAPI.post(user, %{status: "This is about 2hu"})
+ {:ok, activity2} = CommonAPI.post(user_two, %{status: "This is also about 2hu"})
results =
conn
diff --git a/test/web/mastodon_api/controllers/status_controller_test.exs b/test/web/mastodon_api/controllers/status_controller_test.exs
index 85068edd0..a4403132c 100644
--- a/test/web/mastodon_api/controllers/status_controller_test.exs
+++ b/test/web/mastodon_api/controllers/status_controller_test.exs
@@ -32,13 +32,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
response =
conn
+ |> put_req_header("content-type", "application/json")
|> post("api/v1/statuses", %{
"content_type" => "text/plain",
"source" => "Pleroma FE",
"status" => "Hello world",
"visibility" => "public"
})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert response["reblogs_count"] == 0
ObanHelpers.perform_all()
@@ -46,7 +47,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
response =
conn
|> get("api/v1/statuses/#{response["id"]}", %{})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert response["reblogs_count"] == 0
end
@@ -56,6 +57,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
conn_one =
conn
+ |> put_req_header("content-type", "application/json")
|> put_req_header("idempotency-key", idempotency_key)
|> post("/api/v1/statuses", %{
"status" => "cofe",
@@ -68,12 +70,13 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
assert ttl > :timer.seconds(6 * 60 * 60 - 1)
assert %{"content" => "cofe", "id" => id, "spoiler_text" => "2hu", "sensitive" => false} =
- json_response(conn_one, 200)
+ json_response_and_validate_schema(conn_one, 200)
assert Activity.get_by_id(id)
conn_two =
conn
+ |> put_req_header("content-type", "application/json")
|> put_req_header("idempotency-key", idempotency_key)
|> post("/api/v1/statuses", %{
"status" => "cofe",
@@ -86,13 +89,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
conn_three =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/statuses", %{
"status" => "cofe",
"spoiler_text" => "2hu",
"sensitive" => "false"
})
- assert %{"id" => third_id} = json_response(conn_three, 200)
+ assert %{"id" => third_id} = json_response_and_validate_schema(conn_three, 200)
refute id == third_id
# An activity that will expire:
@@ -101,12 +105,15 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
conn_four =
conn
+ |> put_req_header("content-type", "application/json")
|> post("api/v1/statuses", %{
"status" => "oolong",
"expires_in" => expires_in
})
- assert fourth_response = %{"id" => fourth_id} = json_response(conn_four, 200)
+ assert fourth_response =
+ %{"id" => fourth_id} = json_response_and_validate_schema(conn_four, 200)
+
assert activity = Activity.get_by_id(fourth_id)
assert expiration = ActivityExpiration.get_by_activity_id(fourth_id)
@@ -130,22 +137,24 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
assert %{"error" => "Expiry date is too soon"} =
conn
+ |> put_req_header("content-type", "application/json")
|> post("api/v1/statuses", %{
"status" => "oolong",
"expires_in" => expires_in
})
- |> json_response(422)
+ |> json_response_and_validate_schema(422)
# 30 minutes
expires_in = 30 * 60
assert %{"error" => "Expiry date is too soon"} =
conn
+ |> put_req_header("content-type", "application/json")
|> post("api/v1/statuses", %{
"status" => "oolong",
"expires_in" => expires_in
})
- |> json_response(422)
+ |> json_response_and_validate_schema(422)
end
test "posting an undefined status with an attachment", %{user: user, conn: conn} do
@@ -158,21 +167,24 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
{:ok, upload} = ActivityPub.upload(file, actor: user.ap_id)
conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"media_ids" => [to_string(upload.id)]
})
- assert json_response(conn, 200)
+ assert json_response_and_validate_schema(conn, 200)
end
test "replying to a status", %{user: user, conn: conn} do
- {:ok, replied_to} = CommonAPI.post(user, %{"status" => "cofe"})
+ {:ok, replied_to} = CommonAPI.post(user, %{status: "cofe"})
conn =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => replied_to.id})
- assert %{"content" => "xD", "id" => id} = json_response(conn, 200)
+ assert %{"content" => "xD", "id" => id} = json_response_and_validate_schema(conn, 200)
activity = Activity.get_by_id(id)
@@ -184,43 +196,56 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
user: user,
conn: conn
} do
- {:ok, replied_to} = CommonAPI.post(user, %{"status" => "suya..", "visibility" => "direct"})
+ {:ok, replied_to} = CommonAPI.post(user, %{status: "suya..", visibility: "direct"})
Enum.each(["public", "private", "unlisted"], fn visibility ->
conn =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/statuses", %{
"status" => "@#{user.nickname} hey",
"in_reply_to_id" => replied_to.id,
"visibility" => visibility
})
- assert json_response(conn, 422) == %{"error" => "The message visibility must be direct"}
+ assert json_response_and_validate_schema(conn, 422) == %{
+ "error" => "The message visibility must be direct"
+ }
end)
end
test "posting a status with an invalid in_reply_to_id", %{conn: conn} do
- conn = post(conn, "/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => ""})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => ""})
- assert %{"content" => "xD", "id" => id} = json_response(conn, 200)
+ assert %{"content" => "xD", "id" => id} = json_response_and_validate_schema(conn, 200)
assert Activity.get_by_id(id)
end
test "posting a sensitive status", %{conn: conn} do
- conn = post(conn, "/api/v1/statuses", %{"status" => "cofe", "sensitive" => true})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{"status" => "cofe", "sensitive" => true})
+
+ assert %{"content" => "cofe", "id" => id, "sensitive" => true} =
+ json_response_and_validate_schema(conn, 200)
- assert %{"content" => "cofe", "id" => id, "sensitive" => true} = json_response(conn, 200)
assert Activity.get_by_id(id)
end
test "posting a fake status", %{conn: conn} do
real_conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"status" =>
"\"Tenshi Eating a Corndog\" is a much discussed concept on /jp/. The significance of it is disputed, so I will focus on one core concept: the symbolism behind it"
})
- real_status = json_response(real_conn, 200)
+ real_status = json_response_and_validate_schema(real_conn, 200)
assert real_status
assert Object.get_by_ap_id(real_status["uri"])
@@ -234,13 +259,15 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
|> Kernel.put_in(["pleroma", "conversation_id"], nil)
fake_conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"status" =>
"\"Tenshi Eating a Corndog\" is a much discussed concept on /jp/. The significance of it is disputed, so I will focus on one core concept: the symbolism behind it",
"preview" => true
})
- fake_status = json_response(fake_conn, 200)
+ fake_status = json_response_and_validate_schema(fake_conn, 200)
assert fake_status
refute Object.get_by_ap_id(fake_status["uri"])
@@ -261,11 +288,15 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
Config.put([:rich_media, :enabled], true)
conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"status" => "https://example.com/ogp"
})
- assert %{"id" => id, "card" => %{"title" => "The Rock"}} = json_response(conn, 200)
+ assert %{"id" => id, "card" => %{"title" => "The Rock"}} =
+ json_response_and_validate_schema(conn, 200)
+
assert Activity.get_by_id(id)
end
@@ -273,9 +304,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
user2 = insert(:user)
content = "direct cofe @#{user2.nickname}"
- conn = post(conn, "api/v1/statuses", %{"status" => content, "visibility" => "direct"})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("api/v1/statuses", %{"status" => content, "visibility" => "direct"})
- assert %{"id" => id} = response = json_response(conn, 200)
+ assert %{"id" => id} = response = json_response_and_validate_schema(conn, 200)
assert response["visibility"] == "direct"
assert response["pleroma"]["direct_conversation_id"]
assert activity = Activity.get_by_id(id)
@@ -289,32 +323,45 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
setup do: oauth_access(["write:statuses"])
test "creates a scheduled activity", %{conn: conn} do
- scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond)
+ scheduled_at =
+ NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond)
+ |> NaiveDateTime.to_iso8601()
+ |> Kernel.<>("Z")
conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"status" => "scheduled",
"scheduled_at" => scheduled_at
})
- assert %{"scheduled_at" => expected_scheduled_at} = json_response(conn, 200)
+ assert %{"scheduled_at" => expected_scheduled_at} =
+ json_response_and_validate_schema(conn, 200)
+
assert expected_scheduled_at == CommonAPI.Utils.to_masto_date(scheduled_at)
assert [] == Repo.all(Activity)
end
test "ignores nil values", %{conn: conn} do
conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"status" => "not scheduled",
"scheduled_at" => nil
})
- assert result = json_response(conn, 200)
+ assert result = json_response_and_validate_schema(conn, 200)
assert Activity.get_by_id(result["id"])
end
test "creates a scheduled activity with a media attachment", %{user: user, conn: conn} do
- scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond)
+ scheduled_at =
+ NaiveDateTime.utc_now()
+ |> NaiveDateTime.add(:timer.minutes(120), :millisecond)
+ |> NaiveDateTime.to_iso8601()
+ |> Kernel.<>("Z")
file = %Plug.Upload{
content_type: "image/jpg",
@@ -325,13 +372,17 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
{:ok, upload} = ActivityPub.upload(file, actor: user.ap_id)
conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"media_ids" => [to_string(upload.id)],
"status" => "scheduled",
"scheduled_at" => scheduled_at
})
- assert %{"media_attachments" => [media_attachment]} = json_response(conn, 200)
+ assert %{"media_attachments" => [media_attachment]} =
+ json_response_and_validate_schema(conn, 200)
+
assert %{"type" => "image"} = media_attachment
end
@@ -339,14 +390,18 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
%{conn: conn} do
scheduled_at =
NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(5) - 1, :millisecond)
+ |> NaiveDateTime.to_iso8601()
+ |> Kernel.<>("Z")
conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"status" => "not scheduled",
"scheduled_at" => scheduled_at
})
- assert %{"content" => "not scheduled"} = json_response(conn, 200)
+ assert %{"content" => "not scheduled"} = json_response_and_validate_schema(conn, 200)
assert [] == Repo.all(ScheduledActivity)
end
@@ -355,14 +410,19 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
NaiveDateTime.utc_now()
|> NaiveDateTime.add(:timer.minutes(6), :millisecond)
|> NaiveDateTime.to_iso8601()
+ # TODO
+ |> Kernel.<>("Z")
attrs = %{params: %{}, scheduled_at: today}
{:ok, _} = ScheduledActivity.create(user, attrs)
{:ok, _} = ScheduledActivity.create(user, attrs)
- conn = post(conn, "/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => today})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => today})
- assert %{"error" => "daily limit exceeded"} == json_response(conn, 422)
+ assert %{"error" => "daily limit exceeded"} == json_response_and_validate_schema(conn, 422)
end
test "returns error when total user limit is exceeded", %{user: user, conn: conn} do
@@ -370,11 +430,13 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
NaiveDateTime.utc_now()
|> NaiveDateTime.add(:timer.minutes(6), :millisecond)
|> NaiveDateTime.to_iso8601()
+ |> Kernel.<>("Z")
tomorrow =
NaiveDateTime.utc_now()
|> NaiveDateTime.add(:timer.hours(36), :millisecond)
|> NaiveDateTime.to_iso8601()
+ |> Kernel.<>("Z")
attrs = %{params: %{}, scheduled_at: today}
{:ok, _} = ScheduledActivity.create(user, attrs)
@@ -382,9 +444,11 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
{:ok, _} = ScheduledActivity.create(user, %{params: %{}, scheduled_at: tomorrow})
conn =
- post(conn, "/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => tomorrow})
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => tomorrow})
- assert %{"error" => "total limit exceeded"} == json_response(conn, 422)
+ assert %{"error" => "total limit exceeded"} == json_response_and_validate_schema(conn, 422)
end
end
@@ -395,12 +459,17 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
time = NaiveDateTime.utc_now()
conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"status" => "Who is the #bestgrill?",
- "poll" => %{"options" => ["Rei", "Asuka", "Misato"], "expires_in" => 420}
+ "poll" => %{
+ "options" => ["Rei", "Asuka", "Misato"],
+ "expires_in" => 420
+ }
})
- response = json_response(conn, 200)
+ response = json_response_and_validate_schema(conn, 200)
assert Enum.all?(response["poll"]["options"], fn %{"title" => title} ->
title in ["Rei", "Asuka", "Misato"]
@@ -419,12 +488,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
limit = Config.get([:instance, :poll_limits, :max_options])
conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"status" => "desu~",
"poll" => %{"options" => Enum.map(0..limit, fn _ -> "desu" end), "expires_in" => 1}
})
- %{"error" => error} = json_response(conn, 422)
+ %{"error" => error} = json_response_and_validate_schema(conn, 422)
assert error == "Poll can't contain more than #{limit} options"
end
@@ -432,7 +503,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
limit = Config.get([:instance, :poll_limits, :max_option_chars])
conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"status" => "...",
"poll" => %{
"options" => [Enum.reduce(0..limit, "", fn _, acc -> acc <> "." end)],
@@ -440,7 +513,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
}
})
- %{"error" => error} = json_response(conn, 422)
+ %{"error" => error} = json_response_and_validate_schema(conn, 422)
assert error == "Poll options cannot be longer than #{limit} characters each"
end
@@ -448,7 +521,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
limit = Config.get([:instance, :poll_limits, :min_expiration])
conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"status" => "imagine arbitrary limits",
"poll" => %{
"options" => ["this post was made by pleroma gang"],
@@ -456,7 +531,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
}
})
- %{"error" => error} = json_response(conn, 422)
+ %{"error" => error} = json_response_and_validate_schema(conn, 422)
assert error == "Expiration date is too soon"
end
@@ -464,7 +539,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
limit = Config.get([:instance, :poll_limits, :max_expiration])
conn =
- post(conn, "/api/v1/statuses", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses", %{
"status" => "imagine arbitrary limits",
"poll" => %{
"options" => ["this post was made by pleroma gang"],
@@ -472,7 +549,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
}
})
- %{"error" => error} = json_response(conn, 422)
+ %{"error" => error} = json_response_and_validate_schema(conn, 422)
assert error == "Expiration date is too far in the future"
end
end
@@ -483,7 +560,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
conn = get(conn, "/api/v1/statuses/#{activity.id}")
- assert %{"id" => id} = json_response(conn, 200)
+ assert %{"id" => id} = json_response_and_validate_schema(conn, 200)
assert id == to_string(activity.id)
end
@@ -503,13 +580,13 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
res_conn = get(conn, "/api/v1/statuses/#{local.id}")
- assert json_response(res_conn, :not_found) == %{
+ assert json_response_and_validate_schema(res_conn, :not_found) == %{
"error" => "Record not found"
}
res_conn = get(conn, "/api/v1/statuses/#{remote.id}")
- assert json_response(res_conn, :not_found) == %{
+ assert json_response_and_validate_schema(res_conn, :not_found) == %{
"error" => "Record not found"
}
end
@@ -517,10 +594,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "if user is authenticated", %{local: local, remote: remote} do
%{conn: conn} = oauth_access(["read"])
res_conn = get(conn, "/api/v1/statuses/#{local.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
res_conn = get(conn, "/api/v1/statuses/#{remote.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
end
end
@@ -532,21 +609,21 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
res_conn = get(conn, "/api/v1/statuses/#{local.id}")
- assert json_response(res_conn, :not_found) == %{
+ assert json_response_and_validate_schema(res_conn, :not_found) == %{
"error" => "Record not found"
}
res_conn = get(conn, "/api/v1/statuses/#{remote.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
end
test "if user is authenticated", %{local: local, remote: remote} do
%{conn: conn} = oauth_access(["read"])
res_conn = get(conn, "/api/v1/statuses/#{local.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
res_conn = get(conn, "/api/v1/statuses/#{remote.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
end
end
@@ -557,11 +634,11 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
res_conn = get(conn, "/api/v1/statuses/#{local.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
res_conn = get(conn, "/api/v1/statuses/#{remote.id}")
- assert json_response(res_conn, :not_found) == %{
+ assert json_response_and_validate_schema(res_conn, :not_found) == %{
"error" => "Record not found"
}
end
@@ -569,10 +646,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "if user is authenticated", %{local: local, remote: remote} do
%{conn: conn} = oauth_access(["read"])
res_conn = get(conn, "/api/v1/statuses/#{local.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
res_conn = get(conn, "/api/v1/statuses/#{remote.id}")
- assert %{"id" => _} = json_response(res_conn, 200)
+ assert %{"id" => _} = json_response_and_validate_schema(res_conn, 200)
end
end
@@ -582,7 +659,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
conn = get(conn, "/api/v1/statuses/#{String.downcase(activity.id)}")
- assert json_response(conn, 404) == %{"error" => "Record not found"}
+ assert json_response_and_validate_schema(conn, 404) == %{"error" => "Record not found"}
end
test "get a direct status" do
@@ -590,7 +667,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
other_user = insert(:user)
{:ok, activity} =
- CommonAPI.post(user, %{"status" => "@#{other_user.nickname}", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "@#{other_user.nickname}", visibility: "direct"})
conn =
conn
@@ -599,7 +676,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
[participation] = Participation.for_user(user)
- res = json_response(conn, 200)
+ res = json_response_and_validate_schema(conn, 200)
assert res["pleroma"]["direct_conversation_id"] == participation.id
end
@@ -611,7 +688,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
query_string = "ids[]=#{id1}&ids[]=#{id2}"
conn = get(conn, "/api/v1/statuses/?#{query_string}")
- assert [%{"id" => ^id1}, %{"id" => ^id2}] = Enum.sort_by(json_response(conn, :ok), & &1["id"])
+ assert [%{"id" => ^id1}, %{"id" => ^id2}] =
+ Enum.sort_by(json_response_and_validate_schema(conn, :ok), & &1["id"])
end
describe "getting statuses by ids with restricted unauthenticated for local and remote" do
@@ -622,17 +700,17 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
setup do: clear_config([:restrict_unauthenticated, :activities, :remote], true)
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
- res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]})
+ res_conn = get(conn, "/api/v1/statuses?ids[]=#{local.id}&ids[]=#{remote.id}")
- assert json_response(res_conn, 200) == []
+ assert json_response_and_validate_schema(res_conn, 200) == []
end
test "if user is authenticated", %{local: local, remote: remote} do
%{conn: conn} = oauth_access(["read"])
- res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]})
+ res_conn = get(conn, "/api/v1/statuses?ids[]=#{local.id}&ids[]=#{remote.id}")
- assert length(json_response(res_conn, 200)) == 2
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 2
end
end
@@ -642,18 +720,18 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
setup do: clear_config([:restrict_unauthenticated, :activities, :local], true)
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
- res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]})
+ res_conn = get(conn, "/api/v1/statuses?ids[]=#{local.id}&ids[]=#{remote.id}")
remote_id = remote.id
- assert [%{"id" => ^remote_id}] = json_response(res_conn, 200)
+ assert [%{"id" => ^remote_id}] = json_response_and_validate_schema(res_conn, 200)
end
test "if user is authenticated", %{local: local, remote: remote} do
%{conn: conn} = oauth_access(["read"])
- res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]})
+ res_conn = get(conn, "/api/v1/statuses?ids[]=#{local.id}&ids[]=#{remote.id}")
- assert length(json_response(res_conn, 200)) == 2
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 2
end
end
@@ -663,18 +741,18 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
setup do: clear_config([:restrict_unauthenticated, :activities, :remote], true)
test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do
- res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]})
+ res_conn = get(conn, "/api/v1/statuses?ids[]=#{local.id}&ids[]=#{remote.id}")
local_id = local.id
- assert [%{"id" => ^local_id}] = json_response(res_conn, 200)
+ assert [%{"id" => ^local_id}] = json_response_and_validate_schema(res_conn, 200)
end
test "if user is authenticated", %{local: local, remote: remote} do
%{conn: conn} = oauth_access(["read"])
- res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]})
+ res_conn = get(conn, "/api/v1/statuses?ids[]=#{local.id}&ids[]=#{remote.id}")
- assert length(json_response(res_conn, 200)) == 2
+ assert length(json_response_and_validate_schema(res_conn, 200)) == 2
end
end
@@ -688,7 +766,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
|> assign(:user, author)
|> delete("/api/v1/statuses/#{activity.id}")
- assert %{} = json_response(conn, 200)
+ assert %{} = json_response_and_validate_schema(conn, 200)
refute Activity.get_by_id(activity.id)
end
@@ -702,7 +780,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
|> assign(:user, author)
|> delete("/api/v1/statuses/#{String.downcase(activity.id)}")
- assert %{"error" => "Record not found"} == json_response(conn, 404)
+ assert %{"error" => "Record not found"} == json_response_and_validate_schema(conn, 404)
end
test "when you didn't create it" do
@@ -711,7 +789,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
conn = delete(conn, "/api/v1/statuses/#{activity.id}")
- assert %{"error" => _} = json_response(conn, 403)
+ assert %{"error" => _} = json_response_and_validate_schema(conn, 403)
assert Activity.get_by_id(activity.id) == activity
end
@@ -728,7 +806,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
|> assign(:token, insert(:oauth_token, user: admin, scopes: ["write:statuses"]))
|> delete("/api/v1/statuses/#{activity1.id}")
- assert %{} = json_response(res_conn, 200)
+ assert %{} = json_response_and_validate_schema(res_conn, 200)
res_conn =
conn
@@ -736,7 +814,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
|> assign(:token, insert(:oauth_token, user: moderator, scopes: ["write:statuses"]))
|> delete("/api/v1/statuses/#{activity2.id}")
- assert %{} = json_response(res_conn, 200)
+ assert %{} = json_response_and_validate_schema(res_conn, 200)
refute Activity.get_by_id(activity1.id)
refute Activity.get_by_id(activity2.id)
@@ -749,12 +827,15 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "reblogs and returns the reblogged status", %{conn: conn} do
activity = insert(:note_activity)
- conn = post(conn, "/api/v1/statuses/#{activity.id}/reblog")
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{activity.id}/reblog")
assert %{
"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1},
"reblogged" => true
- } = json_response(conn, 200)
+ } = json_response_and_validate_schema(conn, 200)
assert to_string(activity.id) == id
end
@@ -762,21 +843,30 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "returns 404 if the reblogged status doesn't exist", %{conn: conn} do
activity = insert(:note_activity)
- conn = post(conn, "/api/v1/statuses/#{String.downcase(activity.id)}/reblog")
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{String.downcase(activity.id)}/reblog")
- assert %{"error" => "Record not found"} = json_response(conn, 404)
+ assert %{"error" => "Record not found"} = json_response_and_validate_schema(conn, 404)
end
test "reblogs privately and returns the reblogged status", %{conn: conn} do
activity = insert(:note_activity)
- conn = post(conn, "/api/v1/statuses/#{activity.id}/reblog", %{"visibility" => "private"})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post(
+ "/api/v1/statuses/#{activity.id}/reblog",
+ %{"visibility" => "private"}
+ )
assert %{
"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1},
"reblogged" => true,
"visibility" => "private"
- } = json_response(conn, 200)
+ } = json_response_and_validate_schema(conn, 200)
assert to_string(activity.id) == id
end
@@ -802,7 +892,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
"reblogged" => false,
"favourited" => false,
"bookmarked" => false
- } = json_response(conn_res, 200)
+ } = json_response_and_validate_schema(conn_res, 200)
conn_res =
build_conn()
@@ -815,7 +905,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
"reblogged" => true,
"favourited" => true,
"bookmarked" => true
- } = json_response(conn_res, 200)
+ } = json_response_and_validate_schema(conn_res, 200)
assert to_string(activity.id) == id
end
@@ -829,17 +919,24 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
{:ok, _, _} = CommonAPI.repeat(activity.id, user)
- conn = post(conn, "/api/v1/statuses/#{activity.id}/unreblog")
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{activity.id}/unreblog")
- assert %{"id" => id, "reblogged" => false, "reblogs_count" => 0} = json_response(conn, 200)
+ assert %{"id" => id, "reblogged" => false, "reblogs_count" => 0} =
+ json_response_and_validate_schema(conn, 200)
assert to_string(activity.id) == id
end
test "returns 404 error when activity does not exist", %{conn: conn} do
- conn = post(conn, "/api/v1/statuses/foo/unreblog")
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/foo/unreblog")
- assert json_response(conn, 404) == %{"error" => "Record not found"}
+ assert json_response_and_validate_schema(conn, 404) == %{"error" => "Record not found"}
end
end
@@ -849,10 +946,13 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "favs a status and returns it", %{conn: conn} do
activity = insert(:note_activity)
- conn = post(conn, "/api/v1/statuses/#{activity.id}/favourite")
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{activity.id}/favourite")
assert %{"id" => id, "favourites_count" => 1, "favourited" => true} =
- json_response(conn, 200)
+ json_response_and_validate_schema(conn, 200)
assert to_string(activity.id) == id
end
@@ -860,18 +960,23 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "favoriting twice will just return 200", %{conn: conn} do
activity = insert(:note_activity)
- post(conn, "/api/v1/statuses/#{activity.id}/favourite")
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{activity.id}/favourite")
- assert post(conn, "/api/v1/statuses/#{activity.id}/favourite")
- |> json_response(200)
+ assert conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{activity.id}/favourite")
+ |> json_response_and_validate_schema(200)
end
test "returns 404 error for a wrong id", %{conn: conn} do
conn =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/statuses/1/favourite")
- assert json_response(conn, 404) == %{"error" => "Record not found"}
+ assert json_response_and_validate_schema(conn, 404) == %{"error" => "Record not found"}
end
end
@@ -883,18 +988,24 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
{:ok, _} = CommonAPI.favorite(user, activity.id)
- conn = post(conn, "/api/v1/statuses/#{activity.id}/unfavourite")
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{activity.id}/unfavourite")
assert %{"id" => id, "favourites_count" => 0, "favourited" => false} =
- json_response(conn, 200)
+ json_response_and_validate_schema(conn, 200)
assert to_string(activity.id) == id
end
test "returns 404 error for a wrong id", %{conn: conn} do
- conn = post(conn, "/api/v1/statuses/1/unfavourite")
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/1/unfavourite")
- assert json_response(conn, 404) == %{"error" => "Record not found"}
+ assert json_response_and_validate_schema(conn, 404) == %{"error" => "Record not found"}
end
end
@@ -902,7 +1013,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
setup do: oauth_access(["write:accounts"])
setup %{user: user} do
- {:ok, activity} = CommonAPI.post(user, %{"status" => "HI!!!"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "HI!!!"})
%{activity: activity}
end
@@ -914,21 +1025,25 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
assert %{"id" => ^id_str, "pinned" => true} =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/statuses/#{activity.id}/pin")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert [%{"id" => ^id_str, "pinned" => true}] =
conn
|> get("/api/v1/accounts/#{user.id}/statuses?pinned=true")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
end
test "/pin: returns 400 error when activity is not public", %{conn: conn, user: user} do
- {:ok, dm} = CommonAPI.post(user, %{"status" => "test", "visibility" => "direct"})
+ {:ok, dm} = CommonAPI.post(user, %{status: "test", visibility: "direct"})
- conn = post(conn, "/api/v1/statuses/#{dm.id}/pin")
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{dm.id}/pin")
- assert json_response(conn, 400) == %{"error" => "Could not pin"}
+ assert json_response_and_validate_schema(conn, 400) == %{"error" => "Could not pin"}
end
test "unpin status", %{conn: conn, user: user, activity: activity} do
@@ -941,29 +1056,33 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/unpin")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert [] =
conn
|> get("/api/v1/accounts/#{user.id}/statuses?pinned=true")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
end
test "/unpin: returns 400 error when activity is not exist", %{conn: conn} do
- conn = post(conn, "/api/v1/statuses/1/unpin")
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/1/unpin")
- assert json_response(conn, 400) == %{"error" => "Could not unpin"}
+ assert json_response_and_validate_schema(conn, 400) == %{"error" => "Could not unpin"}
end
test "max pinned statuses", %{conn: conn, user: user, activity: activity_one} do
- {:ok, activity_two} = CommonAPI.post(user, %{"status" => "HI!!!"})
+ {:ok, activity_two} = CommonAPI.post(user, %{status: "HI!!!"})
id_str_one = to_string(activity_one.id)
assert %{"id" => ^id_str_one, "pinned" => true} =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/statuses/#{id_str_one}/pin")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
user = refresh_record(user)
@@ -971,7 +1090,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity_two.id}/pin")
- |> json_response(400)
+ |> json_response_and_validate_schema(400)
end
end
@@ -985,7 +1104,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "returns rich-media card", %{conn: conn, user: user} do
Tesla.Mock.mock(fn env -> apply(HttpRequestMock, :request, [env]) end)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "https://example.com/ogp"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "https://example.com/ogp"})
card_data = %{
"image" => "http://ia.media-imdb.com/images/rock.jpg",
@@ -1011,18 +1130,18 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
response =
conn
|> get("/api/v1/statuses/#{activity.id}/card")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert response == card_data
# works with private posts
{:ok, activity} =
- CommonAPI.post(user, %{"status" => "https://example.com/ogp", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "https://example.com/ogp", visibility: "direct"})
response_two =
conn
|> get("/api/v1/statuses/#{activity.id}/card")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert response_two == card_data
end
@@ -1030,13 +1149,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "replaces missing description with an empty string", %{conn: conn, user: user} do
Tesla.Mock.mock(fn env -> apply(HttpRequestMock, :request, [env]) end)
- {:ok, activity} =
- CommonAPI.post(user, %{"status" => "https://example.com/ogp-missing-data"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "https://example.com/ogp-missing-data"})
response =
conn
|> get("/api/v1/statuses/#{activity.id}/card")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert response == %{
"type" => "link",
@@ -1063,36 +1181,42 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
%{conn: conn} = oauth_access(["write:bookmarks", "read:bookmarks"])
author = insert(:user)
- {:ok, activity1} =
- CommonAPI.post(author, %{
- "status" => "heweoo?"
- })
+ {:ok, activity1} = CommonAPI.post(author, %{status: "heweoo?"})
+ {:ok, activity2} = CommonAPI.post(author, %{status: "heweoo!"})
- {:ok, activity2} =
- CommonAPI.post(author, %{
- "status" => "heweoo!"
- })
-
- response1 = post(conn, "/api/v1/statuses/#{activity1.id}/bookmark")
+ response1 =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{activity1.id}/bookmark")
- assert json_response(response1, 200)["bookmarked"] == true
+ assert json_response_and_validate_schema(response1, 200)["bookmarked"] == true
- response2 = post(conn, "/api/v1/statuses/#{activity2.id}/bookmark")
+ response2 =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{activity2.id}/bookmark")
- assert json_response(response2, 200)["bookmarked"] == true
+ assert json_response_and_validate_schema(response2, 200)["bookmarked"] == true
bookmarks = get(conn, bookmarks_uri)
- assert [json_response(response2, 200), json_response(response1, 200)] ==
- json_response(bookmarks, 200)
+ assert [
+ json_response_and_validate_schema(response2, 200),
+ json_response_and_validate_schema(response1, 200)
+ ] ==
+ json_response_and_validate_schema(bookmarks, 200)
- response1 = post(conn, "/api/v1/statuses/#{activity1.id}/unbookmark")
+ response1 =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{activity1.id}/unbookmark")
- assert json_response(response1, 200)["bookmarked"] == false
+ assert json_response_and_validate_schema(response1, 200)["bookmarked"] == false
bookmarks = get(conn, bookmarks_uri)
- assert [json_response(response2, 200)] == json_response(bookmarks, 200)
+ assert [json_response_and_validate_schema(response2, 200)] ==
+ json_response_and_validate_schema(bookmarks, 200)
end
describe "conversation muting" do
@@ -1100,7 +1224,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
setup do
post_user = insert(:user)
- {:ok, activity} = CommonAPI.post(post_user, %{"status" => "HIE"})
+ {:ok, activity} = CommonAPI.post(post_user, %{status: "HIE"})
%{activity: activity}
end
@@ -1109,16 +1233,22 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
assert %{"id" => ^id_str, "muted" => true} =
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/statuses/#{activity.id}/mute")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
end
test "cannot mute already muted conversation", %{conn: conn, user: user, activity: activity} do
{:ok, _} = CommonAPI.add_mute(user, activity)
- conn = post(conn, "/api/v1/statuses/#{activity.id}/mute")
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/statuses/#{activity.id}/mute")
- assert json_response(conn, 400) == %{"error" => "conversation is already muted"}
+ assert json_response_and_validate_schema(conn, 400) == %{
+ "error" => "conversation is already muted"
+ }
end
test "unmute conversation", %{conn: conn, user: user, activity: activity} do
@@ -1130,7 +1260,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
conn
# |> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/unmute")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
end
end
@@ -1139,16 +1269,17 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
user2 = insert(:user)
user3 = insert(:user)
- {:ok, replied_to} = CommonAPI.post(user1, %{"status" => "cofe"})
+ {:ok, replied_to} = CommonAPI.post(user1, %{status: "cofe"})
# Reply to status from another user
conn1 =
conn
|> assign(:user, user2)
|> assign(:token, insert(:oauth_token, user: user2, scopes: ["write:statuses"]))
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => replied_to.id})
- assert %{"content" => "xD", "id" => id} = json_response(conn1, 200)
+ assert %{"content" => "xD", "id" => id} = json_response_and_validate_schema(conn1, 200)
activity = Activity.get_by_id_with_object(id)
@@ -1160,10 +1291,11 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
conn
|> assign(:user, user3)
|> assign(:token, insert(:oauth_token, user: user3, scopes: ["write:statuses"]))
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/statuses/#{activity.id}/reblog")
assert %{"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}} =
- json_response(conn2, 200)
+ json_response_and_validate_schema(conn2, 200)
assert to_string(activity.id) == id
@@ -1186,7 +1318,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
setup do: oauth_access(["read:accounts"])
setup %{user: user} do
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test"})
%{activity: activity}
end
@@ -1198,7 +1330,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
response =
conn
|> get("/api/v1/statuses/#{activity.id}/favourited_by")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
[%{"id" => id}] = response
@@ -1212,7 +1344,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
response =
conn
|> get("/api/v1/statuses/#{activity.id}/favourited_by")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert Enum.empty?(response)
end
@@ -1229,7 +1361,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
response =
conn
|> get("/api/v1/statuses/#{activity.id}/favourited_by")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert Enum.empty?(response)
end
@@ -1241,7 +1373,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
response =
build_conn()
|> get("/api/v1/statuses/#{activity.id}/favourited_by")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
[%{"id" => id}] = response
assert id == other_user.id
@@ -1252,8 +1384,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "@#{other_user.nickname} wanna get some #cofe together?",
- "visibility" => "direct"
+ status: "@#{other_user.nickname} wanna get some #cofe together?",
+ visibility: "direct"
})
{:ok, _} = CommonAPI.favorite(other_user, activity.id)
@@ -1262,7 +1394,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
build_conn()
|> get(favourited_by_url)
- |> json_response(404)
+ |> json_response_and_validate_schema(404)
conn =
build_conn()
@@ -1272,12 +1404,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
conn
|> assign(:token, nil)
|> get(favourited_by_url)
- |> json_response(404)
+ |> json_response_and_validate_schema(404)
response =
conn
|> get(favourited_by_url)
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
[%{"id" => id}] = response
assert id == other_user.id
@@ -1288,7 +1420,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
setup do: oauth_access(["read:accounts"])
setup %{user: user} do
- {:ok, activity} = CommonAPI.post(user, %{"status" => "test"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "test"})
%{activity: activity}
end
@@ -1300,7 +1432,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
response =
conn
|> get("/api/v1/statuses/#{activity.id}/reblogged_by")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
[%{"id" => id}] = response
@@ -1314,7 +1446,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
response =
conn
|> get("/api/v1/statuses/#{activity.id}/reblogged_by")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert Enum.empty?(response)
end
@@ -1331,7 +1463,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
response =
conn
|> get("/api/v1/statuses/#{activity.id}/reblogged_by")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert Enum.empty?(response)
end
@@ -1342,12 +1474,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
} do
other_user = insert(:user)
- {:ok, _, _} = CommonAPI.repeat(activity.id, other_user, %{"visibility" => "private"})
+ {:ok, _, _} = CommonAPI.repeat(activity.id, other_user, %{visibility: "private"})
response =
conn
|> get("/api/v1/statuses/#{activity.id}/reblogged_by")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert Enum.empty?(response)
end
@@ -1359,7 +1491,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
response =
build_conn()
|> get("/api/v1/statuses/#{activity.id}/reblogged_by")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
[%{"id" => id}] = response
assert id == other_user.id
@@ -1370,20 +1502,20 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "@#{other_user.nickname} wanna get some #cofe together?",
- "visibility" => "direct"
+ status: "@#{other_user.nickname} wanna get some #cofe together?",
+ visibility: "direct"
})
build_conn()
|> get("/api/v1/statuses/#{activity.id}/reblogged_by")
- |> json_response(404)
+ |> json_response_and_validate_schema(404)
response =
build_conn()
|> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"]))
|> get("/api/v1/statuses/#{activity.id}/reblogged_by")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert [] == response
end
@@ -1392,16 +1524,16 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "context" do
user = insert(:user)
- {:ok, %{id: id1}} = CommonAPI.post(user, %{"status" => "1"})
- {:ok, %{id: id2}} = CommonAPI.post(user, %{"status" => "2", "in_reply_to_status_id" => id1})
- {:ok, %{id: id3}} = CommonAPI.post(user, %{"status" => "3", "in_reply_to_status_id" => id2})
- {:ok, %{id: id4}} = CommonAPI.post(user, %{"status" => "4", "in_reply_to_status_id" => id3})
- {:ok, %{id: id5}} = CommonAPI.post(user, %{"status" => "5", "in_reply_to_status_id" => id4})
+ {:ok, %{id: id1}} = CommonAPI.post(user, %{status: "1"})
+ {:ok, %{id: id2}} = CommonAPI.post(user, %{status: "2", in_reply_to_status_id: id1})
+ {:ok, %{id: id3}} = CommonAPI.post(user, %{status: "3", in_reply_to_status_id: id2})
+ {:ok, %{id: id4}} = CommonAPI.post(user, %{status: "4", in_reply_to_status_id: id3})
+ {:ok, %{id: id5}} = CommonAPI.post(user, %{status: "5", in_reply_to_status_id: id4})
response =
build_conn()
|> get("/api/v1/statuses/#{id3}/context")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert %{
"ancestors" => [%{"id" => ^id1}, %{"id" => ^id2}],
@@ -1413,14 +1545,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
%{user: user, conn: conn} = oauth_access(["read:favourites"])
other_user = insert(:user)
- {:ok, _} = CommonAPI.post(other_user, %{"status" => "bla"})
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "traps are happy"})
+ {:ok, _} = CommonAPI.post(other_user, %{status: "bla"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "traps are happy"})
{:ok, _} = CommonAPI.favorite(user, activity.id)
first_conn = get(conn, "/api/v1/favourites")
- assert [status] = json_response(first_conn, 200)
+ assert [status] = json_response_and_validate_schema(first_conn, 200)
assert status["id"] == to_string(activity.id)
assert [{"link", _link_header}] =
@@ -1429,8 +1561,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
# Honours query params
{:ok, second_activity} =
CommonAPI.post(other_user, %{
- "status" =>
- "Trees Are Never Sad Look At Them Every Once In Awhile They're Quite Beautiful."
+ status: "Trees Are Never Sad Look At Them Every Once In Awhile They're Quite Beautiful."
})
{:ok, _} = CommonAPI.favorite(user, second_activity.id)
@@ -1439,17 +1570,17 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
second_conn = get(conn, "/api/v1/favourites?since_id=#{last_like}")
- assert [second_status] = json_response(second_conn, 200)
+ assert [second_status] = json_response_and_validate_schema(second_conn, 200)
assert second_status["id"] == to_string(second_activity.id)
third_conn = get(conn, "/api/v1/favourites?limit=0")
- assert [] = json_response(third_conn, 200)
+ assert [] = json_response_and_validate_schema(third_conn, 200)
end
test "expires_at is nil for another user" do
%{conn: conn, user: user} = oauth_access(["read:statuses"])
- {:ok, activity} = CommonAPI.post(user, %{"status" => "foobar", "expires_in" => 1_000_000})
+ {:ok, activity} = CommonAPI.post(user, %{status: "foobar", expires_in: 1_000_000})
expires_at =
activity.id
@@ -1458,11 +1589,15 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
|> NaiveDateTime.to_iso8601()
assert %{"pleroma" => %{"expires_at" => ^expires_at}} =
- conn |> get("/api/v1/statuses/#{activity.id}") |> json_response(:ok)
+ conn
+ |> get("/api/v1/statuses/#{activity.id}")
+ |> json_response_and_validate_schema(:ok)
%{conn: conn} = oauth_access(["read:statuses"])
assert %{"pleroma" => %{"expires_at" => nil}} =
- conn |> get("/api/v1/statuses/#{activity.id}") |> json_response(:ok)
+ conn
+ |> get("/api/v1/statuses/#{activity.id}")
+ |> json_response_and_validate_schema(:ok)
end
end
diff --git a/test/web/mastodon_api/controllers/timeline_controller_test.exs b/test/web/mastodon_api/controllers/timeline_controller_test.exs
index 06efdc901..6d8f81b75 100644
--- a/test/web/mastodon_api/controllers/timeline_controller_test.exs
+++ b/test/web/mastodon_api/controllers/timeline_controller_test.exs
@@ -28,7 +28,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
other_user = insert(:user)
- {:ok, _} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
+ {:ok, _} = CommonAPI.post(other_user, %{status: "hi @#{user.nickname}"})
response =
conn
@@ -47,8 +47,8 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
following = insert(:user, nickname: "followed")
third_user = insert(:user, nickname: "repeated")
- {:ok, _activity} = CommonAPI.post(following, %{"status" => "post"})
- {:ok, activity} = CommonAPI.post(third_user, %{"status" => "repeated post"})
+ {:ok, _activity} = CommonAPI.post(following, %{status: "post"})
+ {:ok, activity} = CommonAPI.post(third_user, %{status: "repeated post"})
{:ok, _, _} = CommonAPI.repeat(activity.id, following)
ret_conn = get(conn, uri)
@@ -108,14 +108,12 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
end
test "the home timeline when the direct messages are excluded", %{user: user, conn: conn} do
- {:ok, public_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "public"})
- {:ok, direct_activity} = CommonAPI.post(user, %{"status" => ".", "visibility" => "direct"})
+ {:ok, public_activity} = CommonAPI.post(user, %{status: ".", visibility: "public"})
+ {:ok, direct_activity} = CommonAPI.post(user, %{status: ".", visibility: "direct"})
- {:ok, unlisted_activity} =
- CommonAPI.post(user, %{"status" => ".", "visibility" => "unlisted"})
+ {:ok, unlisted_activity} = CommonAPI.post(user, %{status: ".", visibility: "unlisted"})
- {:ok, private_activity} =
- CommonAPI.post(user, %{"status" => ".", "visibility" => "private"})
+ {:ok, private_activity} = CommonAPI.post(user, %{status: ".", visibility: "private"})
conn = get(conn, "/api/v1/timelines/home", %{"exclude_visibilities" => ["direct"]})
@@ -132,7 +130,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
test "the public timeline", %{conn: conn} do
following = insert(:user)
- {:ok, _activity} = CommonAPI.post(following, %{"status" => "test"})
+ {:ok, _activity} = CommonAPI.post(following, %{status: "test"})
_activity = insert(:note_activity, local: false)
@@ -152,10 +150,10 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
test "the public timeline includes only public statuses for an authenticated user" do
%{user: user, conn: conn} = oauth_access(["read:statuses"])
- {:ok, _activity} = CommonAPI.post(user, %{"status" => "test"})
- {:ok, _activity} = CommonAPI.post(user, %{"status" => "test", "visibility" => "private"})
- {:ok, _activity} = CommonAPI.post(user, %{"status" => "test", "visibility" => "unlisted"})
- {:ok, _activity} = CommonAPI.post(user, %{"status" => "test", "visibility" => "direct"})
+ {:ok, _activity} = CommonAPI.post(user, %{status: "test"})
+ {:ok, _activity} = CommonAPI.post(user, %{status: "test", visibility: "private"})
+ {:ok, _activity} = CommonAPI.post(user, %{status: "test", visibility: "unlisted"})
+ {:ok, _activity} = CommonAPI.post(user, %{status: "test", visibility: "direct"})
res_conn = get(conn, "/api/v1/timelines/public")
assert length(json_response(res_conn, 200)) == 1
@@ -263,14 +261,14 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
{:ok, direct} =
CommonAPI.post(user_one, %{
- "status" => "Hi @#{user_two.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{user_two.nickname}!",
+ visibility: "direct"
})
{:ok, _follower_only} =
CommonAPI.post(user_one, %{
- "status" => "Hi @#{user_two.nickname}!",
- "visibility" => "private"
+ status: "Hi @#{user_two.nickname}!",
+ visibility: "private"
})
conn_user_two =
@@ -306,8 +304,8 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
Enum.each(1..20, fn _ ->
{:ok, _} =
CommonAPI.post(user_one, %{
- "status" => "Hi @#{user_two.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{user_two.nickname}!",
+ visibility: "direct"
})
end)
@@ -332,14 +330,14 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
{:ok, _blocked_direct} =
CommonAPI.post(blocked, %{
- "status" => "Hi @#{blocker.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{blocker.nickname}!",
+ visibility: "direct"
})
{:ok, direct} =
CommonAPI.post(other_user, %{
- "status" => "Hi @#{blocker.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{blocker.nickname}!",
+ visibility: "direct"
})
res_conn = get(conn, "api/v1/timelines/direct")
@@ -354,8 +352,8 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
test "list timeline", %{user: user, conn: conn} do
other_user = insert(:user)
- {:ok, _activity_one} = CommonAPI.post(user, %{"status" => "Marisa is cute."})
- {:ok, activity_two} = CommonAPI.post(other_user, %{"status" => "Marisa is cute."})
+ {:ok, _activity_one} = CommonAPI.post(user, %{status: "Marisa is cute."})
+ {:ok, activity_two} = CommonAPI.post(other_user, %{status: "Marisa is cute."})
{:ok, list} = Pleroma.List.create("name", user)
{:ok, list} = Pleroma.List.follow(list, other_user)
@@ -371,12 +369,12 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
conn: conn
} do
other_user = insert(:user)
- {:ok, activity_one} = CommonAPI.post(other_user, %{"status" => "Marisa is cute."})
+ {:ok, activity_one} = CommonAPI.post(other_user, %{status: "Marisa is cute."})
{:ok, _activity_two} =
CommonAPI.post(other_user, %{
- "status" => "Marisa is cute.",
- "visibility" => "private"
+ status: "Marisa is cute.",
+ visibility: "private"
})
{:ok, list} = Pleroma.List.create("name", user)
@@ -397,7 +395,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
test "hashtag timeline", %{conn: conn} do
following = insert(:user)
- {:ok, activity} = CommonAPI.post(following, %{"status" => "test #2hu"})
+ {:ok, activity} = CommonAPI.post(following, %{status: "test #2hu"})
nconn = get(conn, "/api/v1/timelines/tag/2hu")
@@ -416,9 +414,9 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
test "multi-hashtag timeline", %{conn: conn} do
user = insert(:user)
- {:ok, activity_test} = CommonAPI.post(user, %{"status" => "#test"})
- {:ok, activity_test1} = CommonAPI.post(user, %{"status" => "#test #test1"})
- {:ok, activity_none} = CommonAPI.post(user, %{"status" => "#test #none"})
+ {:ok, activity_test} = CommonAPI.post(user, %{status: "#test"})
+ {:ok, activity_test1} = CommonAPI.post(user, %{status: "#test #test1"})
+ {:ok, activity_none} = CommonAPI.post(user, %{status: "#test #none"})
any_test = get(conn, "/api/v1/timelines/tag/test", %{"any" => ["test1"]})
diff --git a/test/web/mastodon_api/mastodon_api_test.exs b/test/web/mastodon_api/mastodon_api_test.exs
index cb971806a..a7f9c5205 100644
--- a/test/web/mastodon_api/mastodon_api_test.exs
+++ b/test/web/mastodon_api/mastodon_api_test.exs
@@ -75,9 +75,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPITest do
User.subscribe(subscriber, user)
- {:ok, status} = CommonAPI.post(user, %{"status" => "Akariiiin"})
+ {:ok, status} = CommonAPI.post(user, %{status: "Akariiiin"})
- {:ok, status1} = CommonAPI.post(user, %{"status" => "Magi"})
+ {:ok, status1} = CommonAPI.post(user, %{status: "Magi"})
{:ok, [notification]} = Notification.create_notifications(status)
{:ok, [notification1]} = Notification.create_notifications(status1)
res = MastodonAPI.get_notifications(subscriber)
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index 375f0103a..69ddbb5d4 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -93,7 +93,14 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
test "Represent the user account for the account owner" do
user = insert(:user)
- notification_settings = %Pleroma.User.NotificationSetting{}
+ notification_settings = %{
+ followers: true,
+ follows: true,
+ non_followers: true,
+ non_follows: true,
+ privacy_option: false
+ }
+
privacy = user.default_scope
assert %{
@@ -452,8 +459,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
{:ok, _activity} =
CommonAPI.post(other_user, %{
- "status" => "Hey @#{user.nickname}.",
- "visibility" => "direct"
+ status: "Hey @#{user.nickname}.",
+ visibility: "direct"
})
user = User.get_cached_by_ap_id(user.ap_id)
diff --git a/test/web/mastodon_api/views/conversation_view_test.exs b/test/web/mastodon_api/views/conversation_view_test.exs
index dbf3c51e2..6f84366f8 100644
--- a/test/web/mastodon_api/views/conversation_view_test.exs
+++ b/test/web/mastodon_api/views/conversation_view_test.exs
@@ -16,7 +16,7 @@ defmodule Pleroma.Web.MastodonAPI.ConversationViewTest do
other_user = insert(:user)
{:ok, activity} =
- CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "hey @#{other_user.nickname}", visibility: "direct"})
[participation] = Participation.for_user_with_last_activity_id(user)
diff --git a/test/web/mastodon_api/views/notification_view_test.exs b/test/web/mastodon_api/views/notification_view_test.exs
index 0806269a2..04a774d17 100644
--- a/test/web/mastodon_api/views/notification_view_test.exs
+++ b/test/web/mastodon_api/views/notification_view_test.exs
@@ -34,7 +34,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
test "Mention notification" do
user = insert(:user)
mentioned_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{mentioned_user.nickname}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey @#{mentioned_user.nickname}"})
{:ok, [notification]} = Notification.create_notifications(activity)
user = User.get_cached_by_id(user.id)
@@ -53,7 +53,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
test "Favourite notification" do
user = insert(:user)
another_user = insert(:user)
- {:ok, create_activity} = CommonAPI.post(user, %{"status" => "hey"})
+ {:ok, create_activity} = CommonAPI.post(user, %{status: "hey"})
{:ok, favorite_activity} = CommonAPI.favorite(another_user, create_activity.id)
{:ok, [notification]} = Notification.create_notifications(favorite_activity)
create_activity = Activity.get_by_id(create_activity.id)
@@ -73,7 +73,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
test "Reblog notification" do
user = insert(:user)
another_user = insert(:user)
- {:ok, create_activity} = CommonAPI.post(user, %{"status" => "hey"})
+ {:ok, create_activity} = CommonAPI.post(user, %{status: "hey"})
{:ok, reblog_activity, _object} = CommonAPI.repeat(create_activity.id, another_user)
{:ok, [notification]} = Notification.create_notifications(reblog_activity)
reblog_activity = Activity.get_by_id(create_activity.id)
@@ -155,7 +155,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
{:ok, _activity} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
activity = Repo.get(Activity, activity.id)
diff --git a/test/web/mastodon_api/views/poll_view_test.exs b/test/web/mastodon_api/views/poll_view_test.exs
index 63b204387..76672f36c 100644
--- a/test/web/mastodon_api/views/poll_view_test.exs
+++ b/test/web/mastodon_api/views/poll_view_test.exs
@@ -22,10 +22,10 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "Is Tenshi eating a corndog cute?",
- "poll" => %{
- "options" => ["absolutely!", "sure", "yes", "why are you even asking?"],
- "expires_in" => 20
+ status: "Is Tenshi eating a corndog cute?",
+ poll: %{
+ options: ["absolutely!", "sure", "yes", "why are you even asking?"],
+ expires_in: 20
}
})
@@ -62,11 +62,11 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "Which Mastodon developer is your favourite?",
- "poll" => %{
- "options" => ["Gargron", "Eugen"],
- "expires_in" => 20,
- "multiple" => true
+ status: "Which Mastodon developer is your favourite?",
+ poll: %{
+ options: ["Gargron", "Eugen"],
+ expires_in: 20,
+ multiple: true
}
})
@@ -91,10 +91,10 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "What's with the smug face?",
- "poll" => %{
- "options" => [":blank: sip", ":blank::blank: sip", ":blank::blank::blank: sip"],
- "expires_in" => 20
+ status: "What's with the smug face?",
+ poll: %{
+ options: [":blank: sip", ":blank::blank: sip", ":blank::blank::blank: sip"],
+ expires_in: 20
}
})
@@ -109,11 +109,11 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "Which input devices do you use?",
- "poll" => %{
- "options" => ["mouse", "trackball", "trackpoint"],
- "multiple" => true,
- "expires_in" => 20
+ status: "Which input devices do you use?",
+ poll: %{
+ options: ["mouse", "trackball", "trackpoint"],
+ multiple: true,
+ expires_in: 20
}
})
diff --git a/test/web/mastodon_api/views/scheduled_activity_view_test.exs b/test/web/mastodon_api/views/scheduled_activity_view_test.exs
index 0c0987593..fbfd873ef 100644
--- a/test/web/mastodon_api/views/scheduled_activity_view_test.exs
+++ b/test/web/mastodon_api/views/scheduled_activity_view_test.exs
@@ -14,7 +14,7 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityViewTest do
test "A scheduled activity with a media attachment" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hi"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hi"})
scheduled_at =
NaiveDateTime.utc_now()
@@ -47,7 +47,7 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityViewTest do
expected = %{
id: to_string(scheduled_activity.id),
media_attachments:
- %{"media_ids" => [upload.id]}
+ %{media_ids: [upload.id]}
|> Utils.attachments_from_ids()
|> Enum.map(&StatusView.render("attachment.json", %{attachment: &1})),
params: %{
diff --git a/test/web/mastodon_api/views/status_view_test.exs b/test/web/mastodon_api/views/status_view_test.exs
index b5e7dc317..ffad65b01 100644
--- a/test/web/mastodon_api/views/status_view_test.exs
+++ b/test/web/mastodon_api/views/status_view_test.exs
@@ -20,6 +20,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
import Pleroma.Factory
import Tesla.Mock
+ import OpenApiSpex.TestAssertions
setup do
mock(fn env -> apply(HttpRequestMock, :request, [env]) end)
@@ -30,7 +31,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
user = insert(:user)
other_user = insert(:user)
third_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "dae cofe??"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "dae cofe??"})
{:ok, _} = CommonAPI.react_with_emoji(activity.id, user, "☕")
{:ok, _} = CommonAPI.react_with_emoji(activity.id, third_user, "🍵")
@@ -38,6 +39,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
activity = Repo.get(Activity, activity.id)
status = StatusView.render("show.json", activity: activity)
+ assert_schema(status, "Status", Pleroma.Web.ApiSpec.spec())
+
assert status[:pleroma][:emoji_reactions] == [
%{name: "☕", count: 2, me: false},
%{name: "🍵", count: 1, me: false}
@@ -45,6 +48,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
status = StatusView.render("show.json", activity: activity, for: user)
+ assert_schema(status, "Status", Pleroma.Web.ApiSpec.spec())
+
assert status[:pleroma][:emoji_reactions] == [
%{name: "☕", count: 2, me: true},
%{name: "🍵", count: 1, me: false}
@@ -54,7 +59,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
test "loads and returns the direct conversation id when given the `with_direct_conversation_id` option" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Hey @shp!", "visibility" => "direct"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "Hey @shp!", visibility: "direct"})
[participation] = Participation.for_user(user)
status =
@@ -68,12 +73,13 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
status = StatusView.render("show.json", activity: activity, for: user)
assert status[:pleroma][:direct_conversation_id] == nil
+ assert_schema(status, "Status", Pleroma.Web.ApiSpec.spec())
end
test "returns the direct conversation id when given the `direct_conversation_id` option" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Hey @shp!", "visibility" => "direct"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "Hey @shp!", visibility: "direct"})
[participation] = Participation.for_user(user)
status =
@@ -84,12 +90,13 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
)
assert status[:pleroma][:direct_conversation_id] == participation.id
+ assert_schema(status, "Status", Pleroma.Web.ApiSpec.spec())
end
test "returns a temporary ap_id based user for activities missing db users" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Hey @shp!", "visibility" => "direct"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "Hey @shp!", visibility: "direct"})
Repo.delete(user)
Cachex.clear(:user_cache)
@@ -119,7 +126,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
test "tries to get a user by nickname if fetching by ap_id doesn't work" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Hey @shp!", "visibility" => "direct"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "Hey @shp!", visibility: "direct"})
{:ok, user} =
user
@@ -131,6 +138,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
result = StatusView.render("show.json", activity: activity)
assert result[:account][:id] == to_string(user.id)
+ assert_schema(result, "Status", Pleroma.Web.ApiSpec.spec())
end
test "a note with null content" do
@@ -149,6 +157,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
status = StatusView.render("show.json", %{activity: note})
assert status.content == ""
+ assert_schema(status, "Status", Pleroma.Web.ApiSpec.spec())
end
test "a note activity" do
@@ -222,6 +231,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
}
assert status == expected
+ assert_schema(status, "Status", Pleroma.Web.ApiSpec.spec())
end
test "tells if the message is muted for some reason" do
@@ -230,13 +240,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
{:ok, _user_relationships} = User.mute(user, other_user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "test"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "test"})
relationships_opt = UserRelationship.view_relationships_option(user, [other_user])
opts = %{activity: activity}
status = StatusView.render("show.json", opts)
assert status.muted == false
+ assert_schema(status, "Status", Pleroma.Web.ApiSpec.spec())
status = StatusView.render("show.json", Map.put(opts, :relationships, relationships_opt))
assert status.muted == false
@@ -247,6 +258,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
status = StatusView.render("show.json", Map.put(for_opts, :relationships, relationships_opt))
assert status.muted == true
+ assert_schema(status, "Status", Pleroma.Web.ApiSpec.spec())
end
test "tells if the message is thread muted" do
@@ -255,7 +267,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
{:ok, _user_relationships} = User.mute(user, other_user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "test"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "test"})
status = StatusView.render("show.json", %{activity: activity, for: user})
assert status.pleroma.thread_muted == false
@@ -270,7 +282,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
test "tells if the status is bookmarked" do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Cute girls doing cute things"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "Cute girls doing cute things"})
status = StatusView.render("show.json", %{activity: activity})
assert status.bookmarked == false
@@ -292,8 +304,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
note = insert(:note_activity)
user = insert(:user)
- {:ok, activity} =
- CommonAPI.post(user, %{"status" => "he", "in_reply_to_status_id" => note.id})
+ {:ok, activity} = CommonAPI.post(user, %{status: "he", in_reply_to_status_id: note.id})
status = StatusView.render("show.json", %{activity: activity})
@@ -308,12 +319,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
user = insert(:user)
mentioned = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hi @#{mentioned.nickname}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hi @#{mentioned.nickname}"})
status = StatusView.render("show.json", %{activity: activity})
assert status.mentions ==
Enum.map([mentioned], fn u -> AccountView.render("mention.json", %{user: u}) end)
+
+ assert_schema(status, "Status", Pleroma.Web.ApiSpec.spec())
end
test "create mentions from the 'to' field" do
@@ -405,14 +418,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
api_spec = Pleroma.Web.ApiSpec.spec()
assert expected == StatusView.render("attachment.json", %{attachment: object})
- OpenApiSpex.TestAssertions.assert_schema(expected, "Attachment", api_spec)
+ assert_schema(expected, "Attachment", api_spec)
# If theres a "id", use that instead of the generated one
object = Map.put(object, "id", 2)
result = StatusView.render("attachment.json", %{attachment: object})
assert %{id: "2"} = result
- OpenApiSpex.TestAssertions.assert_schema(result, "Attachment", api_spec)
+ assert_schema(result, "Attachment", api_spec)
end
test "put the url advertised in the Activity in to the url attribute" do
@@ -436,6 +449,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
assert represented[:id] == to_string(reblog.id)
assert represented[:reblog][:id] == to_string(activity.id)
assert represented[:emojis] == []
+ assert_schema(represented, "Status", Pleroma.Web.ApiSpec.spec())
end
test "a peertube video" do
@@ -452,6 +466,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
assert represented[:id] == to_string(activity.id)
assert length(represented[:media_attachments]) == 1
+ assert_schema(represented, "Status", Pleroma.Web.ApiSpec.spec())
end
test "funkwhale audio" do
@@ -567,13 +582,15 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "drink more water"
+ status: "drink more water"
})
result = StatusView.render("show.json", %{activity: activity, for: other_user})
assert result[:account][:pleroma][:relationship] ==
AccountView.render("relationship.json", %{user: other_user, target: user})
+
+ assert_schema(result, "Status", Pleroma.Web.ApiSpec.spec())
end
test "embeds a relationship in the account in reposts" do
@@ -582,7 +599,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "˙˙ɐʎns"
+ status: "˙˙ɐʎns"
})
{:ok, activity, _object} = CommonAPI.repeat(activity.id, other_user)
@@ -594,6 +611,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
assert result[:reblog][:account][:pleroma][:relationship] ==
AccountView.render("relationship.json", %{user: user, target: user})
+
+ assert_schema(result, "Status", Pleroma.Web.ApiSpec.spec())
end
test "visibility/list" do
@@ -601,8 +620,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
{:ok, list} = Pleroma.List.create("foo", user)
- {:ok, activity} =
- CommonAPI.post(user, %{"status" => "foobar", "visibility" => "list:#{list.id}"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "foobar", visibility: "list:#{list.id}"})
status = StatusView.render("show.json", activity: activity)
@@ -616,5 +634,6 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
assert status.length == listen_activity.data["object"]["length"]
assert status.title == listen_activity.data["object"]["title"]
+ assert_schema(status, "Status", Pleroma.Web.ApiSpec.spec())
end
end
diff --git a/test/web/metadata/twitter_card_test.exs b/test/web/metadata/twitter_card_test.exs
index 9e9c6853a..10931b5ba 100644
--- a/test/web/metadata/twitter_card_test.exs
+++ b/test/web/metadata/twitter_card_test.exs
@@ -30,7 +30,7 @@ defmodule Pleroma.Web.Metadata.Providers.TwitterCardTest do
test "it uses summary twittercard if post has no attachment" do
user = insert(:user, name: "Jimmy Hendriks", bio: "born 19 March 1994")
- {:ok, activity} = CommonAPI.post(user, %{"status" => "HI"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "HI"})
note =
insert(:note, %{
@@ -56,7 +56,7 @@ defmodule Pleroma.Web.Metadata.Providers.TwitterCardTest do
test "it renders avatar not attachment if post is nsfw and unfurl_nsfw is disabled" do
Pleroma.Config.put([Pleroma.Web.Metadata, :unfurl_nsfw], false)
user = insert(:user, name: "Jimmy Hendriks", bio: "born 19 March 1994")
- {:ok, activity} = CommonAPI.post(user, %{"status" => "HI"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "HI"})
note =
insert(:note, %{
@@ -100,7 +100,7 @@ defmodule Pleroma.Web.Metadata.Providers.TwitterCardTest do
test "it renders supported types of attachments and skips unknown types" do
user = insert(:user, name: "Jimmy Hendriks", bio: "born 19 March 1994")
- {:ok, activity} = CommonAPI.post(user, %{"status" => "HI"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "HI"})
note =
insert(:note, %{
diff --git a/test/web/pleroma_api/controllers/account_controller_test.exs b/test/web/pleroma_api/controllers/account_controller_test.exs
index 6b671a667..34fc4aa23 100644
--- a/test/web/pleroma_api/controllers/account_controller_test.exs
+++ b/test/web/pleroma_api/controllers/account_controller_test.exs
@@ -171,8 +171,8 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
} do
{:ok, direct} =
CommonAPI.post(current_user, %{
- "status" => "Hi @#{user.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{user.nickname}!",
+ visibility: "direct"
})
CommonAPI.favorite(user, direct.id)
@@ -204,8 +204,8 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
{:ok, direct} =
CommonAPI.post(user_two, %{
- "status" => "Hi @#{user.nickname}!",
- "visibility" => "direct"
+ status: "Hi @#{user.nickname}!",
+ visibility: "direct"
})
CommonAPI.favorite(user, direct.id)
diff --git a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
index 43f1b154d..cfd1dbd24 100644
--- a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
@@ -20,7 +20,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
result =
conn
@@ -42,7 +42,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
{:ok, _reaction_activity} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
ObanHelpers.perform_all()
@@ -68,7 +68,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
other_user = insert(:user)
doomed_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
result =
conn
@@ -106,7 +106,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
result =
conn
@@ -133,7 +133,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
%{user: other_user, conn: conn} = oauth_access(["read:statuses"])
{:ok, _activity} =
- CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}!", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}!", visibility: "direct"})
[participation] = Participation.for_user(other_user)
@@ -151,18 +151,18 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
third_user = insert(:user)
{:ok, _activity} =
- CommonAPI.post(user, %{"status" => "Hi @#{third_user.nickname}!", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "Hi @#{third_user.nickname}!", visibility: "direct"})
{:ok, activity} =
- CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}!", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}!", visibility: "direct"})
[participation] = Participation.for_user(other_user)
{:ok, activity_two} =
CommonAPI.post(other_user, %{
- "status" => "Hi!",
- "in_reply_to_status_id" => activity.id,
- "in_reply_to_conversation_id" => participation.id
+ status: "Hi!",
+ in_reply_to_status_id: activity.id,
+ in_reply_to_conversation_id: participation.id
})
result =
@@ -178,9 +178,9 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
{:ok, %{id: id_three}} =
CommonAPI.post(other_user, %{
- "status" => "Bye!",
- "in_reply_to_status_id" => activity.id,
- "in_reply_to_conversation_id" => participation.id
+ status: "Bye!",
+ in_reply_to_status_id: activity.id,
+ in_reply_to_conversation_id: participation.id
})
assert [%{"id" => ^id_two}, %{"id" => ^id_three}] =
@@ -198,7 +198,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
%{user: user, conn: conn} = oauth_access(["write:conversations"])
other_user = insert(:user)
- {:ok, _activity} = CommonAPI.post(user, %{"status" => "Hi", "visibility" => "direct"})
+ {:ok, _activity} = CommonAPI.post(user, %{status: "Hi", visibility: "direct"})
[participation] = Participation.for_user(user)
@@ -229,10 +229,10 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
%{user: other_user, conn: conn} = oauth_access(["write:conversations"])
{:ok, _activity} =
- CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}", visibility: "direct"})
{:ok, _activity} =
- CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}", "visibility" => "direct"})
+ CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}", visibility: "direct"})
[participation2, participation1] = Participation.for_user(other_user)
assert Participation.get(participation2.id).read == false
@@ -255,8 +255,8 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
test "it marks a single notification as read", %{user: user1, conn: conn} do
user2 = insert(:user)
- {:ok, activity1} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"})
- {:ok, activity2} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"})
+ {:ok, activity1} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
+ {:ok, activity2} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
{:ok, [notification1]} = Notification.create_notifications(activity1)
{:ok, [notification2]} = Notification.create_notifications(activity2)
@@ -272,9 +272,9 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
test "it marks multiple notifications as read", %{user: user1, conn: conn} do
user2 = insert(:user)
- {:ok, _activity1} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"})
- {:ok, _activity2} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"})
- {:ok, _activity3} = CommonAPI.post(user2, %{"status" => "HIE @#{user1.nickname}"})
+ {:ok, _activity1} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
+ {:ok, _activity2} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
+ {:ok, _activity3} = CommonAPI.post(user2, %{status: "HIE @#{user1.nickname}"})
[notification3, notification2, notification1] = Notification.for_user(user1, %{limit: 3})
diff --git a/test/web/push/impl_test.exs b/test/web/push/impl_test.exs
index b855d72ba..2fc3e73b5 100644
--- a/test/web/push/impl_test.exs
+++ b/test/web/push/impl_test.exs
@@ -55,7 +55,7 @@ defmodule Pleroma.Web.Push.ImplTest do
data: %{alerts: %{"follow" => true, "mention" => false}}
)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "
+ status:
"Lorem ipsum dolor sit amet, consectetur :firefox: adipiscing elit. Fusce sagittis finibus turpis."
})
@@ -147,7 +147,7 @@ defmodule Pleroma.Web.Push.ImplTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" =>
+ status:
"Lorem ipsum dolor sit amet, consectetur :firefox: adipiscing elit. Fusce sagittis finibus turpis."
})
@@ -166,7 +166,7 @@ defmodule Pleroma.Web.Push.ImplTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" =>
+ status:
"Lorem ipsum dolor sit amet, consectetur :firefox: adipiscing elit. Fusce sagittis finibus turpis."
})
@@ -184,8 +184,8 @@ defmodule Pleroma.Web.Push.ImplTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "visibility" => "direct",
- "status" => "This is just between you and me, pal"
+ visibility: "direct",
+ status: "This is just between you and me, pal"
})
assert Impl.format_title(%{activity: activity}) ==
@@ -199,8 +199,8 @@ defmodule Pleroma.Web.Push.ImplTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "visibility" => "direct",
- "status" => " "public",
- "status" => " "direct",
- "status" =>
+ visibility: "direct",
+ status:
"Lorem ipsum dolor sit amet, consectetur :firefox: adipiscing elit. Fusce sagittis finibus turpis."
})
@@ -263,8 +263,8 @@ defmodule Pleroma.Web.Push.ImplTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "visibility" => "public",
- "status" =>
+ visibility: "public",
+ status:
"Lorem ipsum dolor sit amet, consectetur :firefox: adipiscing elit. Fusce sagittis finibus turpis."
})
diff --git a/test/web/rich_media/helpers_test.exs b/test/web/rich_media/helpers_test.exs
index aa0c5c830..8264a9c41 100644
--- a/test/web/rich_media/helpers_test.exs
+++ b/test/web/rich_media/helpers_test.exs
@@ -26,8 +26,8 @@ defmodule Pleroma.Web.RichMedia.HelpersTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "[test](example.com/ogp)",
- "content_type" => "text/markdown"
+ status: "[test](example.com/ogp)",
+ content_type: "text/markdown"
})
Config.put([:rich_media, :enabled], true)
@@ -40,8 +40,8 @@ defmodule Pleroma.Web.RichMedia.HelpersTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "[test](example.com[]/ogp)",
- "content_type" => "text/markdown"
+ status: "[test](example.com[]/ogp)",
+ content_type: "text/markdown"
})
Config.put([:rich_media, :enabled], true)
@@ -54,8 +54,8 @@ defmodule Pleroma.Web.RichMedia.HelpersTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "[test](https://example.com/ogp)",
- "content_type" => "text/markdown"
+ status: "[test](https://example.com/ogp)",
+ content_type: "text/markdown"
})
Config.put([:rich_media, :enabled], true)
@@ -69,8 +69,8 @@ defmodule Pleroma.Web.RichMedia.HelpersTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "http://example.com/ogp",
- "sensitive" => true
+ status: "http://example.com/ogp",
+ sensitive: true
})
%Object{} = object = Object.normalize(activity)
@@ -87,7 +87,7 @@ defmodule Pleroma.Web.RichMedia.HelpersTest do
{:ok, activity} =
CommonAPI.post(user, %{
- "status" => "http://example.com/ogp #nsfw"
+ status: "http://example.com/ogp #nsfw"
})
%Object{} = object = Object.normalize(activity)
@@ -103,12 +103,12 @@ defmodule Pleroma.Web.RichMedia.HelpersTest do
user = insert(:user)
{:ok, activity} =
- CommonAPI.post(user, %{"status" => "http://127.0.0.1:4000/notice/9kCP7VNyPJXFOXDrgO"})
+ CommonAPI.post(user, %{status: "http://127.0.0.1:4000/notice/9kCP7VNyPJXFOXDrgO"})
- {:ok, activity2} = CommonAPI.post(user, %{"status" => "https://10.111.10.1/notice/9kCP7V"})
- {:ok, activity3} = CommonAPI.post(user, %{"status" => "https://172.16.32.40/notice/9kCP7V"})
- {:ok, activity4} = CommonAPI.post(user, %{"status" => "https://192.168.10.40/notice/9kCP7V"})
- {:ok, activity5} = CommonAPI.post(user, %{"status" => "https://pleroma.local/notice/9kCP7V"})
+ {:ok, activity2} = CommonAPI.post(user, %{status: "https://10.111.10.1/notice/9kCP7V"})
+ {:ok, activity3} = CommonAPI.post(user, %{status: "https://172.16.32.40/notice/9kCP7V"})
+ {:ok, activity4} = CommonAPI.post(user, %{status: "https://192.168.10.40/notice/9kCP7V"})
+ {:ok, activity5} = CommonAPI.post(user, %{status: "https://pleroma.local/notice/9kCP7V"})
Config.put([:rich_media, :enabled], true)
diff --git a/test/web/static_fe/static_fe_controller_test.exs b/test/web/static_fe/static_fe_controller_test.exs
index 430683ea0..a49ab002f 100644
--- a/test/web/static_fe/static_fe_controller_test.exs
+++ b/test/web/static_fe/static_fe_controller_test.exs
@@ -32,8 +32,8 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do
end
test "profile does not include private messages", %{conn: conn, user: user} do
- CommonAPI.post(user, %{"status" => "public"})
- CommonAPI.post(user, %{"status" => "private", "visibility" => "private"})
+ CommonAPI.post(user, %{status: "public"})
+ CommonAPI.post(user, %{status: "private", visibility: "private"})
conn = get(conn, "/users/#{user.nickname}")
@@ -44,7 +44,7 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do
end
test "pagination", %{conn: conn, user: user} do
- Enum.map(1..30, fn i -> CommonAPI.post(user, %{"status" => "test#{i}"}) end)
+ Enum.map(1..30, fn i -> CommonAPI.post(user, %{status: "test#{i}"}) end)
conn = get(conn, "/users/#{user.nickname}")
@@ -57,7 +57,7 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do
end
test "pagination, page 2", %{conn: conn, user: user} do
- activities = Enum.map(1..30, fn i -> CommonAPI.post(user, %{"status" => "test#{i}"}) end)
+ activities = Enum.map(1..30, fn i -> CommonAPI.post(user, %{status: "test#{i}"}) end)
{:ok, a11} = Enum.at(activities, 11)
conn = get(conn, "/users/#{user.nickname}?max_id=#{a11.id}")
@@ -77,7 +77,7 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do
describe "notice html" do
test "single notice page", %{conn: conn, user: user} do
- {:ok, activity} = CommonAPI.post(user, %{"status" => "testing a thing!"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "testing a thing!"})
conn = get(conn, "/notice/#{activity.id}")
@@ -89,7 +89,7 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do
test "filters HTML tags", %{conn: conn} do
user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => ""})
+ {:ok, activity} = CommonAPI.post(user, %{status: ""})
conn =
conn
@@ -101,11 +101,11 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do
end
test "shows the whole thread", %{conn: conn, user: user} do
- {:ok, activity} = CommonAPI.post(user, %{"status" => "space: the final frontier"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "space: the final frontier"})
CommonAPI.post(user, %{
- "status" => "these are the voyages or something",
- "in_reply_to_status_id" => activity.id
+ status: "these are the voyages or something",
+ in_reply_to_status_id: activity.id
})
conn = get(conn, "/notice/#{activity.id}")
@@ -117,7 +117,7 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do
test "redirect by AP object ID", %{conn: conn, user: user} do
{:ok, %Activity{data: %{"object" => object_url}}} =
- CommonAPI.post(user, %{"status" => "beam me up"})
+ CommonAPI.post(user, %{status: "beam me up"})
conn = get(conn, URI.parse(object_url).path)
@@ -126,7 +126,7 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do
test "redirect by activity ID", %{conn: conn, user: user} do
{:ok, %Activity{data: %{"id" => id}}} =
- CommonAPI.post(user, %{"status" => "I'm a doctor, not a devops!"})
+ CommonAPI.post(user, %{status: "I'm a doctor, not a devops!"})
conn = get(conn, URI.parse(id).path)
@@ -140,8 +140,7 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do
end
test "404 for private status", %{conn: conn, user: user} do
- {:ok, activity} =
- CommonAPI.post(user, %{"status" => "don't show me!", "visibility" => "private"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "don't show me!", visibility: "private"})
conn = get(conn, "/notice/#{activity.id}")
@@ -171,7 +170,7 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do
end
test "it requires authentication if instance is NOT federating", %{conn: conn, user: user} do
- {:ok, activity} = CommonAPI.post(user, %{"status" => "testing a thing!"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "testing a thing!"})
ensure_federating_or_authenticated(conn, "/notice/#{activity.id}", user)
end
diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs
index db07c5df5..95b7d1420 100644
--- a/test/web/streamer/streamer_test.exs
+++ b/test/web/streamer/streamer_test.exs
@@ -96,7 +96,7 @@ defmodule Pleroma.Web.StreamerTest do
test "it streams the user's post in the 'user' stream", %{user: user} do
Streamer.get_topic_and_add_socket("user", user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "hey"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey"})
assert_receive {:render_with_user, _, _, ^activity}
refute Streamer.filtered_by_user?(user, activity)
end
@@ -105,7 +105,7 @@ defmodule Pleroma.Web.StreamerTest do
Streamer.get_topic_and_add_socket("user", user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hey"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "hey"})
{:ok, announce, _} = CommonAPI.repeat(activity.id, user)
assert_receive {:render_with_user, Pleroma.Web.StreamerView, "update.json", ^announce}
@@ -134,7 +134,7 @@ defmodule Pleroma.Web.StreamerTest do
Streamer.get_topic_and_add_socket("user:notification", user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => ":("})
+ {:ok, activity} = CommonAPI.post(user, %{status: ":("})
{:ok, _} = CommonAPI.favorite(blocked, activity.id)
refute_receive _
@@ -145,7 +145,7 @@ defmodule Pleroma.Web.StreamerTest do
} do
user2 = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "super hot take"})
{:ok, _} = CommonAPI.add_mute(user, activity)
Streamer.get_topic_and_add_socket("user:notification", user)
@@ -161,7 +161,7 @@ defmodule Pleroma.Web.StreamerTest do
} do
user2 = insert(:user, %{ap_id: "https://hecking-lewd-place.com/user/meanie"})
- {:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "super hot take"})
Streamer.get_topic_and_add_socket("user:notification", user)
{:ok, favorite_activity} = CommonAPI.favorite(user2, activity.id)
@@ -176,7 +176,7 @@ defmodule Pleroma.Web.StreamerTest do
user2 = insert(:user, %{ap_id: "https://hecking-lewd-place.com/user/meanie"})
{:ok, user} = User.block_domain(user, "hecking-lewd-place.com")
- {:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "super hot take"})
Streamer.get_topic_and_add_socket("user:notification", user)
{:ok, favorite_activity} = CommonAPI.favorite(user2, activity.id)
@@ -215,7 +215,7 @@ defmodule Pleroma.Web.StreamerTest do
Streamer.get_topic_and_add_socket("public", other_user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Test"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "Test"})
assert_receive {:render_with_user, _, _, ^activity}
refute Streamer.filtered_by_user?(user, activity)
end
@@ -223,7 +223,7 @@ defmodule Pleroma.Web.StreamerTest do
test "works for deletions" do
user = insert(:user)
other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(other_user, %{"status" => "Test"})
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "Test"})
Streamer.get_topic_and_add_socket("public", user)
@@ -238,7 +238,7 @@ defmodule Pleroma.Web.StreamerTest do
Streamer.get_topic_and_add_socket("public", nil)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "Test"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "Test"})
activity_id = activity.id
assert_receive {:text, event}
assert %{"event" => "update", "payload" => payload} = Jason.decode!(event)
@@ -323,7 +323,7 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, _user_relationship} = User.block(user, blocked_user)
Streamer.get_topic_and_add_socket("public", user)
- {:ok, activity} = CommonAPI.post(blocked_user, %{"status" => "Test"})
+ {:ok, activity} = CommonAPI.post(blocked_user, %{status: "Test"})
assert_receive {:render_with_user, _, _, ^activity}
assert Streamer.filtered_by_user?(user, activity)
end
@@ -337,17 +337,17 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, _user_relationship} = User.block(blocker, blockee)
- {:ok, activity_one} = CommonAPI.post(friend, %{"status" => "hey! @#{blockee.nickname}"})
+ {:ok, activity_one} = CommonAPI.post(friend, %{status: "hey! @#{blockee.nickname}"})
assert_receive {:render_with_user, _, _, ^activity_one}
assert Streamer.filtered_by_user?(blocker, activity_one)
- {:ok, activity_two} = CommonAPI.post(blockee, %{"status" => "hey! @#{friend.nickname}"})
+ {:ok, activity_two} = CommonAPI.post(blockee, %{status: "hey! @#{friend.nickname}"})
assert_receive {:render_with_user, _, _, ^activity_two}
assert Streamer.filtered_by_user?(blocker, activity_two)
- {:ok, activity_three} = CommonAPI.post(blockee, %{"status" => "hey! @#{blocker.nickname}"})
+ {:ok, activity_three} = CommonAPI.post(blockee, %{status: "hey! @#{blocker.nickname}"})
assert_receive {:render_with_user, _, _, ^activity_three}
assert Streamer.filtered_by_user?(blocker, activity_three)
@@ -369,8 +369,8 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, _activity} =
CommonAPI.post(user_b, %{
- "status" => "@#{user_c.nickname} Test",
- "visibility" => "direct"
+ status: "@#{user_c.nickname} Test",
+ visibility: "direct"
})
refute_receive _
@@ -387,8 +387,8 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, _activity} =
CommonAPI.post(user_b, %{
- "status" => "Test",
- "visibility" => "private"
+ status: "Test",
+ visibility: "private"
})
refute_receive _
@@ -407,8 +407,8 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, activity} =
CommonAPI.post(user_b, %{
- "status" => "Test",
- "visibility" => "private"
+ status: "Test",
+ visibility: "private"
})
assert_receive {:render_with_user, _, _, ^activity}
@@ -424,7 +424,7 @@ defmodule Pleroma.Web.StreamerTest do
CommonAPI.follow(user1, user2)
CommonAPI.hide_reblogs(user1, user2)
- {:ok, create_activity} = CommonAPI.post(user3, %{"status" => "I'm kawen"})
+ {:ok, create_activity} = CommonAPI.post(user3, %{status: "I'm kawen"})
Streamer.get_topic_and_add_socket("user", user1)
{:ok, announce_activity, _} = CommonAPI.repeat(create_activity.id, user2)
@@ -438,7 +438,7 @@ defmodule Pleroma.Web.StreamerTest do
CommonAPI.follow(user1, user2)
CommonAPI.hide_reblogs(user1, user2)
- {:ok, create_activity} = CommonAPI.post(user1, %{"status" => "I'm kawen"})
+ {:ok, create_activity} = CommonAPI.post(user1, %{status: "I'm kawen"})
Streamer.get_topic_and_add_socket("user", user1)
{:ok, _favorite_activity, _} = CommonAPI.repeat(create_activity.id, user2)
@@ -452,7 +452,7 @@ defmodule Pleroma.Web.StreamerTest do
CommonAPI.follow(user1, user2)
CommonAPI.hide_reblogs(user1, user2)
- {:ok, create_activity} = CommonAPI.post(user1, %{"status" => "I'm kawen"})
+ {:ok, create_activity} = CommonAPI.post(user1, %{status: "I'm kawen"})
Streamer.get_topic_and_add_socket("user", user1)
{:ok, _favorite_activity} = CommonAPI.favorite(user2, create_activity.id)
@@ -466,7 +466,7 @@ defmodule Pleroma.Web.StreamerTest do
user2 = insert(:user)
Streamer.get_topic_and_add_socket("user", user2)
{:ok, user2, user, _activity} = CommonAPI.follow(user2, user)
- {:ok, activity} = CommonAPI.post(user, %{"status" => "super hot take"})
+ {:ok, activity} = CommonAPI.post(user, %{status: "super hot take"})
{:ok, _} = CommonAPI.add_mute(user2, activity)
assert_receive {:render_with_user, _, _, ^activity}
assert Streamer.filtered_by_user?(user2, activity)
@@ -485,8 +485,8 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, _create_activity} =
CommonAPI.post(another_user, %{
- "status" => "hey @#{user.nickname}",
- "visibility" => "direct"
+ status: "hey @#{user.nickname}",
+ visibility: "direct"
})
assert_receive {:text, received_event}
@@ -507,8 +507,8 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, create_activity} =
CommonAPI.post(another_user, %{
- "status" => "hi @#{user.nickname}",
- "visibility" => "direct"
+ status: "hi @#{user.nickname}",
+ visibility: "direct"
})
create_activity_id = create_activity.id
@@ -533,15 +533,15 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, create_activity} =
CommonAPI.post(another_user, %{
- "status" => "hi @#{user.nickname}",
- "visibility" => "direct"
+ status: "hi @#{user.nickname}",
+ visibility: "direct"
})
{:ok, create_activity2} =
CommonAPI.post(another_user, %{
- "status" => "hi @#{user.nickname} 2",
- "in_reply_to_status_id" => create_activity.id,
- "visibility" => "direct"
+ status: "hi @#{user.nickname} 2",
+ in_reply_to_status_id: create_activity.id,
+ visibility: "direct"
})
assert_receive {:render_with_user, _, _, ^create_activity}
diff --git a/test/workers/cron/digest_emails_worker_test.exs b/test/workers/cron/digest_emails_worker_test.exs
index 0a63bf4e0..f9bc50db5 100644
--- a/test/workers/cron/digest_emails_worker_test.exs
+++ b/test/workers/cron/digest_emails_worker_test.exs
@@ -29,7 +29,7 @@ defmodule Pleroma.Workers.Cron.DigestEmailsWorkerTest do
user2 = insert(:user, last_digest_emailed_at: date)
{:ok, _} = User.switch_email_notifications(user2, "digest", true)
- CommonAPI.post(user, %{"status" => "hey @#{user2.nickname}!"})
+ CommonAPI.post(user, %{status: "hey @#{user2.nickname}!"})
{:ok, user2: user2}
end
diff --git a/test/workers/cron/new_users_digest_worker_test.exs b/test/workers/cron/new_users_digest_worker_test.exs
index e6d050ecc..54cf0ca46 100644
--- a/test/workers/cron/new_users_digest_worker_test.exs
+++ b/test/workers/cron/new_users_digest_worker_test.exs
@@ -15,7 +15,7 @@ defmodule Pleroma.Workers.Cron.NewUsersDigestWorkerTest do
admin = insert(:user, %{is_admin: true})
user = insert(:user, %{inserted_at: yesterday})
user2 = insert(:user, %{inserted_at: yesterday})
- CommonAPI.post(user, %{"status" => "cofe"})
+ CommonAPI.post(user, %{status: "cofe"})
NewUsersDigestWorker.perform(nil, nil)
ObanHelpers.perform_all()
@@ -36,7 +36,7 @@ defmodule Pleroma.Workers.Cron.NewUsersDigestWorkerTest do
insert(:user, %{inserted_at: yesterday})
user = insert(:user, %{inserted_at: yesterday})
- CommonAPI.post(user, %{"status" => "cofe"})
+ CommonAPI.post(user, %{status: "cofe"})
NewUsersDigestWorker.perform(nil, nil)
ObanHelpers.perform_all()
--
cgit v1.2.3
From b46811a07444187e7765f439e933f214c0a0aeb3 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Tue, 12 May 2020 16:42:24 -0500
Subject: Upgrade Comeonin to v5
https://github.com/riverrun/comeonin/blob/master/UPGRADE_v5.md
---
test/mfa_test.exs | 5 ++---
test/plugs/authentication_plug_test.exs | 2 +-
test/support/builders/user_builder.ex | 2 +-
test/support/factory.ex | 2 +-
test/web/auth/basic_auth_test.exs | 2 +-
test/web/auth/pleroma_authenticator_test.exs | 2 +-
test/web/auth/totp_authenticator_test.exs | 2 +-
test/web/mongooseim/mongoose_im_controller_test.exs | 4 ++--
test/web/oauth/ldap_authorization_test.exs | 6 +++---
test/web/oauth/mfa_controller_test.exs | 4 ++--
test/web/oauth/oauth_controller_test.exs | 16 ++++++++--------
test/web/twitter_api/password_controller_test.exs | 2 +-
test/web/twitter_api/util_controller_test.exs | 2 +-
13 files changed, 25 insertions(+), 26 deletions(-)
(limited to 'test')
diff --git a/test/mfa_test.exs b/test/mfa_test.exs
index 94bc48c26..8875cefd9 100644
--- a/test/mfa_test.exs
+++ b/test/mfa_test.exs
@@ -6,7 +6,6 @@ defmodule Pleroma.MFATest do
use Pleroma.DataCase
import Pleroma.Factory
- alias Comeonin.Pbkdf2
alias Pleroma.MFA
describe "mfa_settings" do
@@ -31,8 +30,8 @@ defmodule Pleroma.MFATest do
{:ok, [code1, code2]} = MFA.generate_backup_codes(user)
updated_user = refresh_record(user)
[hash1, hash2] = updated_user.multi_factor_authentication_settings.backup_codes
- assert Pbkdf2.checkpw(code1, hash1)
- assert Pbkdf2.checkpw(code2, hash2)
+ assert Pbkdf2.verify_pass(code1, hash1)
+ assert Pbkdf2.verify_pass(code2, hash2)
end
end
diff --git a/test/plugs/authentication_plug_test.exs b/test/plugs/authentication_plug_test.exs
index 646bda9d3..31e20d726 100644
--- a/test/plugs/authentication_plug_test.exs
+++ b/test/plugs/authentication_plug_test.exs
@@ -16,7 +16,7 @@ defmodule Pleroma.Plugs.AuthenticationPlugTest do
user = %User{
id: 1,
name: "dude",
- password_hash: Comeonin.Pbkdf2.hashpwsalt("guy")
+ password_hash: Pbkdf2.hash_pwd_salt("guy")
}
conn =
diff --git a/test/support/builders/user_builder.ex b/test/support/builders/user_builder.ex
index 0d0490714..0c687c029 100644
--- a/test/support/builders/user_builder.ex
+++ b/test/support/builders/user_builder.ex
@@ -7,7 +7,7 @@ defmodule Pleroma.Builders.UserBuilder do
email: "test@example.org",
name: "Test Name",
nickname: "testname",
- password_hash: Comeonin.Pbkdf2.hashpwsalt("test"),
+ password_hash: Pbkdf2.hash_pwd_salt("test"),
bio: "A tester.",
ap_id: "some id",
last_digest_emailed_at: NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second),
diff --git a/test/support/factory.ex b/test/support/factory.ex
index c8c45e2a7..d4284831c 100644
--- a/test/support/factory.ex
+++ b/test/support/factory.ex
@@ -29,7 +29,7 @@ defmodule Pleroma.Factory do
name: sequence(:name, &"Test テスト User #{&1}"),
email: sequence(:email, &"user#{&1}@example.com"),
nickname: sequence(:nickname, &"nick#{&1}"),
- password_hash: Comeonin.Pbkdf2.hashpwsalt("test"),
+ password_hash: Pbkdf2.hash_pwd_salt("test"),
bio: sequence(:bio, &"Tester Number #{&1}"),
last_digest_emailed_at: NaiveDateTime.utc_now(),
last_refreshed_at: NaiveDateTime.utc_now(),
diff --git a/test/web/auth/basic_auth_test.exs b/test/web/auth/basic_auth_test.exs
index 64f8a6863..bf6e3d2fc 100644
--- a/test/web/auth/basic_auth_test.exs
+++ b/test/web/auth/basic_auth_test.exs
@@ -11,7 +11,7 @@ defmodule Pleroma.Web.Auth.BasicAuthTest do
conn: conn
} do
user = insert(:user)
- assert Comeonin.Pbkdf2.checkpw("test", user.password_hash)
+ assert Pbkdf2.verify_pass("test", user.password_hash)
basic_auth_contents =
(URI.encode_www_form(user.nickname) <> ":" <> URI.encode_www_form("test"))
diff --git a/test/web/auth/pleroma_authenticator_test.exs b/test/web/auth/pleroma_authenticator_test.exs
index 7125c5081..5a421e5ed 100644
--- a/test/web/auth/pleroma_authenticator_test.exs
+++ b/test/web/auth/pleroma_authenticator_test.exs
@@ -11,7 +11,7 @@ defmodule Pleroma.Web.Auth.PleromaAuthenticatorTest do
setup do
password = "testpassword"
name = "AgentSmith"
- user = insert(:user, nickname: name, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
+ user = insert(:user, nickname: name, password_hash: Pbkdf2.hash_pwd_salt(password))
{:ok, [user: user, name: name, password: password]}
end
diff --git a/test/web/auth/totp_authenticator_test.exs b/test/web/auth/totp_authenticator_test.exs
index e08069490..e502e0ae8 100644
--- a/test/web/auth/totp_authenticator_test.exs
+++ b/test/web/auth/totp_authenticator_test.exs
@@ -34,7 +34,7 @@ defmodule Pleroma.Web.Auth.TOTPAuthenticatorTest do
hashed_codes =
backup_codes
- |> Enum.map(&Comeonin.Pbkdf2.hashpwsalt(&1))
+ |> Enum.map(&Pbkdf2.hash_pwd_salt(&1))
user =
insert(:user,
diff --git a/test/web/mongooseim/mongoose_im_controller_test.exs b/test/web/mongooseim/mongoose_im_controller_test.exs
index 1ac2f2c27..5176cde84 100644
--- a/test/web/mongooseim/mongoose_im_controller_test.exs
+++ b/test/web/mongooseim/mongoose_im_controller_test.exs
@@ -41,13 +41,13 @@ defmodule Pleroma.Web.MongooseIMController do
end
test "/check_password", %{conn: conn} do
- user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("cool"))
+ user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt("cool"))
_deactivated_user =
insert(:user,
nickname: "konata",
deactivated: true,
- password_hash: Comeonin.Pbkdf2.hashpwsalt("cool")
+ password_hash: Pbkdf2.hash_pwd_salt("cool")
)
res =
diff --git a/test/web/oauth/ldap_authorization_test.exs b/test/web/oauth/ldap_authorization_test.exs
index a8fe8a841..011642c08 100644
--- a/test/web/oauth/ldap_authorization_test.exs
+++ b/test/web/oauth/ldap_authorization_test.exs
@@ -19,7 +19,7 @@ defmodule Pleroma.Web.OAuth.LDAPAuthorizationTest do
@tag @skip
test "authorizes the existing user using LDAP credentials" do
password = "testpassword"
- user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
+ user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password))
app = insert(:oauth_app, scopes: ["read", "write"])
host = Pleroma.Config.get([:ldap, :host]) |> to_charlist
@@ -104,7 +104,7 @@ defmodule Pleroma.Web.OAuth.LDAPAuthorizationTest do
@tag @skip
test "falls back to the default authorization when LDAP is unavailable" do
password = "testpassword"
- user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
+ user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password))
app = insert(:oauth_app, scopes: ["read", "write"])
host = Pleroma.Config.get([:ldap, :host]) |> to_charlist
@@ -148,7 +148,7 @@ defmodule Pleroma.Web.OAuth.LDAPAuthorizationTest do
@tag @skip
test "disallow authorization for wrong LDAP credentials" do
password = "testpassword"
- user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
+ user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password))
app = insert(:oauth_app, scopes: ["read", "write"])
host = Pleroma.Config.get([:ldap, :host]) |> to_charlist
diff --git a/test/web/oauth/mfa_controller_test.exs b/test/web/oauth/mfa_controller_test.exs
index ce4a07320..3c341facd 100644
--- a/test/web/oauth/mfa_controller_test.exs
+++ b/test/web/oauth/mfa_controller_test.exs
@@ -20,7 +20,7 @@ defmodule Pleroma.Web.OAuth.MFAControllerTest do
insert(:user,
multi_factor_authentication_settings: %MFA.Settings{
enabled: true,
- backup_codes: [Comeonin.Pbkdf2.hashpwsalt("test-code")],
+ backup_codes: [Pbkdf2.hash_pwd_salt("test-code")],
totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
}
)
@@ -247,7 +247,7 @@ defmodule Pleroma.Web.OAuth.MFAControllerTest do
hashed_codes =
backup_codes
- |> Enum.map(&Comeonin.Pbkdf2.hashpwsalt(&1))
+ |> Enum.map(&Pbkdf2.hash_pwd_salt(&1))
user =
insert(:user,
diff --git a/test/web/oauth/oauth_controller_test.exs b/test/web/oauth/oauth_controller_test.exs
index 7a107584d..d389e4ce0 100644
--- a/test/web/oauth/oauth_controller_test.exs
+++ b/test/web/oauth/oauth_controller_test.exs
@@ -311,7 +311,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
app: app,
conn: conn
} do
- user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("testpassword"))
+ user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt("testpassword"))
registration = insert(:registration, user: nil)
redirect_uri = OAuthController.default_redirect_uri(app)
@@ -342,7 +342,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
app: app,
conn: conn
} do
- user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("testpassword"))
+ user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt("testpassword"))
registration = insert(:registration, user: nil)
unlisted_redirect_uri = "http://cross-site-request.com"
@@ -750,7 +750,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do
password = "testpassword"
- user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
+ user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password))
app = insert(:oauth_app, scopes: ["read", "write"])
@@ -778,7 +778,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
user =
insert(:user,
- password_hash: Comeonin.Pbkdf2.hashpwsalt(password),
+ password_hash: Pbkdf2.hash_pwd_salt(password),
multi_factor_authentication_settings: %MFA.Settings{
enabled: true,
totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
@@ -887,7 +887,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
password = "testpassword"
{:ok, user} =
- insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
+ insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password))
|> User.confirmation_changeset(need_confirmation: true)
|> User.update_and_set_cache()
@@ -915,7 +915,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
user =
insert(:user,
- password_hash: Comeonin.Pbkdf2.hashpwsalt(password),
+ password_hash: Pbkdf2.hash_pwd_salt(password),
deactivated: true
)
@@ -943,7 +943,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
user =
insert(:user,
- password_hash: Comeonin.Pbkdf2.hashpwsalt(password),
+ password_hash: Pbkdf2.hash_pwd_salt(password),
password_reset_pending: true
)
@@ -972,7 +972,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do
user =
insert(:user,
- password_hash: Comeonin.Pbkdf2.hashpwsalt(password),
+ password_hash: Pbkdf2.hash_pwd_salt(password),
confirmation_pending: true
)
diff --git a/test/web/twitter_api/password_controller_test.exs b/test/web/twitter_api/password_controller_test.exs
index 0a24860d3..231a46c67 100644
--- a/test/web/twitter_api/password_controller_test.exs
+++ b/test/web/twitter_api/password_controller_test.exs
@@ -54,7 +54,7 @@ defmodule Pleroma.Web.TwitterAPI.PasswordControllerTest do
assert response =~ "Password changed!
"
user = refresh_record(user)
- assert Comeonin.Pbkdf2.checkpw("test", user.password_hash)
+ assert Pbkdf2.verify_pass("test", user.password_hash)
assert Enum.empty?(Token.get_user_tokens(user))
end
diff --git a/test/web/twitter_api/util_controller_test.exs b/test/web/twitter_api/util_controller_test.exs
index b701239a0..ad919d341 100644
--- a/test/web/twitter_api/util_controller_test.exs
+++ b/test/web/twitter_api/util_controller_test.exs
@@ -688,7 +688,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do
assert json_response(conn, 200) == %{"status" => "success"}
fetched_user = User.get_cached_by_id(user.id)
- assert Comeonin.Pbkdf2.checkpw("newpass", fetched_user.password_hash) == true
+ assert Pbkdf2.verify_pass("newpass", fetched_user.password_hash) == true
end
end
--
cgit v1.2.3
From 4ba913d64157909c63cbeab38b6036a5e4beee53 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Fri, 8 May 2020 18:51:16 +0300
Subject: {:error, :enoent} s3 fix
s3 tests were executed before temp file was uploaded
---
test/uploaders/s3_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/uploaders/s3_test.exs b/test/uploaders/s3_test.exs
index 6950ccb25..d949c90a5 100644
--- a/test/uploaders/s3_test.exs
+++ b/test/uploaders/s3_test.exs
@@ -58,7 +58,7 @@ defmodule Pleroma.Uploaders.S3Test do
name: "image-tet.jpg",
content_type: "image/jpg",
path: "test_folder/image-tet.jpg",
- tempfile: Path.absname("test/fixtures/image_tmp.jpg")
+ tempfile: Path.absname("test/instance_static/add/shortcode.png")
}
[file_upload: file_upload]
--
cgit v1.2.3
From 712055612f2696b2677f830be154e18f2396223d Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Mon, 11 May 2020 15:07:05 +0300
Subject: don't run tests which change env in async
---
test/http/request_builder_test.exs | 14 +++----
test/web/admin_api/admin_api_controller_test.exs | 51 +++++++++++-------------
2 files changed, 29 insertions(+), 36 deletions(-)
(limited to 'test')
diff --git a/test/http/request_builder_test.exs b/test/http/request_builder_test.exs
index f11528c3f..fab909905 100644
--- a/test/http/request_builder_test.exs
+++ b/test/http/request_builder_test.exs
@@ -3,23 +3,19 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTP.RequestBuilderTest do
- use ExUnit.Case, async: true
+ use ExUnit.Case
use Pleroma.Tests.Helpers
- alias Pleroma.Config
alias Pleroma.HTTP.Request
alias Pleroma.HTTP.RequestBuilder
describe "headers/2" do
- setup do: clear_config([:http, :send_user_agent])
- setup do: clear_config([:http, :user_agent])
-
test "don't send pleroma user agent" do
assert RequestBuilder.headers(%Request{}, []) == %Request{headers: []}
end
test "send pleroma user agent" do
- Config.put([:http, :send_user_agent], true)
- Config.put([:http, :user_agent], :default)
+ clear_config([:http, :send_user_agent], true)
+ clear_config([:http, :user_agent], :default)
assert RequestBuilder.headers(%Request{}, []) == %Request{
headers: [{"user-agent", Pleroma.Application.user_agent()}]
@@ -27,8 +23,8 @@ defmodule Pleroma.HTTP.RequestBuilderTest do
end
test "send custom user agent" do
- Config.put([:http, :send_user_agent], true)
- Config.put([:http, :user_agent], "totally-not-pleroma")
+ clear_config([:http, :send_user_agent], true)
+ clear_config([:http, :user_agent], "totally-not-pleroma")
assert RequestBuilder.headers(%Request{}, []) == %Request{
headers: [{"user-agent", "totally-not-pleroma"}]
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 4697af50e..94c59de9c 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -2862,26 +2862,25 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
group: ":pleroma",
key: ":http",
value: [
- %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "localhost", 1234]}]},
- %{"tuple" => [":send_user_agent", false]}
+ %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "localhost", 1234]}]}
]
}
]
})
- assert json_response(conn, 200) == %{
+ assert %{
"configs" => [
%{
"group" => ":pleroma",
"key" => ":http",
- "value" => [
- %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "localhost", 1234]}]},
- %{"tuple" => [":send_user_agent", false]}
- ],
- "db" => [":proxy_url", ":send_user_agent"]
+ "value" => value,
+ "db" => db
}
]
- }
+ } = json_response(conn, 200)
+
+ assert %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "localhost", 1234]}]} in value
+ assert ":proxy_url" in db
end
test "proxy tuple domain", %{conn: conn} do
@@ -2892,26 +2891,25 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
group: ":pleroma",
key: ":http",
value: [
- %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "domain.com", 1234]}]},
- %{"tuple" => [":send_user_agent", false]}
+ %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "domain.com", 1234]}]}
]
}
]
})
- assert json_response(conn, 200) == %{
+ assert %{
"configs" => [
%{
"group" => ":pleroma",
"key" => ":http",
- "value" => [
- %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "domain.com", 1234]}]},
- %{"tuple" => [":send_user_agent", false]}
- ],
- "db" => [":proxy_url", ":send_user_agent"]
+ "value" => value,
+ "db" => db
}
]
- }
+ } = json_response(conn, 200)
+
+ assert %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "domain.com", 1234]}]} in value
+ assert ":proxy_url" in db
end
test "proxy tuple ip", %{conn: conn} do
@@ -2922,26 +2920,25 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
group: ":pleroma",
key: ":http",
value: [
- %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "127.0.0.1", 1234]}]},
- %{"tuple" => [":send_user_agent", false]}
+ %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "127.0.0.1", 1234]}]}
]
}
]
})
- assert json_response(conn, 200) == %{
+ assert %{
"configs" => [
%{
"group" => ":pleroma",
"key" => ":http",
- "value" => [
- %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "127.0.0.1", 1234]}]},
- %{"tuple" => [":send_user_agent", false]}
- ],
- "db" => [":proxy_url", ":send_user_agent"]
+ "value" => value,
+ "db" => db
}
]
- }
+ } = json_response(conn, 200)
+
+ assert %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "127.0.0.1", 1234]}]} in value
+ assert ":proxy_url" in db
end
end
--
cgit v1.2.3
From e0944dee993eec88f678e98de9382af82ca5a77a Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Mon, 11 May 2020 15:22:52 +0300
Subject: make test fail everytime
---
test/web/feed/tag_controller_test.exs | 4 ++++
1 file changed, 4 insertions(+)
(limited to 'test')
diff --git a/test/web/feed/tag_controller_test.exs b/test/web/feed/tag_controller_test.exs
index d95aac108..d726300a9 100644
--- a/test/web/feed/tag_controller_test.exs
+++ b/test/web/feed/tag_controller_test.exs
@@ -82,6 +82,10 @@ defmodule Pleroma.Web.Feed.TagControllerTest do
end
test "gets a feed (RSS)", %{conn: conn} do
+ %{microsecond: {micro, _}} = DateTime.utc_now()
+ micro = (micro / 1000) |> floor()
+ Process.sleep(950 - micro)
+
Pleroma.Config.put(
[:feed, :post_title],
%{max_length: 25, omission: "..."}
--
cgit v1.2.3
From ec27f346eebc99ff8bbc7d1e34c9559cf80b8691 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Tue, 12 May 2020 12:12:10 +0300
Subject: correct order for publised in assert
---
test/web/feed/tag_controller_test.exs | 8 ++------
1 file changed, 2 insertions(+), 6 deletions(-)
(limited to 'test')
diff --git a/test/web/feed/tag_controller_test.exs b/test/web/feed/tag_controller_test.exs
index d726300a9..c3d83ef81 100644
--- a/test/web/feed/tag_controller_test.exs
+++ b/test/web/feed/tag_controller_test.exs
@@ -82,10 +82,6 @@ defmodule Pleroma.Web.Feed.TagControllerTest do
end
test "gets a feed (RSS)", %{conn: conn} do
- %{microsecond: {micro, _}} = DateTime.utc_now()
- micro = (micro / 1000) |> floor()
- Process.sleep(950 - micro)
-
Pleroma.Config.put(
[:feed, :post_title],
%{max_length: 25, omission: "..."}
@@ -142,8 +138,8 @@ defmodule Pleroma.Web.Feed.TagControllerTest do
]
assert xpath(xml, ~x"//channel/item/pubDate/text()"sl) == [
- FeedView.pub_date(activity1.data["published"]),
- FeedView.pub_date(activity2.data["published"])
+ FeedView.pub_date(activity2.data["published"]),
+ FeedView.pub_date(activity1.data["published"])
]
assert xpath(xml, ~x"//channel/item/enclosure/@url"sl) == [
--
cgit v1.2.3
From b962b24e6f984dbec0089c80b22fac8f4f9c1fa4 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 13 May 2020 08:00:17 +0300
Subject: don't run in async if tests depend on env config
---
test/http/connection_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/http/connection_test.exs b/test/http/connection_test.exs
index 5cc78ad5b..7c94a50b2 100644
--- a/test/http/connection_test.exs
+++ b/test/http/connection_test.exs
@@ -3,7 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTP.ConnectionTest do
- use ExUnit.Case, async: true
+ use ExUnit.Case
use Pleroma.Tests.Helpers
import ExUnit.CaptureLog
--
cgit v1.2.3
From 12635bc15626dd7d2d4a02b9c8d763687a0d34ce Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 13 May 2020 09:20:25 +0300
Subject: don't use global mocks in setup callbacks
---
test/activity_test.exs | 7 +++++--
test/web/mastodon_api/controllers/search_controller_test.exs | 2 +-
test/web/push/impl_test.exs | 4 ++--
3 files changed, 8 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/activity_test.exs b/test/activity_test.exs
index 0c19f481b..7c3f66da9 100644
--- a/test/activity_test.exs
+++ b/test/activity_test.exs
@@ -11,6 +11,11 @@ defmodule Pleroma.ActivityTest do
alias Pleroma.ThreadMute
import Pleroma.Factory
+ setup_all do
+ Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
+ :ok
+ end
+
test "returns an activity by it's AP id" do
activity = insert(:note_activity)
found_activity = Activity.get_by_ap_id(activity.data["id"])
@@ -107,8 +112,6 @@ defmodule Pleroma.ActivityTest do
describe "search" do
setup do
- Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
-
user = insert(:user)
params = %{
diff --git a/test/web/mastodon_api/controllers/search_controller_test.exs b/test/web/mastodon_api/controllers/search_controller_test.exs
index 02476acb6..8b9459735 100644
--- a/test/web/mastodon_api/controllers/search_controller_test.exs
+++ b/test/web/mastodon_api/controllers/search_controller_test.exs
@@ -13,7 +13,7 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
import Tesla.Mock
import Mock
- setup do
+ setup_all do
mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
:ok
end
diff --git a/test/web/push/impl_test.exs b/test/web/push/impl_test.exs
index b855d72ba..57b35061a 100644
--- a/test/web/push/impl_test.exs
+++ b/test/web/push/impl_test.exs
@@ -13,8 +13,8 @@ defmodule Pleroma.Web.Push.ImplTest do
import Pleroma.Factory
- setup_all do
- Tesla.Mock.mock_global(fn
+ setup do
+ Tesla.Mock.mock(fn
%{method: :post, url: "https://example.com/example/1234"} ->
%Tesla.Env{status: 200}
--
cgit v1.2.3
From 2c356a4bacc534702e9d1c1451fb351152c4bf7a Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 13 May 2020 09:29:41 +0300
Subject: don't use async with global mocks
---
test/web/rel_me_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/rel_me_test.exs b/test/web/rel_me_test.exs
index e05a8863d..65255916d 100644
--- a/test/web/rel_me_test.exs
+++ b/test/web/rel_me_test.exs
@@ -3,7 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.RelMeTest do
- use ExUnit.Case, async: true
+ use ExUnit.Case
setup_all do
Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
--
cgit v1.2.3
From fbe3d3aa5fe07a89c52a16b7bf0626e323366597 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 13 May 2020 10:17:47 +0300
Subject: ignore order
---
test/config/config_db_test.exs | 8 +++-----
1 file changed, 3 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/config/config_db_test.exs b/test/config/config_db_test.exs
index 6b0e7b4b6..a8e947365 100644
--- a/test/config/config_db_test.exs
+++ b/test/config/config_db_test.exs
@@ -43,11 +43,9 @@ defmodule Pleroma.ConfigDBTest do
{ConfigDB.from_string(saved.key), ConfigDB.from_binary(saved.value)}
]
- assert config[:quack] == [
- level: :info,
- meta: [:none],
- webhook_url: "https://hooks.slack.com/services/KEY/some_val"
- ]
+ assert config[:quack][:level] == :info
+ assert config[:quack][:meta] == [:none]
+ assert config[:quack][:webhook_url] == "https://hooks.slack.com/services/KEY/some_val"
end
describe "update_or_create/1" do
--
cgit v1.2.3
From bcadbf964a56c071b2a3b5a5a95c419a467e5e1e Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 13 May 2020 14:15:24 +0400
Subject: Add OpenAPI spec for SuggestionController
---
test/web/mastodon_api/controllers/suggestion_controller_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/suggestion_controller_test.exs b/test/web/mastodon_api/controllers/suggestion_controller_test.exs
index f120bd0cd..7f08e187c 100644
--- a/test/web/mastodon_api/controllers/suggestion_controller_test.exs
+++ b/test/web/mastodon_api/controllers/suggestion_controller_test.exs
@@ -11,7 +11,7 @@ defmodule Pleroma.Web.MastodonAPI.SuggestionControllerTest do
res =
conn
|> get("/api/v1/suggestions")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert res == []
end
--
cgit v1.2.3
From 6802dc28ba10aa8120680c2c9610649316907f55 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 13 May 2020 19:06:25 +0400
Subject: Add OpenAPI spec for PleromaAPI.AccountController
---
test/web/activity_pub/activity_pub_test.exs | 2 +-
.../controllers/account_controller_test.exs | 107 ++++++++++++++-------
2 files changed, 75 insertions(+), 34 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 56fde97e7..77bd07edf 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -951,7 +951,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
test "works with base64 encoded images" do
file = %{
- "img" => data_uri()
+ img: data_uri()
}
{:ok, %Object{}} = ActivityPub.upload(file)
diff --git a/test/web/pleroma_api/controllers/account_controller_test.exs b/test/web/pleroma_api/controllers/account_controller_test.exs
index 34fc4aa23..103997c31 100644
--- a/test/web/pleroma_api/controllers/account_controller_test.exs
+++ b/test/web/pleroma_api/controllers/account_controller_test.exs
@@ -31,8 +31,28 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
test "resend account confirmation email", %{conn: conn, user: user} do
conn
+ |> put_req_header("content-type", "application/json")
|> post("/api/v1/pleroma/accounts/confirmation_resend?email=#{user.email}")
- |> json_response(:no_content)
+ |> json_response_and_validate_schema(:no_content)
+
+ ObanHelpers.perform_all()
+
+ email = Pleroma.Emails.UserEmail.account_confirmation_email(user)
+ notify_email = Config.get([:instance, :notify_email])
+ instance_name = Config.get([:instance, :name])
+
+ assert_email_sent(
+ from: {instance_name, notify_email},
+ to: {user.name, user.email},
+ html_body: email.html_body
+ )
+ end
+
+ test "resend account confirmation email (with nickname)", %{conn: conn, user: user} do
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/pleroma/accounts/confirmation_resend?nickname=#{user.nickname}")
+ |> json_response_and_validate_schema(:no_content)
ObanHelpers.perform_all()
@@ -54,7 +74,10 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
test "user avatar can be set", %{user: user, conn: conn} do
avatar_image = File.read!("test/fixtures/avatar_data_uri")
- conn = patch(conn, "/api/v1/pleroma/accounts/update_avatar", %{img: avatar_image})
+ conn =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/v1/pleroma/accounts/update_avatar", %{img: avatar_image})
user = refresh_record(user)
@@ -70,17 +93,20 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
]
} = user.avatar
- assert %{"url" => _} = json_response(conn, 200)
+ assert %{"url" => _} = json_response_and_validate_schema(conn, 200)
end
test "user avatar can be reset", %{user: user, conn: conn} do
- conn = patch(conn, "/api/v1/pleroma/accounts/update_avatar", %{img: ""})
+ conn =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/v1/pleroma/accounts/update_avatar", %{img: ""})
user = User.get_cached_by_id(user.id)
assert user.avatar == nil
- assert %{"url" => nil} = json_response(conn, 200)
+ assert %{"url" => nil} = json_response_and_validate_schema(conn, 200)
end
end
@@ -88,21 +114,27 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
setup do: oauth_access(["write:accounts"])
test "can set profile banner", %{user: user, conn: conn} do
- conn = patch(conn, "/api/v1/pleroma/accounts/update_banner", %{"banner" => @image})
+ conn =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/v1/pleroma/accounts/update_banner", %{"banner" => @image})
user = refresh_record(user)
assert user.banner["type"] == "Image"
- assert %{"url" => _} = json_response(conn, 200)
+ assert %{"url" => _} = json_response_and_validate_schema(conn, 200)
end
test "can reset profile banner", %{user: user, conn: conn} do
- conn = patch(conn, "/api/v1/pleroma/accounts/update_banner", %{"banner" => ""})
+ conn =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/v1/pleroma/accounts/update_banner", %{"banner" => ""})
user = refresh_record(user)
assert user.banner == %{}
- assert %{"url" => nil} = json_response(conn, 200)
+ assert %{"url" => nil} = json_response_and_validate_schema(conn, 200)
end
end
@@ -110,19 +142,26 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
setup do: oauth_access(["write:accounts"])
test "background image can be set", %{user: user, conn: conn} do
- conn = patch(conn, "/api/v1/pleroma/accounts/update_background", %{"img" => @image})
+ conn =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/v1/pleroma/accounts/update_background", %{"img" => @image})
user = refresh_record(user)
assert user.background["type"] == "Image"
- assert %{"url" => _} = json_response(conn, 200)
+ # assert %{"url" => _} = json_response(conn, 200)
+ assert %{"url" => _} = json_response_and_validate_schema(conn, 200)
end
test "background image can be reset", %{user: user, conn: conn} do
- conn = patch(conn, "/api/v1/pleroma/accounts/update_background", %{"img" => ""})
+ conn =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/v1/pleroma/accounts/update_background", %{"img" => ""})
user = refresh_record(user)
assert user.background == %{}
- assert %{"url" => nil} = json_response(conn, 200)
+ assert %{"url" => nil} = json_response_and_validate_schema(conn, 200)
end
end
@@ -143,7 +182,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
response =
conn
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
[like] = response
@@ -160,7 +199,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
response =
build_conn()
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert length(response) == 1
end
@@ -183,7 +222,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
|> assign(:user, u)
|> assign(:token, insert(:oauth_token, user: u, scopes: ["read:favourites"]))
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert length(response) == 1
end
@@ -191,7 +230,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
response =
build_conn()
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert length(response) == 0
end
@@ -213,7 +252,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
response =
conn
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert Enum.empty?(response)
end
@@ -233,11 +272,12 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
response =
conn
- |> get("/api/v1/pleroma/accounts/#{user.id}/favourites", %{
- since_id: third_activity.id,
- max_id: seventh_activity.id
- })
- |> json_response(:ok)
+ |> get(
+ "/api/v1/pleroma/accounts/#{user.id}/favourites?since_id=#{third_activity.id}&max_id=#{
+ seventh_activity.id
+ }"
+ )
+ |> json_response_and_validate_schema(:ok)
assert length(response) == 3
refute third_activity in response
@@ -256,8 +296,8 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
response =
conn
- |> get("/api/v1/pleroma/accounts/#{user.id}/favourites", %{limit: "3"})
- |> json_response(:ok)
+ |> get("/api/v1/pleroma/accounts/#{user.id}/favourites?limit=3")
+ |> json_response_and_validate_schema(:ok)
assert length(response) == 3
end
@@ -269,7 +309,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
response =
conn
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert Enum.empty?(response)
end
@@ -277,7 +317,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
test "returns 404 error when specified user is not exist", %{conn: conn} do
conn = get(conn, "/api/v1/pleroma/accounts/test/favourites")
- assert json_response(conn, 404) == %{"error" => "Record not found"}
+ assert json_response_and_validate_schema(conn, 404) == %{"error" => "Record not found"}
end
test "returns 403 error when user has hidden own favorites", %{conn: conn} do
@@ -287,7 +327,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
conn = get(conn, "/api/v1/pleroma/accounts/#{user.id}/favourites")
- assert json_response(conn, 403) == %{"error" => "Can't get favorites"}
+ assert json_response_and_validate_schema(conn, 403) == %{"error" => "Can't get favorites"}
end
test "hides favorites for new users by default", %{conn: conn} do
@@ -298,7 +338,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
assert user.hide_favorites
conn = get(conn, "/api/v1/pleroma/accounts/#{user.id}/favourites")
- assert json_response(conn, 403) == %{"error" => "Can't get favorites"}
+ assert json_response_and_validate_schema(conn, 403) == %{"error" => "Can't get favorites"}
end
end
@@ -312,11 +352,12 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
|> assign(:user, user)
|> post("/api/v1/pleroma/accounts/#{subscription_target.id}/subscribe")
- assert %{"id" => _id, "subscribing" => true} = json_response(ret_conn, 200)
+ assert %{"id" => _id, "subscribing" => true} =
+ json_response_and_validate_schema(ret_conn, 200)
conn = post(conn, "/api/v1/pleroma/accounts/#{subscription_target.id}/unsubscribe")
- assert %{"id" => _id, "subscribing" => false} = json_response(conn, 200)
+ assert %{"id" => _id, "subscribing" => false} = json_response_and_validate_schema(conn, 200)
end
end
@@ -326,7 +367,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
conn = post(conn, "/api/v1/pleroma/accounts/target_id/subscribe")
- assert %{"error" => "Record not found"} = json_response(conn, 404)
+ assert %{"error" => "Record not found"} = json_response_and_validate_schema(conn, 404)
end
end
@@ -336,7 +377,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
conn = post(conn, "/api/v1/pleroma/accounts/target_id/unsubscribe")
- assert %{"error" => "Record not found"} = json_response(conn, 404)
+ assert %{"error" => "Record not found"} = json_response_and_validate_schema(conn, 404)
end
end
end
--
cgit v1.2.3
From 9cbf17d59fe34a760f8a4f94bc60f78b38ccba06 Mon Sep 17 00:00:00 2001
From: Alex Gleason
Date: Tue, 12 May 2020 16:57:01 -0500
Subject: Handle bcrypt passwords for Mastodon migration
---
test/plugs/authentication_plug_test.exs | 7 +++++++
1 file changed, 7 insertions(+)
(limited to 'test')
diff --git a/test/plugs/authentication_plug_test.exs b/test/plugs/authentication_plug_test.exs
index 31e20d726..c8ede71c0 100644
--- a/test/plugs/authentication_plug_test.exs
+++ b/test/plugs/authentication_plug_test.exs
@@ -79,6 +79,13 @@ defmodule Pleroma.Plugs.AuthenticationPlugTest do
assert AuthenticationPlug.checkpw("password", hash)
end
+ test "check bcrypt hash" do
+ hash = "$2a$10$uyhC/R/zoE1ndwwCtMusK.TLVzkQ/Ugsbqp3uXI.CTTz0gBw.24jS"
+
+ assert AuthenticationPlug.checkpw("password", hash)
+ refute AuthenticationPlug.checkpw("password1", hash)
+ end
+
test "it returns false when hash invalid" do
hash =
"psBWV8gxkGOZWBz$PmfCycChoxeJ3GgGzwvhlgacb9mUoZ.KUXNCssekER4SJ7bOK53uXrHNb2e4i8yPFgSKyzaW9CcmrDXWIEMtD1"
--
cgit v1.2.3
From e688d4ee69dfbda0f8fd3a5544720a566b3946c5 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Tue, 14 Apr 2020 18:59:04 +0200
Subject: MRF.StealEmojiPolicy: New Policy
Inspired by https://git.pleroma.social/moonman/emoji-stealer-mrf/-/blob/master/steal_emoji_policy.ex
---
test/support/http_request_mock.ex | 4 ++
.../activity_pub/mrf/steal_emoji_policy_test.exs | 64 ++++++++++++++++++++++
2 files changed, 68 insertions(+)
create mode 100644 test/web/activity_pub/mrf/steal_emoji_policy_test.exs
(limited to 'test')
diff --git a/test/support/http_request_mock.ex b/test/support/http_request_mock.ex
index 3a95e92da..3d5128835 100644
--- a/test/support/http_request_mock.ex
+++ b/test/support/http_request_mock.ex
@@ -1291,6 +1291,10 @@ defmodule HttpRequestMock do
}}
end
+ def get("https://example.org/emoji/firedfox.png", _, _, _) do
+ {:ok, %Tesla.Env{status: 200, body: File.read!("test/fixtures/image.jpg")}}
+ end
+
def get("https://skippers-bin.com/users/7v1w1r8ce6", _, _, _) do
{:ok, %Tesla.Env{status: 200, body: File.read!("test/fixtures/tesla_mock/sjw.json")}}
end
diff --git a/test/web/activity_pub/mrf/steal_emoji_policy_test.exs b/test/web/activity_pub/mrf/steal_emoji_policy_test.exs
new file mode 100644
index 000000000..8882c8c13
--- /dev/null
+++ b/test/web/activity_pub/mrf/steal_emoji_policy_test.exs
@@ -0,0 +1,64 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicyTest do
+ use Pleroma.DataCase
+
+ alias Pleroma.Config
+ alias Pleroma.Web.ActivityPub.MRF.StealEmojiPolicy
+
+ setup_all do
+ Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
+ :ok
+ end
+
+ setup do
+ clear_config(:mrf_steal_emoji)
+
+ emoji_path = Path.join(Config.get([:instance, :static_dir]), "emoji/stolen")
+ File.rm_rf!(emoji_path)
+ File.mkdir!(emoji_path)
+
+ Pleroma.Emoji.reload()
+ end
+
+ test "does nothing by default" do
+ installed_emoji = Pleroma.Emoji.get_all() |> Enum.map(fn {k, _} -> k end)
+ refute "firedfox" in installed_emoji
+
+ message = %{
+ "type" => "Create",
+ "object" => %{
+ "emoji" => [{"firedfox", "https://example.org/emoji/firedfox.png"}],
+ "actor" => "https://example.org/users/admin"
+ }
+ }
+
+ assert {:ok, message} == StealEmojiPolicy.filter(message)
+
+ installed_emoji = Pleroma.Emoji.get_all() |> Enum.map(fn {k, _} -> k end)
+ refute "firedfox" in installed_emoji
+ end
+
+ test "Steals emoji on unknown shortcode from allowed remote host" do
+ installed_emoji = Pleroma.Emoji.get_all() |> Enum.map(fn {k, _} -> k end)
+ refute "firedfox" in installed_emoji
+
+ message = %{
+ "type" => "Create",
+ "object" => %{
+ "emoji" => [{"firedfox", "https://example.org/emoji/firedfox.png"}],
+ "actor" => "https://example.org/users/admin"
+ }
+ }
+
+ Config.put([:mrf_steal_emoji, :hosts], ["example.org"])
+ Config.put([:mrf_steal_emoji, :size_limit], 284_468)
+
+ assert {:ok, message} == StealEmojiPolicy.filter(message)
+
+ installed_emoji = Pleroma.Emoji.get_all() |> Enum.map(fn {k, _} -> k end)
+ assert "firedfox" in installed_emoji
+ end
+end
--
cgit v1.2.3
From cb363f018380cceb9531e0ddd12a979b8accc0b2 Mon Sep 17 00:00:00 2001
From: "Haelwenn (lanodan) Monnier"
Date: Wed, 29 Apr 2020 17:38:14 +0200
Subject: MastodonAPI: /api/v2/media endpoints
---
.../controllers/media_controller_test.exs | 62 ++++++++++++++++++++--
1 file changed, 57 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/media_controller_test.exs b/test/web/mastodon_api/controllers/media_controller_test.exs
index 6ac4cf63b..d872ff484 100644
--- a/test/web/mastodon_api/controllers/media_controller_test.exs
+++ b/test/web/mastodon_api/controllers/media_controller_test.exs
@@ -11,7 +11,7 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
setup do: oauth_access(["write:media"])
- describe "media upload" do
+ describe "Upload media" do
setup do
image = %Plug.Upload{
content_type: "image/jpg",
@@ -25,7 +25,7 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
setup do: clear_config([:media_proxy])
setup do: clear_config([Pleroma.Upload])
- test "returns uploaded image", %{conn: conn, image: image} do
+ test "/api/v1/media", %{conn: conn, image: image} do
desc = "Description of the image"
media =
@@ -40,9 +40,31 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
object = Object.get_by_id(media["id"])
assert object.data["actor"] == User.ap_id(conn.assigns[:user])
end
+
+ test "/api/v2/media", %{conn: conn, image: image} do
+ desc = "Description of the image"
+
+ response =
+ conn
+ |> post("/api/v2/media", %{"file" => image, "description" => desc})
+ |> json_response(202)
+
+ assert media_id = response["id"]
+
+ media =
+ conn
+ |> get("/api/v1/media/#{media_id}")
+ |> json_response(200)
+
+ assert media["type"] == "image"
+ assert media["description"] == desc
+ assert media["id"]
+ object = Object.get_by_id(media["id"])
+ assert object.data["actor"] == User.ap_id(conn.assigns[:user])
+ end
end
- describe "PUT /api/v1/media/:id" do
+ describe "Update media description" do
setup %{user: actor} do
file = %Plug.Upload{
content_type: "image/jpg",
@@ -60,7 +82,7 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
[object: object]
end
- test "updates name of media", %{conn: conn, object: object} do
+ test "/api/v1/media/:id good request", %{conn: conn, object: object} do
media =
conn
|> put("/api/v1/media/#{object.id}", %{"description" => "test-media"})
@@ -70,7 +92,7 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
assert refresh_record(object).data["name"] == "test-media"
end
- test "returns error when request is bad", %{conn: conn, object: object} do
+ test "/api/v1/media/:id bad request", %{conn: conn, object: object} do
media =
conn
|> put("/api/v1/media/#{object.id}", %{})
@@ -79,4 +101,34 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
assert media == %{"error" => "bad_request"}
end
end
+
+ describe "Get media by id" do
+ setup %{user: actor} do
+ file = %Plug.Upload{
+ content_type: "image/jpg",
+ path: Path.absname("test/fixtures/image.jpg"),
+ filename: "an_image.jpg"
+ }
+
+ {:ok, %Object{} = object} =
+ ActivityPub.upload(
+ file,
+ actor: User.ap_id(actor),
+ description: "test-media"
+ )
+
+ [object: object]
+ end
+
+ test "/api/v1/media/:id", %{conn: conn, object: object} do
+ media =
+ conn
+ |> get("/api/v1/media/#{object.id}")
+ |> json_response(:ok)
+
+ assert media["description"] == "test-media"
+ assert media["type"] == "image"
+ assert media["id"]
+ end
+ end
end
--
cgit v1.2.3
From 20cbfb5cb5515044de03cc48e8464ec45ad0ca50 Mon Sep 17 00:00:00 2001
From: Stephanie Wilde-Hobbs
Date: Thu, 14 May 2020 12:34:46 +0100
Subject: Allow whitelisting whole groups
---
test/web/admin_api/admin_api_controller_test.exs | 17 ++++++++++++-----
1 file changed, 12 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 7d42a400c..e573220ba 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -2948,7 +2948,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
clear_config(:database_config_whitelist, [
{:pleroma, :key1},
{:pleroma, :key2},
- {:pleroma, Pleroma.Captcha.NotReal}
+ {:pleroma, Pleroma.Captcha.NotReal},
+ {:not_real}
])
post(conn, "/api/pleroma/admin/config", %{
@@ -2957,7 +2958,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
%{group: ":pleroma", key: ":key2", value: "value2"},
%{group: ":pleroma", key: ":key3", value: "value3"},
%{group: ":pleroma", key: "Pleroma.Web.Endpoint.NotReal", value: "value4"},
- %{group: ":pleroma", key: "Pleroma.Captcha.NotReal", value: "value5"}
+ %{group: ":pleroma", key: "Pleroma.Captcha.NotReal", value: "value5"},
+ %{group: ":not_real", key: ":anything", value: "value6"}
]
})
@@ -2966,6 +2968,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
assert Application.get_env(:pleroma, :key3) == nil
assert Application.get_env(:pleroma, Pleroma.Web.Endpoint.NotReal) == nil
assert Application.get_env(:pleroma, Pleroma.Captcha.NotReal) == "value5"
+ assert Application.get_env(:not_real, :anything) == "value6"
end
end
@@ -3624,7 +3627,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
clear_config(:database_config_whitelist, [
{:pleroma, :instance},
{:pleroma, :activitypub},
- {:pleroma, Pleroma.Upload}
+ {:pleroma, Pleroma.Upload},
+ {:esshd}
])
admin = insert(:user, is_admin: true)
@@ -3635,9 +3639,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
children = json_response(conn, 200)
- assert length(children) == 3
+ assert length(children) == 4
- assert Enum.all?(children, fn c -> c["group"] == ":pleroma" end)
+ assert Enum.count(children, fn c -> c["group"] == ":pleroma" end) == 3
instance = Enum.find(children, fn c -> c["key"] == ":instance" end)
assert instance["children"]
@@ -3647,6 +3651,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
web_endpoint = Enum.find(children, fn c -> c["key"] == "Pleroma.Upload" end)
assert web_endpoint["children"]
+
+ esshd = Enum.find(children, fn c -> c["group"] == ":esshd" end)
+ assert esshd["children"]
end
end
--
cgit v1.2.3
From 0f885b4b86ad7ba738ef0dd0de7f7d0496b7e43d Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 14 May 2020 16:18:30 +0400
Subject: Fix OpenAPI spec
---
.../mastodon_api/controllers/media_controller_test.exs | 16 ++++++++++------
1 file changed, 10 insertions(+), 6 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/media_controller_test.exs b/test/web/mastodon_api/controllers/media_controller_test.exs
index d872ff484..715747818 100644
--- a/test/web/mastodon_api/controllers/media_controller_test.exs
+++ b/test/web/mastodon_api/controllers/media_controller_test.exs
@@ -30,8 +30,9 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
media =
conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/v1/media", %{"file" => image, "description" => desc})
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert media["type"] == "image"
assert media["description"] == desc
@@ -46,15 +47,16 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
response =
conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/v2/media", %{"file" => image, "description" => desc})
- |> json_response(202)
+ |> json_response_and_validate_schema(202)
assert media_id = response["id"]
media =
conn
|> get("/api/v1/media/#{media_id}")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert media["type"] == "image"
assert media["description"] == desc
@@ -85,8 +87,9 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
test "/api/v1/media/:id good request", %{conn: conn, object: object} do
media =
conn
+ |> put_req_header("content-type", "multipart/form-data")
|> put("/api/v1/media/#{object.id}", %{"description" => "test-media"})
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert media["description"] == "test-media"
assert refresh_record(object).data["name"] == "test-media"
@@ -95,8 +98,9 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
test "/api/v1/media/:id bad request", %{conn: conn, object: object} do
media =
conn
+ |> put_req_header("content-type", "multipart/form-data")
|> put("/api/v1/media/#{object.id}", %{})
- |> json_response(400)
+ |> json_response_and_validate_schema(400)
assert media == %{"error" => "bad_request"}
end
@@ -124,7 +128,7 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
media =
conn
|> get("/api/v1/media/#{object.id}")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert media["description"] == "test-media"
assert media["type"] == "image"
--
cgit v1.2.3
From bb03dfdb03714027640087ad1bd6475a8bb1c2c3 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 14 May 2020 16:29:32 +0400
Subject: Do not require `description` in `update` action
---
test/web/mastodon_api/controllers/media_controller_test.exs | 10 ----------
1 file changed, 10 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/media_controller_test.exs b/test/web/mastodon_api/controllers/media_controller_test.exs
index 715747818..7ba1727f2 100644
--- a/test/web/mastodon_api/controllers/media_controller_test.exs
+++ b/test/web/mastodon_api/controllers/media_controller_test.exs
@@ -94,16 +94,6 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
assert media["description"] == "test-media"
assert refresh_record(object).data["name"] == "test-media"
end
-
- test "/api/v1/media/:id bad request", %{conn: conn, object: object} do
- media =
- conn
- |> put_req_header("content-type", "multipart/form-data")
- |> put("/api/v1/media/#{object.id}", %{})
- |> json_response_and_validate_schema(400)
-
- assert media == %{"error" => "bad_request"}
- end
end
describe "Get media by id" do
--
cgit v1.2.3
From 3c29f4f957dbfa4bf7b914ecc1680bfa71bb7621 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Fri, 15 May 2020 16:16:02 +0300
Subject: returning partial chain
---
test/config/config_db_test.exs | 8 ++++++++
test/web/admin_api/admin_api_controller_test.exs | 3 +++
2 files changed, 11 insertions(+)
(limited to 'test')
diff --git a/test/config/config_db_test.exs b/test/config/config_db_test.exs
index a8e947365..336de7359 100644
--- a/test/config/config_db_test.exs
+++ b/test/config/config_db_test.exs
@@ -476,6 +476,14 @@ defmodule Pleroma.ConfigDBTest do
assert ConfigDB.from_binary(binary) == [key: "value"]
end
+ test "keyword with partial_chain key" do
+ binary =
+ ConfigDB.transform([%{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]}])
+
+ assert binary == :erlang.term_to_binary(partial_chain: &:hackney_connect.partial_chain/1)
+ assert ConfigDB.from_binary(binary) == [partial_chain: &:hackney_connect.partial_chain/1]
+ end
+
test "keyword" do
binary =
ConfigDB.transform([
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 9b7120712..370d876d0 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -2509,6 +2509,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
%{"tuple" => [":seconds_valid", 60]},
%{"tuple" => [":path", ""]},
%{"tuple" => [":key1", nil]},
+ %{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]},
%{"tuple" => [":regex1", "~r/https:\/\/example.com/"]},
%{"tuple" => [":regex2", "~r/https:\/\/example.com/u"]},
%{"tuple" => [":regex3", "~r/https:\/\/example.com/i"]},
@@ -2532,6 +2533,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
%{"tuple" => [":seconds_valid", 60]},
%{"tuple" => [":path", ""]},
%{"tuple" => [":key1", nil]},
+ %{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]},
%{"tuple" => [":regex1", "~r/https:\\/\\/example.com/"]},
%{"tuple" => [":regex2", "~r/https:\\/\\/example.com/u"]},
%{"tuple" => [":regex3", "~r/https:\\/\\/example.com/i"]},
@@ -2544,6 +2546,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
":seconds_valid",
":path",
":key1",
+ ":partial_chain",
":regex1",
":regex2",
":regex3",
--
cgit v1.2.3
From 2dcb26a6e52b18c62aaa1ef464d94685732496ab Mon Sep 17 00:00:00 2001
From: lain
Date: Sat, 16 May 2020 12:28:24 +0200
Subject: CommonAPI: Unblock a user even if we don't have an activity.
---
test/web/common_api/common_api_test.exs | 12 ++++++++++++
1 file changed, 12 insertions(+)
(limited to 'test')
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index 26e41c313..fd8299013 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -23,6 +23,18 @@ defmodule Pleroma.Web.CommonAPITest do
setup do: clear_config([:instance, :limit])
setup do: clear_config([:instance, :max_pinned_statuses])
+ describe "unblocking" do
+ test "it works even without an existing block activity" do
+ blocked = insert(:user)
+ blocker = insert(:user)
+ User.block(blocker, blocked)
+
+ assert User.blocks?(blocker, blocked)
+ assert {:ok, :no_activity} == CommonAPI.unblock(blocker, blocked)
+ refute User.blocks?(blocker, blocked)
+ end
+ end
+
describe "deletion" do
test "it works with pruned objects" do
user = insert(:user)
--
cgit v1.2.3
From af9dfdce6b502d3a33db7a496879dda56719f56e Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Sun, 17 May 2020 08:46:43 +0300
Subject: MediaController OAuth scope assignments fix. Typo fix (`def
get_media` instead of `def show`).
---
.../web/mastodon_api/controllers/media_controller_test.exs | 14 +++++++++++---
1 file changed, 11 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/media_controller_test.exs b/test/web/mastodon_api/controllers/media_controller_test.exs
index 7ba1727f2..98ec239b1 100644
--- a/test/web/mastodon_api/controllers/media_controller_test.exs
+++ b/test/web/mastodon_api/controllers/media_controller_test.exs
@@ -9,9 +9,9 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
- setup do: oauth_access(["write:media"])
-
describe "Upload media" do
+ setup do: oauth_access(["write:media"])
+
setup do
image = %Plug.Upload{
content_type: "image/jpg",
@@ -42,7 +42,7 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
assert object.data["actor"] == User.ap_id(conn.assigns[:user])
end
- test "/api/v2/media", %{conn: conn, image: image} do
+ test "/api/v2/media", %{conn: conn, user: user, image: image} do
desc = "Description of the image"
response =
@@ -53,6 +53,8 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
assert media_id = response["id"]
+ %{conn: conn} = oauth_access(["read:media"], user: user)
+
media =
conn
|> get("/api/v1/media/#{media_id}")
@@ -62,11 +64,15 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
assert media["description"] == desc
assert media["id"]
object = Object.get_by_id(media["id"])
+
+ # TODO: clarify: if this EP allows access to non-owned objects, the following may be false:
assert object.data["actor"] == User.ap_id(conn.assigns[:user])
end
end
describe "Update media description" do
+ setup do: oauth_access(["write:media"])
+
setup %{user: actor} do
file = %Plug.Upload{
content_type: "image/jpg",
@@ -97,6 +103,8 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
end
describe "Get media by id" do
+ setup do: oauth_access(["read:media"])
+
setup %{user: actor} do
file = %Plug.Upload{
content_type: "image/jpg",
--
cgit v1.2.3
From baef35bcc8685757b0039f76d2614bbb08e410f7 Mon Sep 17 00:00:00 2001
From: lain
Date: Sun, 17 May 2020 10:31:01 +0200
Subject: Authentication Plug: Update bcrypt password on login.
---
test/plugs/authentication_plug_test.exs | 18 ++++++++++++------
1 file changed, 12 insertions(+), 6 deletions(-)
(limited to 'test')
diff --git a/test/plugs/authentication_plug_test.exs b/test/plugs/authentication_plug_test.exs
index c8ede71c0..2c793b29a 100644
--- a/test/plugs/authentication_plug_test.exs
+++ b/test/plugs/authentication_plug_test.exs
@@ -11,6 +11,7 @@ defmodule Pleroma.Plugs.AuthenticationPlugTest do
alias Pleroma.User
import ExUnit.CaptureLog
+ import Pleroma.Factory
setup %{conn: conn} do
user = %User{
@@ -50,16 +51,21 @@ defmodule Pleroma.Plugs.AuthenticationPlugTest do
assert PlugHelper.plug_skipped?(conn, OAuthScopesPlug)
end
- test "with a wrong password in the credentials, it does nothing", %{conn: conn} do
- conn =
- conn
- |> assign(:auth_credentials, %{password: "wrong"})
+ test "with a bcrypt hash, it updates to a pkbdf2 hash", %{conn: conn} do
+ user = insert(:user, password_hash: Bcrypt.hash_pwd_salt("123"))
+ assert "$2" <> _ = user.password_hash
- ret_conn =
+ conn =
conn
+ |> assign(:auth_user, user)
+ |> assign(:auth_credentials, %{password: "123"})
|> AuthenticationPlug.call(%{})
- assert conn == ret_conn
+ assert conn.assigns.user.id == conn.assigns.auth_user.id
+ assert PlugHelper.plug_skipped?(conn, OAuthScopesPlug)
+
+ user = User.get_by_id(user.id)
+ assert "$pbkdf2" <> _ = user.password_hash
end
describe "checkpw/2" do
--
cgit v1.2.3
From bfdd90f6d7c9bb85e572033070d6fa7efda8aeac Mon Sep 17 00:00:00 2001
From: lain
Date: Sun, 17 May 2020 11:40:25 +0200
Subject: AuthenticationPlug: Also update crypt passwords.
---
test/plugs/authentication_plug_test.exs | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
(limited to 'test')
diff --git a/test/plugs/authentication_plug_test.exs b/test/plugs/authentication_plug_test.exs
index 2c793b29a..3c70c1747 100644
--- a/test/plugs/authentication_plug_test.exs
+++ b/test/plugs/authentication_plug_test.exs
@@ -68,6 +68,26 @@ defmodule Pleroma.Plugs.AuthenticationPlugTest do
assert "$pbkdf2" <> _ = user.password_hash
end
+ test "with a crypt hash, it updates to a pkbdf2 hash", %{conn: conn} do
+ user =
+ insert(:user,
+ password_hash:
+ "$6$9psBWV8gxkGOZWBz$PmfCycChoxeJ3GgGzwvhlgacb9mUoZ.KUXNCssekER4SJ7bOK53uXrHNb2e4i8yPFgSKyzaW9CcmrDXWIEMtD1"
+ )
+
+ conn =
+ conn
+ |> assign(:auth_user, user)
+ |> assign(:auth_credentials, %{password: "password"})
+ |> AuthenticationPlug.call(%{})
+
+ assert conn.assigns.user.id == conn.assigns.auth_user.id
+ assert PlugHelper.plug_skipped?(conn, OAuthScopesPlug)
+
+ user = User.get_by_id(user.id)
+ assert "$pbkdf2" <> _ = user.password_hash
+ end
+
describe "checkpw/2" do
test "check pbkdf2 hash" do
hash =
--
cgit v1.2.3
From 8bfd9710ae70204b29e184f08d78b95a2f81ad6c Mon Sep 17 00:00:00 2001
From: lain
Date: Sun, 17 May 2020 11:53:17 +0200
Subject: Pleroma Authenticator: Also update passwords here.
---
test/web/auth/pleroma_authenticator_test.exs | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/auth/pleroma_authenticator_test.exs b/test/web/auth/pleroma_authenticator_test.exs
index 5a421e5ed..731bd5932 100644
--- a/test/web/auth/pleroma_authenticator_test.exs
+++ b/test/web/auth/pleroma_authenticator_test.exs
@@ -15,11 +15,16 @@ defmodule Pleroma.Web.Auth.PleromaAuthenticatorTest do
{:ok, [user: user, name: name, password: password]}
end
- test "get_user/authorization", %{user: user, name: name, password: password} do
+ test "get_user/authorization", %{name: name, password: password} do
+ name = name <> "1"
+ user = insert(:user, nickname: name, password_hash: Bcrypt.hash_pwd_salt(password))
+
params = %{"authorization" => %{"name" => name, "password" => password}}
res = PleromaAuthenticator.get_user(%Plug.Conn{params: params})
- assert {:ok, user} == res
+ assert {:ok, returned_user} = res
+ assert returned_user.id == user.id
+ assert "$pbkdf2" <> _ = returned_user.password_hash
end
test "get_user/authorization with invalid password", %{name: name} do
--
cgit v1.2.3
From 9b765652649f8b6110bd70aa90b148a90057ff6a Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Mon, 18 May 2020 09:51:53 +0300
Subject: MediaController: enforced owner-only access in :show action. Improved
error response on denied access (now 403). Adjusted tests.
---
.../controllers/media_controller_test.exs | 20 +++++++++++++++-----
1 file changed, 15 insertions(+), 5 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/media_controller_test.exs b/test/web/mastodon_api/controllers/media_controller_test.exs
index 98ec239b1..906fd940f 100644
--- a/test/web/mastodon_api/controllers/media_controller_test.exs
+++ b/test/web/mastodon_api/controllers/media_controller_test.exs
@@ -63,10 +63,9 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
assert media["type"] == "image"
assert media["description"] == desc
assert media["id"]
- object = Object.get_by_id(media["id"])
- # TODO: clarify: if this EP allows access to non-owned objects, the following may be false:
- assert object.data["actor"] == User.ap_id(conn.assigns[:user])
+ object = Object.get_by_id(media["id"])
+ assert object.data["actor"] == user.ap_id
end
end
@@ -102,7 +101,7 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
end
end
- describe "Get media by id" do
+ describe "Get media by id (/api/v1/media/:id)" do
setup do: oauth_access(["read:media"])
setup %{user: actor} do
@@ -122,7 +121,7 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
[object: object]
end
- test "/api/v1/media/:id", %{conn: conn, object: object} do
+ test "it returns media object when requested by owner", %{conn: conn, object: object} do
media =
conn
|> get("/api/v1/media/#{object.id}")
@@ -132,5 +131,16 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
assert media["type"] == "image"
assert media["id"]
end
+
+ test "it returns 403 if media object requested by non-owner", %{object: object, user: user} do
+ %{conn: conn, user: other_user} = oauth_access(["read:media"])
+
+ assert object.data["actor"] == user.ap_id
+ refute user.id == other_user.id
+
+ conn
+ |> get("/api/v1/media/#{object.id}")
+ |> json_response(403)
+ end
end
end
--
cgit v1.2.3
From 188b32145e0a97411878a11bd4f8ad8bc9cc1d9a Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 18 May 2020 13:28:50 +0200
Subject: InstanceView: Expose background image link.
This will make it easier for more clients to support this feature.
---
test/web/mastodon_api/controllers/instance_controller_test.exs | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/instance_controller_test.exs b/test/web/mastodon_api/controllers/instance_controller_test.exs
index 2c61dc5ba..8bdfdddd1 100644
--- a/test/web/mastodon_api/controllers/instance_controller_test.exs
+++ b/test/web/mastodon_api/controllers/instance_controller_test.exs
@@ -31,7 +31,8 @@ defmodule Pleroma.Web.MastodonAPI.InstanceControllerTest do
"upload_limit" => _,
"avatar_upload_limit" => _,
"background_upload_limit" => _,
- "banner_upload_limit" => _
+ "banner_upload_limit" => _,
+ "background_image" => _
} = result
assert result["pleroma"]["metadata"]["features"]
--
cgit v1.2.3
From 215daabdb4441ca6620366cc06c6827c8dc69bc5 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Mon, 18 May 2020 15:15:51 +0300
Subject: copyright update
---
test/web/auth/pleroma_authenticator_test.exs | 2 +-
test/web/auth/totp_authenticator_test.exs | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/auth/pleroma_authenticator_test.exs b/test/web/auth/pleroma_authenticator_test.exs
index 731bd5932..1ba0dfecc 100644
--- a/test/web/auth/pleroma_authenticator_test.exs
+++ b/test/web/auth/pleroma_authenticator_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.Auth.PleromaAuthenticatorTest do
diff --git a/test/web/auth/totp_authenticator_test.exs b/test/web/auth/totp_authenticator_test.exs
index e502e0ae8..84d4cd840 100644
--- a/test/web/auth/totp_authenticator_test.exs
+++ b/test/web/auth/totp_authenticator_test.exs
@@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors
+# Copyright © 2017-2020 Pleroma Authors
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.Auth.TOTPAuthenticatorTest do
--
cgit v1.2.3
From 7d381b16b7b80a22dd9964fb5618998ae41b9c08 Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 18 May 2020 14:48:37 +0200
Subject: Transmogrifier Test: Extract Announce handling.
---
.../fixtures/kroeg-announce-with-inline-actor.json | 89 +++++++-
.../transmogrifier/announce_handling_test.exs | 158 +++++++++++++++
test/web/activity_pub/transmogrifier_test.exs | 223 ++++++---------------
3 files changed, 303 insertions(+), 167 deletions(-)
create mode 100644 test/web/activity_pub/transmogrifier/announce_handling_test.exs
(limited to 'test')
diff --git a/test/fixtures/kroeg-announce-with-inline-actor.json b/test/fixtures/kroeg-announce-with-inline-actor.json
index 7bd6e8199..f73f93410 100644
--- a/test/fixtures/kroeg-announce-with-inline-actor.json
+++ b/test/fixtures/kroeg-announce-with-inline-actor.json
@@ -1 +1,88 @@
-{"@context":["https://www.w3.org/ns/activitystreams","https://puckipedia.com/-/context"],"actor":{"endpoints":"https://puckipedia.com/#endpoints","followers":"https://puckipedia.com/followers","following":"https://puckipedia.com/following","icon":{"mediaType":"image/png","type":"Image","url":"https://puckipedia.com/images/avatar.png"},"id":"https://puckipedia.com/","inbox":"https://puckipedia.com/inbox","kroeg:blocks":{"id":"https://puckipedia.com/blocks"},"liked":"https://puckipedia.com/liked","manuallyApprovesFollowers":false,"name":"HACKER TEEN PUCKIPEDIA 👩💻","outbox":"https://puckipedia.com/outbox","preferredUsername":"puckipedia","publicKey":{"id":"https://puckipedia.com/#key","owner":"https://puckipedia.com/","publicKeyPem":"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvN05xIcFE0Qgany7Rht4\n0ZI5wu++IT7K5iSqRimBYkpoeHbVcT9RFlW+aWH/QJJW/YgZ7+LMr8AMCrKrwSpS\nCndyrpx4O4lZ3FNRLu7tbklh01rGZfE6R1SFfYBpvMvImc9nYT6iezYDbv6NkHku\no3aVhjql216XlA0OhIrqQme9sAdrLbjbMrTUS8douCTkDOX+JFj1ghHCqdYEMZJI\nOY9kovtgnqyxFLm0RsPGsO1+g/OVojqG+VqHz6O2lceaTVQLlnZ4gOhLVG1tVsA2\nRfXQK+R/VgXncYE+BlQVd/tcdGAz7CDL7PP3rP65gmARnafhGR96cCOi/KzlAXSO\nMwIDAQAB\n-----END PUBLIC KEY-----","type":[]},"summary":"federated hacker teen
\n[she/they]
","type":"Person","updated":"2017-12-19T16:56:29.7576707+00:00"},"cc":"http://mastodon.example.org/users/admin","id":"https://puckipedia.com/cc56a9658e","object":{"as:sensitive":false,"attributedTo":{"endpoints":{"sharedInbox":"https://mastodon.social/inbox","type":[]},"followers":"http://mastodon.example.org/users/admin/followers","following":"http://mastodon.example.org/users/admin/following","icon":{"mediaType":"image/png","type":"Image","url":"https://files.mastodon.social/accounts/avatars/000/015/163/original/70ca6c52b01ca913.png"},"id":"http://mastodon.example.org/users/admin","inbox":"http://mastodon.example.org/users/admin/inbox","manuallyApprovesFollowers":{"@value":"False","type":"xsd:boolean"},"name":"","outbox":"http://mastodon.example.org/users/admin/outbox","preferredUsername":"revenant","publicKey":{"id":"http://mastodon.example.org/users/admin#main-key","owner":"http://mastodon.example.org/users/admin","publicKeyPem":"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0gEN3wPW7gkE2gQqnmfB\n1ychjmFIf2LIwY0oCJLiGE/xpZrUKoq+eWH30AP7mATw4LD0gOYABL/ijqPUrPqR\nDXLL+0CqMP8HsZKvRlj9KArMK3YtNiSGGj2U7iReiRrD7nJzjJlsjjJXflLZhZ7/\nenSv1CcaeK8tB0PoAgShy/MyfhPF7WI5/Zm9DmmDQFvUEnDYKXAf/vG/IWw1EyMC\nkbaEYJeIowQU3GsbPxzRGI22bQtfotm431Ch2MbNo+kyzmYVFLAVoSGNMzvJwOPg\nTxLIIBeQXG7MinRyK887yPKhxhcALea4yCcALaa+3jPE7yqwIKYwTHtSlblsHDAo\nmQIDAQAB\n-----END PUBLIC KEY-----\n","type":[]},"summary":"neatly partitioned meats and cheeses appeal to me on an aesthetic level | any pronouns | revenant1.net
","type":"Person","url":"https://mastodon.social/@revenant"},"cc":"http://mastodon.example.org/users/admin/followers","content":"the name's jond (jeans bond)
","contentMap":{"en":"the name's jond (jeans bond)
"},"conversation":"tag:mastodon.social,2018-09-25:objectId=55659382:objectType=Conversation","id":"http://mastodon.example.org/users/admin/statuses/100787282858396771","ostatus:atomUri":"http://mastodon.example.org/users/admin/statuses/100787282858396771","published":"2018-09-25T16:11:29Z","to":"https://www.w3.org/ns/activitystreams#Public","type":"Note","url":"https://mastodon.social/@revenant/100787282858396771"},"to":["https://www.w3.org/ns/activitystreams#Public","https://puckipedia.com/followers"],"type":"Announce"}
+{
+ "@context" : [
+ "https://www.w3.org/ns/activitystreams",
+ "https://puckipedia.com/-/context"
+ ],
+ "actor" : {
+ "endpoints" : "https://puckipedia.com/#endpoints",
+ "followers" : "https://puckipedia.com/followers",
+ "following" : "https://puckipedia.com/following",
+ "icon" : {
+ "mediaType" : "image/png",
+ "type" : "Image",
+ "url" : "https://puckipedia.com/images/avatar.png"
+ },
+ "id" : "https://puckipedia.com/",
+ "inbox" : "https://puckipedia.com/inbox",
+ "kroeg:blocks" : {
+ "id" : "https://puckipedia.com/blocks"
+ },
+ "liked" : "https://puckipedia.com/liked",
+ "manuallyApprovesFollowers" : false,
+ "name" : "HACKER TEEN PUCKIPEDIA ð©âð»",
+ "outbox" : "https://puckipedia.com/outbox",
+ "preferredUsername" : "puckipedia",
+ "publicKey" : {
+ "id" : "https://puckipedia.com/#key",
+ "owner" : "https://puckipedia.com/",
+ "publicKeyPem" : "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvN05xIcFE0Qgany7Rht4\n0ZI5wu++IT7K5iSqRimBYkpoeHbVcT9RFlW+aWH/QJJW/YgZ7+LMr8AMCrKrwSpS\nCndyrpx4O4lZ3FNRLu7tbklh01rGZfE6R1SFfYBpvMvImc9nYT6iezYDbv6NkHku\no3aVhjql216XlA0OhIrqQme9sAdrLbjbMrTUS8douCTkDOX+JFj1ghHCqdYEMZJI\nOY9kovtgnqyxFLm0RsPGsO1+g/OVojqG+VqHz6O2lceaTVQLlnZ4gOhLVG1tVsA2\nRfXQK+R/VgXncYE+BlQVd/tcdGAz7CDL7PP3rP65gmARnafhGR96cCOi/KzlAXSO\nMwIDAQAB\n-----END PUBLIC KEY-----",
+ "type" : []
+ },
+ "summary" : "federated hacker teen
\n[she/they]
",
+ "type" : "Person",
+ "updated" : "2017-12-19T16:56:29.7576707+00:00"
+ },
+ "cc" : "http://mastodon.example.org/users/admin",
+ "id" : "https://puckipedia.com/cc56a9658e",
+ "object" : {
+ "as:sensitive" : false,
+ "attributedTo" : {
+ "endpoints" : {
+ "sharedInbox" : "https://mastodon.social/inbox",
+ "type" : []
+ },
+ "followers" : "http://mastodon.example.org/users/admin/followers",
+ "following" : "http://mastodon.example.org/users/admin/following",
+ "icon" : {
+ "mediaType" : "image/png",
+ "type" : "Image",
+ "url" : "https://files.mastodon.social/accounts/avatars/000/015/163/original/70ca6c52b01ca913.png"
+ },
+ "id" : "http://mastodon.example.org/users/admin",
+ "inbox" : "http://mastodon.example.org/users/admin/inbox",
+ "manuallyApprovesFollowers" : {
+ "@value" : "False",
+ "type" : "xsd:boolean"
+ },
+ "name" : "",
+ "outbox" : "http://mastodon.example.org/users/admin/outbox",
+ "preferredUsername" : "revenant",
+ "publicKey" : {
+ "id" : "http://mastodon.example.org/users/admin#main-key",
+ "owner" : "http://mastodon.example.org/users/admin",
+ "publicKeyPem" : "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0gEN3wPW7gkE2gQqnmfB\n1ychjmFIf2LIwY0oCJLiGE/xpZrUKoq+eWH30AP7mATw4LD0gOYABL/ijqPUrPqR\nDXLL+0CqMP8HsZKvRlj9KArMK3YtNiSGGj2U7iReiRrD7nJzjJlsjjJXflLZhZ7/\nenSv1CcaeK8tB0PoAgShy/MyfhPF7WI5/Zm9DmmDQFvUEnDYKXAf/vG/IWw1EyMC\nkbaEYJeIowQU3GsbPxzRGI22bQtfotm431Ch2MbNo+kyzmYVFLAVoSGNMzvJwOPg\nTxLIIBeQXG7MinRyK887yPKhxhcALea4yCcALaa+3jPE7yqwIKYwTHtSlblsHDAo\nmQIDAQAB\n-----END PUBLIC KEY-----\n",
+ "type" : []
+ },
+ "summary" : "neatly partitioned meats and cheeses appeal to me on an aesthetic level | any pronouns | revenant1.net
",
+ "type" : "Person",
+ "url" : "https://mastodon.social/@revenant"
+ },
+ "cc" : "http://mastodon.example.org/users/admin/followers",
+ "content" : "the name's jond (jeans bond)
",
+ "contentMap" : {
+ "en" : "the name's jond (jeans bond)
"
+ },
+ "conversation" : "tag:mastodon.social,2018-09-25:objectId=55659382:objectType=Conversation",
+ "id" : "http://mastodon.example.org/users/admin/statuses/100787282858396771",
+ "ostatus:atomUri" : "http://mastodon.example.org/users/admin/statuses/100787282858396771",
+ "published" : "2018-09-25T16:11:29Z",
+ "to" : "https://www.w3.org/ns/activitystreams#Public",
+ "type" : "Note",
+ "url" : "https://mastodon.social/@revenant/100787282858396771"
+ },
+ "to" : [
+ "https://www.w3.org/ns/activitystreams#Public",
+ "https://puckipedia.com/followers"
+ ],
+ "type" : "Announce"
+}
diff --git a/test/web/activity_pub/transmogrifier/announce_handling_test.exs b/test/web/activity_pub/transmogrifier/announce_handling_test.exs
new file mode 100644
index 000000000..8a4af6546
--- /dev/null
+++ b/test/web/activity_pub/transmogrifier/announce_handling_test.exs
@@ -0,0 +1,158 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnnounceHandlingTest do
+ use Pleroma.DataCase
+
+ alias Pleroma.Activity
+ alias Pleroma.Object
+ alias Pleroma.Web.CommonAPI
+ alias Pleroma.Web.ActivityPub.Transmogrifier
+
+ import Pleroma.Factory
+
+ test "it works for incoming honk announces" do
+ _user = insert(:user, ap_id: "https://honktest/u/test", local: false)
+ other_user = insert(:user)
+ {:ok, post} = CommonAPI.post(other_user, %{status: "bonkeronk"})
+
+ announce = %{
+ "@context" => "https://www.w3.org/ns/activitystreams",
+ "actor" => "https://honktest/u/test",
+ "id" => "https://honktest/u/test/bonk/1793M7B9MQ48847vdx",
+ "object" => post.data["object"],
+ "published" => "2019-06-25T19:33:58Z",
+ "to" => "https://www.w3.org/ns/activitystreams#Public",
+ "type" => "Announce"
+ }
+
+ {:ok, %Activity{local: false}} = Transmogrifier.handle_incoming(announce)
+ end
+
+ test "it works for incoming announces with actor being inlined (kroeg)" do
+ data = File.read!("test/fixtures/kroeg-announce-with-inline-actor.json") |> Poison.decode!()
+
+ _user = insert(:user, local: false, ap_id: data["actor"]["id"])
+ other_user = insert(:user)
+
+ {:ok, post} = CommonAPI.post(other_user, %{status: "kroegeroeg"})
+
+ data =
+ data
+ |> put_in(["object", "id"], post.data["object"])
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert data["actor"] == "https://puckipedia.com/"
+ end
+
+ test "it works for incoming announces, fetching the announced object" do
+ Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
+ data = File.read!("test/fixtures/mastodon-announce.json") |> Poison.decode!()
+
+ _user = insert(:user, local: false, ap_id: data["actor"])
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert data["actor"] == "http://mastodon.example.org/users/admin"
+ assert data["type"] == "Announce"
+
+ assert data["id"] ==
+ "http://mastodon.example.org/users/admin/statuses/99542391527669785/activity"
+
+ assert data["object"] ==
+ "http://mastodon.example.org/users/admin/statuses/99541947525187367"
+
+ assert(Activity.get_create_by_object_ap_id(data["object"]))
+ end
+
+ @tag capture_log: true
+ test "it works for incoming announces with an existing activity" do
+ user = insert(:user)
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey"})
+
+ data =
+ File.read!("test/fixtures/mastodon-announce.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+
+ _user = insert(:user, local: false, ap_id: data["actor"])
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert data["actor"] == "http://mastodon.example.org/users/admin"
+ assert data["type"] == "Announce"
+
+ assert data["id"] ==
+ "http://mastodon.example.org/users/admin/statuses/99542391527669785/activity"
+
+ assert data["object"] == activity.data["object"]
+
+ assert Activity.get_create_by_object_ap_id(data["object"]).id == activity.id
+ end
+
+ test "it works for incoming announces with an inlined activity" do
+ data =
+ File.read!("test/fixtures/mastodon-announce-private.json")
+ |> Poison.decode!()
+
+ _user =
+ insert(:user,
+ local: false,
+ ap_id: data["actor"],
+ follower_address: data["actor"] <> "/followers"
+ )
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert data["actor"] == "http://mastodon.example.org/users/admin"
+ assert data["type"] == "Announce"
+
+ assert data["id"] ==
+ "http://mastodon.example.org/users/admin/statuses/99542391527669785/activity"
+
+ object = Object.normalize(data["object"])
+
+ assert object.data["id"] == "http://mastodon.example.org/@admin/99541947525187368"
+ assert object.data["content"] == "this is a private toot"
+ end
+
+ @tag capture_log: true
+ test "it rejects incoming announces with an inlined activity from another origin" do
+ Tesla.Mock.mock(fn
+ %{method: :get} -> %Tesla.Env{status: 404, body: ""}
+ end)
+
+ data =
+ File.read!("test/fixtures/bogus-mastodon-announce.json")
+ |> Poison.decode!()
+
+ _user = insert(:user, local: false, ap_id: data["actor"])
+
+ assert {:error, e} = Transmogrifier.handle_incoming(data)
+ end
+
+ test "it does not clobber the addressing on announce activities" do
+ user = insert(:user)
+ {:ok, activity} = CommonAPI.post(user, %{status: "hey"})
+
+ data =
+ File.read!("test/fixtures/mastodon-announce.json")
+ |> Poison.decode!()
+ |> Map.put("object", Object.normalize(activity).data["id"])
+ |> Map.put("to", ["http://mastodon.example.org/users/admin/followers"])
+ |> Map.put("cc", [])
+
+ _user =
+ insert(:user,
+ local: false,
+ ap_id: data["actor"],
+ follower_address: "http://mastodon.example.org/users/admin/followers"
+ )
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+
+ assert data["to"] == ["http://mastodon.example.org/users/admin/followers"]
+ end
+end
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 0a54e3bb9..ae88a4480 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -28,6 +28,63 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
setup do: clear_config([:instance, :max_remote_account_fields])
describe "handle_incoming" do
+ test "it works for incoming notices with tag not being an array (kroeg)" do
+ data = File.read!("test/fixtures/kroeg-array-less-emoji.json") |> Poison.decode!()
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+ object = Object.normalize(data["object"])
+
+ assert object.data["emoji"] == %{
+ "icon_e_smile" => "https://puckipedia.com/forum/images/smilies/icon_e_smile.png"
+ }
+
+ data = File.read!("test/fixtures/kroeg-array-less-hashtag.json") |> Poison.decode!()
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+ object = Object.normalize(data["object"])
+
+ assert "test" in object.data["tag"]
+ end
+
+ test "it works for incoming notices with url not being a string (prismo)" do
+ data = File.read!("test/fixtures/prismo-url-map.json") |> Poison.decode!()
+
+ {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
+ object = Object.normalize(data["object"])
+
+ assert object.data["url"] == "https://prismo.news/posts/83"
+ end
+
+ test "it cleans up incoming notices which are not really DMs" do
+ user = insert(:user)
+ other_user = insert(:user)
+
+ to = [user.ap_id, other_user.ap_id]
+
+ data =
+ File.read!("test/fixtures/mastodon-post-activity.json")
+ |> Poison.decode!()
+ |> Map.put("to", to)
+ |> Map.put("cc", [])
+
+ object =
+ data["object"]
+ |> Map.put("to", to)
+ |> Map.put("cc", [])
+
+ data = Map.put(data, "object", object)
+
+ {:ok, %Activity{data: data, local: false} = activity} = Transmogrifier.handle_incoming(data)
+
+ assert data["to"] == []
+ assert data["cc"] == to
+
+ object_data = Object.normalize(activity).data
+
+ assert object_data["to"] == []
+ assert object_data["cc"] == to
+ end
+
test "it ignores an incoming notice if we already have it" do
activity = insert(:note_activity)
@@ -260,172 +317,6 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
"henlo from my Psion netBook
message sent from my Psion netBook
"
end
- test "it works for incoming honk announces" do
- _user = insert(:user, ap_id: "https://honktest/u/test", local: false)
- other_user = insert(:user)
- {:ok, post} = CommonAPI.post(other_user, %{status: "bonkeronk"})
-
- announce = %{
- "@context" => "https://www.w3.org/ns/activitystreams",
- "actor" => "https://honktest/u/test",
- "id" => "https://honktest/u/test/bonk/1793M7B9MQ48847vdx",
- "object" => post.data["object"],
- "published" => "2019-06-25T19:33:58Z",
- "to" => "https://www.w3.org/ns/activitystreams#Public",
- "type" => "Announce"
- }
-
- {:ok, %Activity{local: false}} = Transmogrifier.handle_incoming(announce)
- end
-
- test "it works for incoming announces with actor being inlined (kroeg)" do
- data = File.read!("test/fixtures/kroeg-announce-with-inline-actor.json") |> Poison.decode!()
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == "https://puckipedia.com/"
- end
-
- test "it works for incoming notices with tag not being an array (kroeg)" do
- data = File.read!("test/fixtures/kroeg-array-less-emoji.json") |> Poison.decode!()
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
- object = Object.normalize(data["object"])
-
- assert object.data["emoji"] == %{
- "icon_e_smile" => "https://puckipedia.com/forum/images/smilies/icon_e_smile.png"
- }
-
- data = File.read!("test/fixtures/kroeg-array-less-hashtag.json") |> Poison.decode!()
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
- object = Object.normalize(data["object"])
-
- assert "test" in object.data["tag"]
- end
-
- test "it works for incoming notices with url not being a string (prismo)" do
- data = File.read!("test/fixtures/prismo-url-map.json") |> Poison.decode!()
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
- object = Object.normalize(data["object"])
-
- assert object.data["url"] == "https://prismo.news/posts/83"
- end
-
- test "it cleans up incoming notices which are not really DMs" do
- user = insert(:user)
- other_user = insert(:user)
-
- to = [user.ap_id, other_user.ap_id]
-
- data =
- File.read!("test/fixtures/mastodon-post-activity.json")
- |> Poison.decode!()
- |> Map.put("to", to)
- |> Map.put("cc", [])
-
- object =
- data["object"]
- |> Map.put("to", to)
- |> Map.put("cc", [])
-
- data = Map.put(data, "object", object)
-
- {:ok, %Activity{data: data, local: false} = activity} = Transmogrifier.handle_incoming(data)
-
- assert data["to"] == []
- assert data["cc"] == to
-
- object_data = Object.normalize(activity).data
-
- assert object_data["to"] == []
- assert object_data["cc"] == to
- end
-
- test "it works for incoming announces" do
- data = File.read!("test/fixtures/mastodon-announce.json") |> Poison.decode!()
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == "http://mastodon.example.org/users/admin"
- assert data["type"] == "Announce"
-
- assert data["id"] ==
- "http://mastodon.example.org/users/admin/statuses/99542391527669785/activity"
-
- assert data["object"] ==
- "http://mastodon.example.org/users/admin/statuses/99541947525187367"
-
- assert Activity.get_create_by_object_ap_id(data["object"])
- end
-
- test "it works for incoming announces with an existing activity" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{status: "hey"})
-
- data =
- File.read!("test/fixtures/mastodon-announce.json")
- |> Poison.decode!()
- |> Map.put("object", activity.data["object"])
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == "http://mastodon.example.org/users/admin"
- assert data["type"] == "Announce"
-
- assert data["id"] ==
- "http://mastodon.example.org/users/admin/statuses/99542391527669785/activity"
-
- assert data["object"] == activity.data["object"]
-
- assert Activity.get_create_by_object_ap_id(data["object"]).id == activity.id
- end
-
- test "it works for incoming announces with an inlined activity" do
- data =
- File.read!("test/fixtures/mastodon-announce-private.json")
- |> Poison.decode!()
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["actor"] == "http://mastodon.example.org/users/admin"
- assert data["type"] == "Announce"
-
- assert data["id"] ==
- "http://mastodon.example.org/users/admin/statuses/99542391527669785/activity"
-
- object = Object.normalize(data["object"])
-
- assert object.data["id"] == "http://mastodon.example.org/@admin/99541947525187368"
- assert object.data["content"] == "this is a private toot"
- end
-
- @tag capture_log: true
- test "it rejects incoming announces with an inlined activity from another origin" do
- data =
- File.read!("test/fixtures/bogus-mastodon-announce.json")
- |> Poison.decode!()
-
- assert :error = Transmogrifier.handle_incoming(data)
- end
-
- test "it does not clobber the addressing on announce activities" do
- user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{status: "hey"})
-
- data =
- File.read!("test/fixtures/mastodon-announce.json")
- |> Poison.decode!()
- |> Map.put("object", Object.normalize(activity).data["id"])
- |> Map.put("to", ["http://mastodon.example.org/users/admin/followers"])
- |> Map.put("cc", [])
-
- {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
-
- assert data["to"] == ["http://mastodon.example.org/users/admin/followers"]
- end
-
test "it ensures that as:Public activities make it to their followers collection" do
user = insert(:user)
--
cgit v1.2.3
From 63ab2743ce7f33b8072d5addc3e6545d12df27fd Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 18 May 2020 15:47:26 +0200
Subject: TransmogrifierTest: Fix tests.
---
test/web/activity_pub/transmogrifier_test.exs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index ae88a4480..81f966ad9 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -1329,7 +1329,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
}
assert capture_log(fn ->
- :error = Transmogrifier.handle_incoming(data)
+ {:error, _} = Transmogrifier.handle_incoming(data)
end) =~ "Object containment failed"
end
@@ -1344,7 +1344,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
}
assert capture_log(fn ->
- :error = Transmogrifier.handle_incoming(data)
+ {:error, _} = Transmogrifier.handle_incoming(data)
end) =~ "Object containment failed"
end
@@ -1359,7 +1359,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
}
assert capture_log(fn ->
- :error = Transmogrifier.handle_incoming(data)
+ {:error, _} = Transmogrifier.handle_incoming(data)
end) =~ "Object containment failed"
end
end
--
cgit v1.2.3
From 17a8342c1e2bd615edb8e41535aa96c1b22d440a Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 18 May 2020 16:45:11 +0200
Subject: ObjectValidators: Add basic Announce validator.
---
test/web/activity_pub/object_validator_test.exs | 50 +++++++++++++++++++++++++
1 file changed, 50 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 96eff1c30..9313015f1 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -280,4 +280,54 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
assert {:object, valid_like["object"]} in validated.changes
end
end
+
+ describe "announces" do
+ setup do
+ user = insert(:user)
+ announcer = insert(:user)
+ {:ok, post_activity} = CommonAPI.post(user, %{status: "uguu"})
+
+ object = Object.normalize(post_activity, false)
+ {:ok, valid_announce, []} = Builder.announce(announcer, object)
+
+ %{
+ valid_announce: valid_announce,
+ user: user,
+ post_activity: post_activity,
+ announcer: announcer
+ }
+ end
+
+ test "returns ok for a valid announce", %{valid_announce: valid_announce} do
+ assert {:ok, _object, _meta} = ObjectValidator.validate(valid_announce, [])
+ end
+
+ test "returns an error if the object can't be found", %{valid_announce: valid_announce} do
+ without_object =
+ valid_announce
+ |> Map.delete("object")
+
+ {:error, cng} = ObjectValidator.validate(without_object, [])
+
+ assert {:object, {"can't be blank", [validation: :required]}} in cng.errors
+
+ nonexisting_object =
+ valid_announce
+ |> Map.put("object", "https://gensokyo.2hu/objects/99999999")
+
+ {:error, cng} = ObjectValidator.validate(nonexisting_object, [])
+
+ assert {:object, {"can't find object", []}} in cng.errors
+ end
+
+ test "returns an error if we don't have the actor", %{valid_announce: valid_announce} do
+ nonexisting_actor =
+ valid_announce
+ |> Map.put("actor", "https://gensokyo.2hu/users/raymoo")
+
+ {:error, cng} = ObjectValidator.validate(nonexisting_actor, [])
+
+ assert {:actor, {"can't find user", []}} in cng.errors
+ end
+ end
end
--
cgit v1.2.3
From 0d5bce018df9c99c771daaaa1de3ab0efc0cba5c Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 18 May 2020 16:54:10 +0200
Subject: AnnounceValidator: Validate for existing announce
---
test/web/activity_pub/object_validator_test.exs | 13 +++++++++++++
1 file changed, 13 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 9313015f1..e24e0f913 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -329,5 +329,18 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
assert {:actor, {"can't find user", []}} in cng.errors
end
+
+ test "returns an error if the actor already announced the object", %{
+ valid_announce: valid_announce,
+ announcer: announcer,
+ post_activity: post_activity
+ } do
+ _announce = CommonAPI.repeat(post_activity.id, announcer)
+
+ {:error, cng} = ObjectValidator.validate(valid_announce, [])
+
+ assert {:actor, {"already announced this object", []}} in cng.errors
+ assert {:object, {"already announced by this actor", []}} in cng.errors
+ end
end
end
--
cgit v1.2.3
From 6e4de715b3ae2523fc90c2f5660a47fdda03bd6b Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 14 May 2020 19:21:51 +0400
Subject: Add OpenAPI spec for PleromaAPI.EmojiAPIController
---
test/web/api_spec/schema_examples_test.exs | 2 +-
.../controllers/emoji_api_controller_test.exs | 184 +++++++++++++--------
2 files changed, 120 insertions(+), 66 deletions(-)
(limited to 'test')
diff --git a/test/web/api_spec/schema_examples_test.exs b/test/web/api_spec/schema_examples_test.exs
index 88b6f07cb..f00e834fc 100644
--- a/test/web/api_spec/schema_examples_test.exs
+++ b/test/web/api_spec/schema_examples_test.exs
@@ -28,7 +28,7 @@ defmodule Pleroma.Web.ApiSpec.SchemaExamplesTest do
end
end
- for {status, response} <- operation.responses do
+ for {status, response} <- operation.responses, is_map(response.content[@content_type]) do
describe "#{operation.operationId} - #{status} Response" do
@schema resolve_schema(response.content[@content_type].schema)
diff --git a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
index d343256fe..c625a5c43 100644
--- a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
@@ -28,7 +28,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end
test "GET /api/pleroma/emoji/packs", %{conn: conn} do
- resp = conn |> get("/api/pleroma/emoji/packs") |> json_response(200)
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
shared = resp["test_pack"]
assert shared["files"] == %{"blank" => "blank.png"}
@@ -46,7 +46,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
resp =
conn
|> get("/api/pleroma/emoji/packs")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
mock(fn
%{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
@@ -60,10 +60,8 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
- |> get("/api/pleroma/emoji/packs/remote", %{
- url: "https://example.com"
- })
- |> json_response(200) == resp
+ |> get("/api/pleroma/emoji/packs/remote?url=https://example.com")
+ |> json_response_and_validate_schema(200) == resp
end
test "non shareable instance", %{admin_conn: admin_conn} do
@@ -76,8 +74,8 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
- |> get("/api/pleroma/emoji/packs/remote", %{url: "https://example.com"})
- |> json_response(500) == %{
+ |> get("/api/pleroma/emoji/packs/remote?url=https://example.com")
+ |> json_response_and_validate_schema(500) == %{
"error" => "The requested instance does not support sharing emoji packs"
}
end
@@ -99,7 +97,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "non existing pack", %{conn: conn} do
assert conn
|> get("/api/pleroma/emoji/packs/test_pack_for_import/archive")
- |> json_response(:not_found) == %{
+ |> json_response_and_validate_schema(:not_found) == %{
"error" => "Pack test_pack_for_import does not exist"
}
end
@@ -107,7 +105,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "non downloadable pack", %{conn: conn} do
assert conn
|> get("/api/pleroma/emoji/packs/test_pack_nonshared/archive")
- |> json_response(:forbidden) == %{
+ |> json_response_and_validate_schema(:forbidden) == %{
"error" =>
"Pack test_pack_nonshared cannot be downloaded from this instance, either pack sharing was disabled for this pack or some files are missing"
}
@@ -132,7 +130,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
} ->
conn
|> get("/api/pleroma/emoji/packs/test_pack")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
|> json()
%{
@@ -150,7 +148,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
} ->
conn
|> get("/api/pleroma/emoji/packs/test_pack_nonshared")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
|> json()
%{
@@ -161,23 +159,25 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/pleroma/emoji/packs/download", %{
url: "https://example.com",
name: "test_pack",
as: "test_pack2"
})
- |> json_response(200) == "ok"
+ |> json_response_and_validate_schema(200) == "ok"
assert File.exists?("#{@emoji_path}/test_pack2/pack.json")
assert File.exists?("#{@emoji_path}/test_pack2/blank.png")
assert admin_conn
|> delete("/api/pleroma/emoji/packs/test_pack2")
- |> json_response(200) == "ok"
+ |> json_response_and_validate_schema(200) == "ok"
refute File.exists?("#{@emoji_path}/test_pack2")
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post(
"/api/pleroma/emoji/packs/download",
%{
@@ -186,14 +186,14 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
as: "test_pack_nonshared2"
}
)
- |> json_response(200) == "ok"
+ |> json_response_and_validate_schema(200) == "ok"
assert File.exists?("#{@emoji_path}/test_pack_nonshared2/pack.json")
assert File.exists?("#{@emoji_path}/test_pack_nonshared2/blank.png")
assert admin_conn
|> delete("/api/pleroma/emoji/packs/test_pack_nonshared2")
- |> json_response(200) == "ok"
+ |> json_response_and_validate_schema(200) == "ok"
refute File.exists?("#{@emoji_path}/test_pack_nonshared2")
end
@@ -208,6 +208,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post(
"/api/pleroma/emoji/packs/download",
%{
@@ -216,7 +217,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
as: "test_pack2"
}
)
- |> json_response(500) == %{
+ |> json_response_and_validate_schema(500) == %{
"error" => "The requested instance does not support sharing emoji packs"
}
end
@@ -249,12 +250,13 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/pleroma/emoji/packs/download", %{
url: "https://example.com",
name: "pack_bad_sha",
as: "pack_bad_sha2"
})
- |> json_response(:internal_server_error) == %{
+ |> json_response_and_validate_schema(:internal_server_error) == %{
"error" => "SHA256 for the pack doesn't match the one sent by the server"
}
end
@@ -278,12 +280,13 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/pleroma/emoji/packs/download", %{
url: "https://example.com",
name: "test_pack",
as: "test_pack2"
})
- |> json_response(:internal_server_error) == %{
+ |> json_response_and_validate_schema(:internal_server_error) == %{
"error" =>
"The pack was not set as shared and there is no fallback src to download from"
}
@@ -311,8 +314,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "for a pack without a fallback source", ctx do
assert ctx[:admin_conn]
+ |> put_req_header("content-type", "multipart/form-data")
|> patch("/api/pleroma/emoji/packs/test_pack", %{"metadata" => ctx[:new_data]})
- |> json_response(200) == ctx[:new_data]
+ |> json_response_and_validate_schema(200) == ctx[:new_data]
assert Jason.decode!(File.read!(ctx[:pack_file]))["pack"] == ctx[:new_data]
end
@@ -336,8 +340,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
)
assert ctx[:admin_conn]
+ |> put_req_header("content-type", "multipart/form-data")
|> patch("/api/pleroma/emoji/packs/test_pack", %{metadata: new_data})
- |> json_response(200) == new_data_with_sha
+ |> json_response_and_validate_schema(200) == new_data_with_sha
assert Jason.decode!(File.read!(ctx[:pack_file]))["pack"] == new_data_with_sha
end
@@ -355,8 +360,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
new_data = Map.put(ctx[:new_data], "fallback-src", "https://nonshared-pack")
assert ctx[:admin_conn]
+ |> put_req_header("content-type", "multipart/form-data")
|> patch("/api/pleroma/emoji/packs/test_pack", %{metadata: new_data})
- |> json_response(:bad_request) == %{
+ |> json_response_and_validate_schema(:bad_request) == %{
"error" => "The fallback archive does not have all files specified in pack.json"
}
end
@@ -376,6 +382,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "create shortcode exists", %{admin_conn: admin_conn} do
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/pleroma/emoji/packs/test_pack/files", %{
shortcode: "blank",
filename: "dir/blank.png",
@@ -384,7 +391,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
path: "#{@emoji_path}/test_pack/blank.png"
}
})
- |> json_response(:conflict) == %{
+ |> json_response_and_validate_schema(:conflict) == %{
"error" => "An emoji with the \"blank\" shortcode already exists"
}
end
@@ -393,6 +400,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir/") end)
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/pleroma/emoji/packs/test_pack/files", %{
shortcode: "blank2",
filename: "dir/blank.png",
@@ -401,17 +409,21 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
path: "#{@emoji_path}/test_pack/blank.png"
}
})
- |> json_response(200) == %{"blank" => "blank.png", "blank2" => "dir/blank.png"}
+ |> json_response_and_validate_schema(200) == %{
+ "blank" => "blank.png",
+ "blank2" => "dir/blank.png"
+ }
assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> patch("/api/pleroma/emoji/packs/test_pack/files", %{
shortcode: "blank",
new_shortcode: "blank2",
new_filename: "dir_2/blank_3.png"
})
- |> json_response(:conflict) == %{
+ |> json_response_and_validate_schema(:conflict) == %{
"error" =>
"New shortcode \"blank2\" is already used. If you want to override emoji use 'force' option"
}
@@ -421,6 +433,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir_2/") end)
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/pleroma/emoji/packs/test_pack/files", %{
shortcode: "blank2",
filename: "dir/blank.png",
@@ -429,18 +442,22 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
path: "#{@emoji_path}/test_pack/blank.png"
}
})
- |> json_response(200) == %{"blank" => "blank.png", "blank2" => "dir/blank.png"}
+ |> json_response_and_validate_schema(200) == %{
+ "blank" => "blank.png",
+ "blank2" => "dir/blank.png"
+ }
assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> patch("/api/pleroma/emoji/packs/test_pack/files", %{
shortcode: "blank2",
new_shortcode: "blank3",
new_filename: "dir_2/blank_3.png",
force: true
})
- |> json_response(200) == %{
+ |> json_response_and_validate_schema(200) == %{
"blank" => "blank.png",
"blank3" => "dir_2/blank_3.png"
}
@@ -450,6 +467,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "with empty filename", %{admin_conn: admin_conn} do
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/pleroma/emoji/packs/test_pack/files", %{
shortcode: "blank2",
filename: "",
@@ -458,13 +476,14 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
path: "#{@emoji_path}/test_pack/blank.png"
}
})
- |> json_response(:bad_request) == %{
+ |> json_response_and_validate_schema(:bad_request) == %{
"error" => "pack name, shortcode or filename cannot be empty"
}
end
test "add file with not loaded pack", %{admin_conn: admin_conn} do
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/pleroma/emoji/packs/not_loaded/files", %{
shortcode: "blank2",
filename: "dir/blank.png",
@@ -473,37 +492,43 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
path: "#{@emoji_path}/test_pack/blank.png"
}
})
- |> json_response(:bad_request) == %{
+ |> json_response_and_validate_schema(:bad_request) == %{
"error" => "pack \"not_loaded\" is not found"
}
end
test "remove file with not loaded pack", %{admin_conn: admin_conn} do
assert admin_conn
- |> delete("/api/pleroma/emoji/packs/not_loaded/files", %{shortcode: "blank3"})
- |> json_response(:bad_request) == %{"error" => "pack \"not_loaded\" is not found"}
+ |> delete("/api/pleroma/emoji/packs/not_loaded/files?shortcode=blank3")
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack \"not_loaded\" is not found"
+ }
end
test "remove file with empty shortcode", %{admin_conn: admin_conn} do
assert admin_conn
- |> delete("/api/pleroma/emoji/packs/not_loaded/files", %{shortcode: ""})
- |> json_response(:bad_request) == %{
+ |> delete("/api/pleroma/emoji/packs/not_loaded/files?shortcode=")
+ |> json_response_and_validate_schema(:bad_request) == %{
"error" => "pack name or shortcode cannot be empty"
}
end
test "update file with not loaded pack", %{admin_conn: admin_conn} do
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> patch("/api/pleroma/emoji/packs/not_loaded/files", %{
shortcode: "blank4",
new_shortcode: "blank3",
new_filename: "dir_2/blank_3.png"
})
- |> json_response(:bad_request) == %{"error" => "pack \"not_loaded\" is not found"}
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack \"not_loaded\" is not found"
+ }
end
test "new with shortcode as file with update", %{admin_conn: admin_conn} do
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/pleroma/emoji/packs/test_pack/files", %{
shortcode: "blank4",
filename: "dir/blank.png",
@@ -512,24 +537,31 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
path: "#{@emoji_path}/test_pack/blank.png"
}
})
- |> json_response(200) == %{"blank" => "blank.png", "blank4" => "dir/blank.png"}
+ |> json_response_and_validate_schema(200) == %{
+ "blank" => "blank.png",
+ "blank4" => "dir/blank.png"
+ }
assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> patch("/api/pleroma/emoji/packs/test_pack/files", %{
shortcode: "blank4",
new_shortcode: "blank3",
new_filename: "dir_2/blank_3.png"
})
- |> json_response(200) == %{"blank3" => "dir_2/blank_3.png", "blank" => "blank.png"}
+ |> json_response_and_validate_schema(200) == %{
+ "blank3" => "dir_2/blank_3.png",
+ "blank" => "blank.png"
+ }
refute File.exists?("#{@emoji_path}/test_pack/dir/")
assert File.exists?("#{@emoji_path}/test_pack/dir_2/blank_3.png")
assert admin_conn
- |> delete("/api/pleroma/emoji/packs/test_pack/files", %{shortcode: "blank3"})
- |> json_response(200) == %{"blank" => "blank.png"}
+ |> delete("/api/pleroma/emoji/packs/test_pack/files?shortcode=blank3")
+ |> json_response_and_validate_schema(200) == %{"blank" => "blank.png"}
refute File.exists?("#{@emoji_path}/test_pack/dir_2/")
@@ -546,11 +578,12 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
end)
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/pleroma/emoji/packs/test_pack/files", %{
shortcode: "blank_url",
file: "https://test-blank/blank_url.png"
})
- |> json_response(200) == %{
+ |> json_response_and_validate_schema(200) == %{
"blank_url" => "blank_url.png",
"blank" => "blank.png"
}
@@ -564,40 +597,51 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/shortcode.png") end)
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> post("/api/pleroma/emoji/packs/test_pack/files", %{
file: %Plug.Upload{
filename: "shortcode.png",
path: "#{Pleroma.Config.get([:instance, :static_dir])}/add/shortcode.png"
}
})
- |> json_response(200) == %{"shortcode" => "shortcode.png", "blank" => "blank.png"}
+ |> json_response_and_validate_schema(200) == %{
+ "shortcode" => "shortcode.png",
+ "blank" => "blank.png"
+ }
end
test "remove non existing shortcode in pack.json", %{admin_conn: admin_conn} do
assert admin_conn
- |> delete("/api/pleroma/emoji/packs/test_pack/files", %{shortcode: "blank2"})
- |> json_response(:bad_request) == %{"error" => "Emoji \"blank2\" does not exist"}
+ |> delete("/api/pleroma/emoji/packs/test_pack/files?shortcode=blank2")
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "Emoji \"blank2\" does not exist"
+ }
end
test "update non existing emoji", %{admin_conn: admin_conn} do
assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
|> patch("/api/pleroma/emoji/packs/test_pack/files", %{
shortcode: "blank2",
new_shortcode: "blank3",
new_filename: "dir_2/blank_3.png"
})
- |> json_response(:bad_request) == %{"error" => "Emoji \"blank2\" does not exist"}
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "Emoji \"blank2\" does not exist"
+ }
end
test "update with empty shortcode", %{admin_conn: admin_conn} do
- assert admin_conn
- |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank",
- new_filename: "dir_2/blank_3.png"
- })
- |> json_response(:bad_request) == %{
- "error" => "new_shortcode or new_filename cannot be empty"
- }
+ assert %{
+ "error" => "Missing field: new_shortcode."
+ } =
+ admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank",
+ new_filename: "dir_2/blank_3.png"
+ })
+ |> json_response_and_validate_schema(:bad_request)
end
end
@@ -605,7 +649,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "creating and deleting a pack", %{admin_conn: admin_conn} do
assert admin_conn
|> post("/api/pleroma/emoji/packs/test_created")
- |> json_response(200) == "ok"
+ |> json_response_and_validate_schema(200) == "ok"
assert File.exists?("#{@emoji_path}/test_created/pack.json")
@@ -616,7 +660,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
assert admin_conn
|> delete("/api/pleroma/emoji/packs/test_created")
- |> json_response(200) == "ok"
+ |> json_response_and_validate_schema(200) == "ok"
refute File.exists?("#{@emoji_path}/test_created/pack.json")
end
@@ -629,7 +673,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
assert admin_conn
|> post("/api/pleroma/emoji/packs/test_created")
- |> json_response(:conflict) == %{
+ |> json_response_and_validate_schema(:conflict) == %{
"error" => "A pack named \"test_created\" already exists"
}
@@ -639,20 +683,26 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
test "with empty name", %{admin_conn: admin_conn} do
assert admin_conn
|> post("/api/pleroma/emoji/packs/ ")
- |> json_response(:bad_request) == %{"error" => "pack name cannot be empty"}
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack name cannot be empty"
+ }
end
end
test "deleting nonexisting pack", %{admin_conn: admin_conn} do
assert admin_conn
|> delete("/api/pleroma/emoji/packs/non_existing")
- |> json_response(:not_found) == %{"error" => "Pack non_existing does not exist"}
+ |> json_response_and_validate_schema(:not_found) == %{
+ "error" => "Pack non_existing does not exist"
+ }
end
test "deleting with empty name", %{admin_conn: admin_conn} do
assert admin_conn
|> delete("/api/pleroma/emoji/packs/ ")
- |> json_response(:bad_request) == %{"error" => "pack name cannot be empty"}
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack name cannot be empty"
+ }
end
test "filesystem import", %{admin_conn: admin_conn, conn: conn} do
@@ -661,15 +711,15 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
File.rm!("#{@emoji_path}/test_pack_for_import/pack.json")
end)
- resp = conn |> get("/api/pleroma/emoji/packs") |> json_response(200)
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
refute Map.has_key?(resp, "test_pack_for_import")
assert admin_conn
|> get("/api/pleroma/emoji/packs/import")
- |> json_response(200) == ["test_pack_for_import"]
+ |> json_response_and_validate_schema(200) == ["test_pack_for_import"]
- resp = conn |> get("/api/pleroma/emoji/packs") |> json_response(200)
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
assert resp["test_pack_for_import"]["files"] == %{"blank" => "blank.png"}
File.rm!("#{@emoji_path}/test_pack_for_import/pack.json")
@@ -686,9 +736,9 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
assert admin_conn
|> get("/api/pleroma/emoji/packs/import")
- |> json_response(200) == ["test_pack_for_import"]
+ |> json_response_and_validate_schema(200) == ["test_pack_for_import"]
- resp = conn |> get("/api/pleroma/emoji/packs") |> json_response(200)
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
assert resp["test_pack_for_import"]["files"] == %{
"blank" => "blank.png",
@@ -712,19 +762,23 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
} =
conn
|> get("/api/pleroma/emoji/packs/test_pack")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
end
test "non existing pack", %{conn: conn} do
assert conn
|> get("/api/pleroma/emoji/packs/non_existing")
- |> json_response(:not_found) == %{"error" => "Pack non_existing does not exist"}
+ |> json_response_and_validate_schema(:not_found) == %{
+ "error" => "Pack non_existing does not exist"
+ }
end
test "error name", %{conn: conn} do
assert conn
|> get("/api/pleroma/emoji/packs/ ")
- |> json_response(:bad_request) == %{"error" => "pack name cannot be empty"}
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack name cannot be empty"
+ }
end
end
end
--
cgit v1.2.3
From 8bde8dfec21dbc83bc73ea6f7ea43a432eea116b Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 18 May 2020 19:43:23 +0400
Subject: Cleanup Pleroma.Emoji.Pack
---
.../pleroma_api/controllers/emoji_api_controller_test.exs | 12 ++++--------
1 file changed, 4 insertions(+), 8 deletions(-)
(limited to 'test')
diff --git a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
index c625a5c43..6871111d7 100644
--- a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
@@ -234,10 +234,8 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
method: :get,
url: "https://example.com/api/pleroma/emoji/packs/pack_bad_sha"
} ->
- %Tesla.Env{
- status: 200,
- body: Pleroma.Emoji.Pack.load_pack("pack_bad_sha") |> Jason.encode!()
- }
+ {:ok, pack} = Pleroma.Emoji.Pack.load_pack("pack_bad_sha")
+ %Tesla.Env{status: 200, body: Jason.encode!(pack)}
%{
method: :get,
@@ -273,10 +271,8 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
method: :get,
url: "https://example.com/api/pleroma/emoji/packs/test_pack"
} ->
- %Tesla.Env{
- status: 200,
- body: Pleroma.Emoji.Pack.load_pack("test_pack") |> Jason.encode!()
- }
+ {:ok, pack} = Pleroma.Emoji.Pack.load_pack("test_pack")
+ %Tesla.Env{status: 200, body: Jason.encode!(pack)}
end)
assert admin_conn
--
cgit v1.2.3
From aef31c69df0424491a3c0bf45fbf46e2da132580 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 18 May 2020 19:38:22 +0400
Subject: Rename EmojiAPIController to EmojiPackController
---
.../controllers/emoji_api_controller_test.exs | 780 ---------------------
.../controllers/emoji_pack_controller_test.exs | 780 +++++++++++++++++++++
2 files changed, 780 insertions(+), 780 deletions(-)
delete mode 100644 test/web/pleroma_api/controllers/emoji_api_controller_test.exs
create mode 100644 test/web/pleroma_api/controllers/emoji_pack_controller_test.exs
(limited to 'test')
diff --git a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
deleted file mode 100644
index 6871111d7..000000000
--- a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs
+++ /dev/null
@@ -1,780 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do
- use Pleroma.Web.ConnCase
-
- import Tesla.Mock
- import Pleroma.Factory
-
- @emoji_path Path.join(
- Pleroma.Config.get!([:instance, :static_dir]),
- "emoji"
- )
- setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false)
-
- setup do
- admin = insert(:user, is_admin: true)
- token = insert(:oauth_admin_token, user: admin)
-
- admin_conn =
- build_conn()
- |> assign(:user, admin)
- |> assign(:token, token)
-
- Pleroma.Emoji.reload()
- {:ok, %{admin_conn: admin_conn}}
- end
-
- test "GET /api/pleroma/emoji/packs", %{conn: conn} do
- resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
-
- shared = resp["test_pack"]
- assert shared["files"] == %{"blank" => "blank.png"}
- assert Map.has_key?(shared["pack"], "download-sha256")
- assert shared["pack"]["can-download"]
- assert shared["pack"]["share-files"]
-
- non_shared = resp["test_pack_nonshared"]
- assert non_shared["pack"]["share-files"] == false
- assert non_shared["pack"]["can-download"] == false
- end
-
- describe "GET /api/pleroma/emoji/packs/remote" do
- test "shareable instance", %{admin_conn: admin_conn, conn: conn} do
- resp =
- conn
- |> get("/api/pleroma/emoji/packs")
- |> json_response_and_validate_schema(200)
-
- mock(fn
- %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
- json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
-
- %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
- json(%{metadata: %{features: ["shareable_emoji_packs"]}})
-
- %{method: :get, url: "https://example.com/api/pleroma/emoji/packs"} ->
- json(resp)
- end)
-
- assert admin_conn
- |> get("/api/pleroma/emoji/packs/remote?url=https://example.com")
- |> json_response_and_validate_schema(200) == resp
- end
-
- test "non shareable instance", %{admin_conn: admin_conn} do
- mock(fn
- %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
- json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
-
- %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
- json(%{metadata: %{features: []}})
- end)
-
- assert admin_conn
- |> get("/api/pleroma/emoji/packs/remote?url=https://example.com")
- |> json_response_and_validate_schema(500) == %{
- "error" => "The requested instance does not support sharing emoji packs"
- }
- end
- end
-
- describe "GET /api/pleroma/emoji/packs/:name/archive" do
- test "download shared pack", %{conn: conn} do
- resp =
- conn
- |> get("/api/pleroma/emoji/packs/test_pack/archive")
- |> response(200)
-
- {:ok, arch} = :zip.unzip(resp, [:memory])
-
- assert Enum.find(arch, fn {n, _} -> n == 'pack.json' end)
- assert Enum.find(arch, fn {n, _} -> n == 'blank.png' end)
- end
-
- test "non existing pack", %{conn: conn} do
- assert conn
- |> get("/api/pleroma/emoji/packs/test_pack_for_import/archive")
- |> json_response_and_validate_schema(:not_found) == %{
- "error" => "Pack test_pack_for_import does not exist"
- }
- end
-
- test "non downloadable pack", %{conn: conn} do
- assert conn
- |> get("/api/pleroma/emoji/packs/test_pack_nonshared/archive")
- |> json_response_and_validate_schema(:forbidden) == %{
- "error" =>
- "Pack test_pack_nonshared cannot be downloaded from this instance, either pack sharing was disabled for this pack or some files are missing"
- }
- end
- end
-
- describe "POST /api/pleroma/emoji/packs/download" do
- test "shared pack from remote and non shared from fallback-src", %{
- admin_conn: admin_conn,
- conn: conn
- } do
- mock(fn
- %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
- json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
-
- %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
- json(%{metadata: %{features: ["shareable_emoji_packs"]}})
-
- %{
- method: :get,
- url: "https://example.com/api/pleroma/emoji/packs/test_pack"
- } ->
- conn
- |> get("/api/pleroma/emoji/packs/test_pack")
- |> json_response_and_validate_schema(200)
- |> json()
-
- %{
- method: :get,
- url: "https://example.com/api/pleroma/emoji/packs/test_pack/archive"
- } ->
- conn
- |> get("/api/pleroma/emoji/packs/test_pack/archive")
- |> response(200)
- |> text()
-
- %{
- method: :get,
- url: "https://example.com/api/pleroma/emoji/packs/test_pack_nonshared"
- } ->
- conn
- |> get("/api/pleroma/emoji/packs/test_pack_nonshared")
- |> json_response_and_validate_schema(200)
- |> json()
-
- %{
- method: :get,
- url: "https://nonshared-pack"
- } ->
- text(File.read!("#{@emoji_path}/test_pack_nonshared/nonshared.zip"))
- end)
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/pleroma/emoji/packs/download", %{
- url: "https://example.com",
- name: "test_pack",
- as: "test_pack2"
- })
- |> json_response_and_validate_schema(200) == "ok"
-
- assert File.exists?("#{@emoji_path}/test_pack2/pack.json")
- assert File.exists?("#{@emoji_path}/test_pack2/blank.png")
-
- assert admin_conn
- |> delete("/api/pleroma/emoji/packs/test_pack2")
- |> json_response_and_validate_schema(200) == "ok"
-
- refute File.exists?("#{@emoji_path}/test_pack2")
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post(
- "/api/pleroma/emoji/packs/download",
- %{
- url: "https://example.com",
- name: "test_pack_nonshared",
- as: "test_pack_nonshared2"
- }
- )
- |> json_response_and_validate_schema(200) == "ok"
-
- assert File.exists?("#{@emoji_path}/test_pack_nonshared2/pack.json")
- assert File.exists?("#{@emoji_path}/test_pack_nonshared2/blank.png")
-
- assert admin_conn
- |> delete("/api/pleroma/emoji/packs/test_pack_nonshared2")
- |> json_response_and_validate_schema(200) == "ok"
-
- refute File.exists?("#{@emoji_path}/test_pack_nonshared2")
- end
-
- test "nonshareable instance", %{admin_conn: admin_conn} do
- mock(fn
- %{method: :get, url: "https://old-instance/.well-known/nodeinfo"} ->
- json(%{links: [%{href: "https://old-instance/nodeinfo/2.1.json"}]})
-
- %{method: :get, url: "https://old-instance/nodeinfo/2.1.json"} ->
- json(%{metadata: %{features: []}})
- end)
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post(
- "/api/pleroma/emoji/packs/download",
- %{
- url: "https://old-instance",
- name: "test_pack",
- as: "test_pack2"
- }
- )
- |> json_response_and_validate_schema(500) == %{
- "error" => "The requested instance does not support sharing emoji packs"
- }
- end
-
- test "checksum fail", %{admin_conn: admin_conn} do
- mock(fn
- %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
- json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
-
- %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
- json(%{metadata: %{features: ["shareable_emoji_packs"]}})
-
- %{
- method: :get,
- url: "https://example.com/api/pleroma/emoji/packs/pack_bad_sha"
- } ->
- {:ok, pack} = Pleroma.Emoji.Pack.load_pack("pack_bad_sha")
- %Tesla.Env{status: 200, body: Jason.encode!(pack)}
-
- %{
- method: :get,
- url: "https://example.com/api/pleroma/emoji/packs/pack_bad_sha/archive"
- } ->
- %Tesla.Env{
- status: 200,
- body: File.read!("test/instance_static/emoji/pack_bad_sha/pack_bad_sha.zip")
- }
- end)
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/pleroma/emoji/packs/download", %{
- url: "https://example.com",
- name: "pack_bad_sha",
- as: "pack_bad_sha2"
- })
- |> json_response_and_validate_schema(:internal_server_error) == %{
- "error" => "SHA256 for the pack doesn't match the one sent by the server"
- }
- end
-
- test "other error", %{admin_conn: admin_conn} do
- mock(fn
- %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
- json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
-
- %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
- json(%{metadata: %{features: ["shareable_emoji_packs"]}})
-
- %{
- method: :get,
- url: "https://example.com/api/pleroma/emoji/packs/test_pack"
- } ->
- {:ok, pack} = Pleroma.Emoji.Pack.load_pack("test_pack")
- %Tesla.Env{status: 200, body: Jason.encode!(pack)}
- end)
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/pleroma/emoji/packs/download", %{
- url: "https://example.com",
- name: "test_pack",
- as: "test_pack2"
- })
- |> json_response_and_validate_schema(:internal_server_error) == %{
- "error" =>
- "The pack was not set as shared and there is no fallback src to download from"
- }
- end
- end
-
- describe "PATCH /api/pleroma/emoji/packs/:name" do
- setup do
- pack_file = "#{@emoji_path}/test_pack/pack.json"
- original_content = File.read!(pack_file)
-
- on_exit(fn ->
- File.write!(pack_file, original_content)
- end)
-
- {:ok,
- pack_file: pack_file,
- new_data: %{
- "license" => "Test license changed",
- "homepage" => "https://pleroma.social",
- "description" => "Test description",
- "share-files" => false
- }}
- end
-
- test "for a pack without a fallback source", ctx do
- assert ctx[:admin_conn]
- |> put_req_header("content-type", "multipart/form-data")
- |> patch("/api/pleroma/emoji/packs/test_pack", %{"metadata" => ctx[:new_data]})
- |> json_response_and_validate_schema(200) == ctx[:new_data]
-
- assert Jason.decode!(File.read!(ctx[:pack_file]))["pack"] == ctx[:new_data]
- end
-
- test "for a pack with a fallback source", ctx do
- mock(fn
- %{
- method: :get,
- url: "https://nonshared-pack"
- } ->
- text(File.read!("#{@emoji_path}/test_pack_nonshared/nonshared.zip"))
- end)
-
- new_data = Map.put(ctx[:new_data], "fallback-src", "https://nonshared-pack")
-
- new_data_with_sha =
- Map.put(
- new_data,
- "fallback-src-sha256",
- "74409E2674DAA06C072729C6C8426C4CB3B7E0B85ED77792DB7A436E11D76DAF"
- )
-
- assert ctx[:admin_conn]
- |> put_req_header("content-type", "multipart/form-data")
- |> patch("/api/pleroma/emoji/packs/test_pack", %{metadata: new_data})
- |> json_response_and_validate_schema(200) == new_data_with_sha
-
- assert Jason.decode!(File.read!(ctx[:pack_file]))["pack"] == new_data_with_sha
- end
-
- test "when the fallback source doesn't have all the files", ctx do
- mock(fn
- %{
- method: :get,
- url: "https://nonshared-pack"
- } ->
- {:ok, {'empty.zip', empty_arch}} = :zip.zip('empty.zip', [], [:memory])
- text(empty_arch)
- end)
-
- new_data = Map.put(ctx[:new_data], "fallback-src", "https://nonshared-pack")
-
- assert ctx[:admin_conn]
- |> put_req_header("content-type", "multipart/form-data")
- |> patch("/api/pleroma/emoji/packs/test_pack", %{metadata: new_data})
- |> json_response_and_validate_schema(:bad_request) == %{
- "error" => "The fallback archive does not have all files specified in pack.json"
- }
- end
- end
-
- describe "POST/PATCH/DELETE /api/pleroma/emoji/packs/:name/files" do
- setup do
- pack_file = "#{@emoji_path}/test_pack/pack.json"
- original_content = File.read!(pack_file)
-
- on_exit(fn ->
- File.write!(pack_file, original_content)
- end)
-
- :ok
- end
-
- test "create shortcode exists", %{admin_conn: admin_conn} do
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank",
- filename: "dir/blank.png",
- file: %Plug.Upload{
- filename: "blank.png",
- path: "#{@emoji_path}/test_pack/blank.png"
- }
- })
- |> json_response_and_validate_schema(:conflict) == %{
- "error" => "An emoji with the \"blank\" shortcode already exists"
- }
- end
-
- test "don't rewrite old emoji", %{admin_conn: admin_conn} do
- on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir/") end)
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank2",
- filename: "dir/blank.png",
- file: %Plug.Upload{
- filename: "blank.png",
- path: "#{@emoji_path}/test_pack/blank.png"
- }
- })
- |> json_response_and_validate_schema(200) == %{
- "blank" => "blank.png",
- "blank2" => "dir/blank.png"
- }
-
- assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank",
- new_shortcode: "blank2",
- new_filename: "dir_2/blank_3.png"
- })
- |> json_response_and_validate_schema(:conflict) == %{
- "error" =>
- "New shortcode \"blank2\" is already used. If you want to override emoji use 'force' option"
- }
- end
-
- test "rewrite old emoji with force option", %{admin_conn: admin_conn} do
- on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir_2/") end)
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank2",
- filename: "dir/blank.png",
- file: %Plug.Upload{
- filename: "blank.png",
- path: "#{@emoji_path}/test_pack/blank.png"
- }
- })
- |> json_response_and_validate_schema(200) == %{
- "blank" => "blank.png",
- "blank2" => "dir/blank.png"
- }
-
- assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank2",
- new_shortcode: "blank3",
- new_filename: "dir_2/blank_3.png",
- force: true
- })
- |> json_response_and_validate_schema(200) == %{
- "blank" => "blank.png",
- "blank3" => "dir_2/blank_3.png"
- }
-
- assert File.exists?("#{@emoji_path}/test_pack/dir_2/blank_3.png")
- end
-
- test "with empty filename", %{admin_conn: admin_conn} do
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank2",
- filename: "",
- file: %Plug.Upload{
- filename: "blank.png",
- path: "#{@emoji_path}/test_pack/blank.png"
- }
- })
- |> json_response_and_validate_schema(:bad_request) == %{
- "error" => "pack name, shortcode or filename cannot be empty"
- }
- end
-
- test "add file with not loaded pack", %{admin_conn: admin_conn} do
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/pleroma/emoji/packs/not_loaded/files", %{
- shortcode: "blank2",
- filename: "dir/blank.png",
- file: %Plug.Upload{
- filename: "blank.png",
- path: "#{@emoji_path}/test_pack/blank.png"
- }
- })
- |> json_response_and_validate_schema(:bad_request) == %{
- "error" => "pack \"not_loaded\" is not found"
- }
- end
-
- test "remove file with not loaded pack", %{admin_conn: admin_conn} do
- assert admin_conn
- |> delete("/api/pleroma/emoji/packs/not_loaded/files?shortcode=blank3")
- |> json_response_and_validate_schema(:bad_request) == %{
- "error" => "pack \"not_loaded\" is not found"
- }
- end
-
- test "remove file with empty shortcode", %{admin_conn: admin_conn} do
- assert admin_conn
- |> delete("/api/pleroma/emoji/packs/not_loaded/files?shortcode=")
- |> json_response_and_validate_schema(:bad_request) == %{
- "error" => "pack name or shortcode cannot be empty"
- }
- end
-
- test "update file with not loaded pack", %{admin_conn: admin_conn} do
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> patch("/api/pleroma/emoji/packs/not_loaded/files", %{
- shortcode: "blank4",
- new_shortcode: "blank3",
- new_filename: "dir_2/blank_3.png"
- })
- |> json_response_and_validate_schema(:bad_request) == %{
- "error" => "pack \"not_loaded\" is not found"
- }
- end
-
- test "new with shortcode as file with update", %{admin_conn: admin_conn} do
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank4",
- filename: "dir/blank.png",
- file: %Plug.Upload{
- filename: "blank.png",
- path: "#{@emoji_path}/test_pack/blank.png"
- }
- })
- |> json_response_and_validate_schema(200) == %{
- "blank" => "blank.png",
- "blank4" => "dir/blank.png"
- }
-
- assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank4",
- new_shortcode: "blank3",
- new_filename: "dir_2/blank_3.png"
- })
- |> json_response_and_validate_schema(200) == %{
- "blank3" => "dir_2/blank_3.png",
- "blank" => "blank.png"
- }
-
- refute File.exists?("#{@emoji_path}/test_pack/dir/")
- assert File.exists?("#{@emoji_path}/test_pack/dir_2/blank_3.png")
-
- assert admin_conn
- |> delete("/api/pleroma/emoji/packs/test_pack/files?shortcode=blank3")
- |> json_response_and_validate_schema(200) == %{"blank" => "blank.png"}
-
- refute File.exists?("#{@emoji_path}/test_pack/dir_2/")
-
- on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir") end)
- end
-
- test "new with shortcode from url", %{admin_conn: admin_conn} do
- mock(fn
- %{
- method: :get,
- url: "https://test-blank/blank_url.png"
- } ->
- text(File.read!("#{@emoji_path}/test_pack/blank.png"))
- end)
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank_url",
- file: "https://test-blank/blank_url.png"
- })
- |> json_response_and_validate_schema(200) == %{
- "blank_url" => "blank_url.png",
- "blank" => "blank.png"
- }
-
- assert File.exists?("#{@emoji_path}/test_pack/blank_url.png")
-
- on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/blank_url.png") end)
- end
-
- test "new without shortcode", %{admin_conn: admin_conn} do
- on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/shortcode.png") end)
-
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> post("/api/pleroma/emoji/packs/test_pack/files", %{
- file: %Plug.Upload{
- filename: "shortcode.png",
- path: "#{Pleroma.Config.get([:instance, :static_dir])}/add/shortcode.png"
- }
- })
- |> json_response_and_validate_schema(200) == %{
- "shortcode" => "shortcode.png",
- "blank" => "blank.png"
- }
- end
-
- test "remove non existing shortcode in pack.json", %{admin_conn: admin_conn} do
- assert admin_conn
- |> delete("/api/pleroma/emoji/packs/test_pack/files?shortcode=blank2")
- |> json_response_and_validate_schema(:bad_request) == %{
- "error" => "Emoji \"blank2\" does not exist"
- }
- end
-
- test "update non existing emoji", %{admin_conn: admin_conn} do
- assert admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank2",
- new_shortcode: "blank3",
- new_filename: "dir_2/blank_3.png"
- })
- |> json_response_and_validate_schema(:bad_request) == %{
- "error" => "Emoji \"blank2\" does not exist"
- }
- end
-
- test "update with empty shortcode", %{admin_conn: admin_conn} do
- assert %{
- "error" => "Missing field: new_shortcode."
- } =
- admin_conn
- |> put_req_header("content-type", "multipart/form-data")
- |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
- shortcode: "blank",
- new_filename: "dir_2/blank_3.png"
- })
- |> json_response_and_validate_schema(:bad_request)
- end
- end
-
- describe "POST/DELETE /api/pleroma/emoji/packs/:name" do
- test "creating and deleting a pack", %{admin_conn: admin_conn} do
- assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_created")
- |> json_response_and_validate_schema(200) == "ok"
-
- assert File.exists?("#{@emoji_path}/test_created/pack.json")
-
- assert Jason.decode!(File.read!("#{@emoji_path}/test_created/pack.json")) == %{
- "pack" => %{},
- "files" => %{}
- }
-
- assert admin_conn
- |> delete("/api/pleroma/emoji/packs/test_created")
- |> json_response_and_validate_schema(200) == "ok"
-
- refute File.exists?("#{@emoji_path}/test_created/pack.json")
- end
-
- test "if pack exists", %{admin_conn: admin_conn} do
- path = Path.join(@emoji_path, "test_created")
- File.mkdir(path)
- pack_file = Jason.encode!(%{files: %{}, pack: %{}})
- File.write!(Path.join(path, "pack.json"), pack_file)
-
- assert admin_conn
- |> post("/api/pleroma/emoji/packs/test_created")
- |> json_response_and_validate_schema(:conflict) == %{
- "error" => "A pack named \"test_created\" already exists"
- }
-
- on_exit(fn -> File.rm_rf(path) end)
- end
-
- test "with empty name", %{admin_conn: admin_conn} do
- assert admin_conn
- |> post("/api/pleroma/emoji/packs/ ")
- |> json_response_and_validate_schema(:bad_request) == %{
- "error" => "pack name cannot be empty"
- }
- end
- end
-
- test "deleting nonexisting pack", %{admin_conn: admin_conn} do
- assert admin_conn
- |> delete("/api/pleroma/emoji/packs/non_existing")
- |> json_response_and_validate_schema(:not_found) == %{
- "error" => "Pack non_existing does not exist"
- }
- end
-
- test "deleting with empty name", %{admin_conn: admin_conn} do
- assert admin_conn
- |> delete("/api/pleroma/emoji/packs/ ")
- |> json_response_and_validate_schema(:bad_request) == %{
- "error" => "pack name cannot be empty"
- }
- end
-
- test "filesystem import", %{admin_conn: admin_conn, conn: conn} do
- on_exit(fn ->
- File.rm!("#{@emoji_path}/test_pack_for_import/emoji.txt")
- File.rm!("#{@emoji_path}/test_pack_for_import/pack.json")
- end)
-
- resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
-
- refute Map.has_key?(resp, "test_pack_for_import")
-
- assert admin_conn
- |> get("/api/pleroma/emoji/packs/import")
- |> json_response_and_validate_schema(200) == ["test_pack_for_import"]
-
- resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
- assert resp["test_pack_for_import"]["files"] == %{"blank" => "blank.png"}
-
- File.rm!("#{@emoji_path}/test_pack_for_import/pack.json")
- refute File.exists?("#{@emoji_path}/test_pack_for_import/pack.json")
-
- emoji_txt_content = """
- blank, blank.png, Fun
- blank2, blank.png
- foo, /emoji/test_pack_for_import/blank.png
- bar
- """
-
- File.write!("#{@emoji_path}/test_pack_for_import/emoji.txt", emoji_txt_content)
-
- assert admin_conn
- |> get("/api/pleroma/emoji/packs/import")
- |> json_response_and_validate_schema(200) == ["test_pack_for_import"]
-
- resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
-
- assert resp["test_pack_for_import"]["files"] == %{
- "blank" => "blank.png",
- "blank2" => "blank.png",
- "foo" => "blank.png"
- }
- end
-
- describe "GET /api/pleroma/emoji/packs/:name" do
- test "shows pack.json", %{conn: conn} do
- assert %{
- "files" => %{"blank" => "blank.png"},
- "pack" => %{
- "can-download" => true,
- "description" => "Test description",
- "download-sha256" => _,
- "homepage" => "https://pleroma.social",
- "license" => "Test license",
- "share-files" => true
- }
- } =
- conn
- |> get("/api/pleroma/emoji/packs/test_pack")
- |> json_response_and_validate_schema(200)
- end
-
- test "non existing pack", %{conn: conn} do
- assert conn
- |> get("/api/pleroma/emoji/packs/non_existing")
- |> json_response_and_validate_schema(:not_found) == %{
- "error" => "Pack non_existing does not exist"
- }
- end
-
- test "error name", %{conn: conn} do
- assert conn
- |> get("/api/pleroma/emoji/packs/ ")
- |> json_response_and_validate_schema(:bad_request) == %{
- "error" => "pack name cannot be empty"
- }
- end
- end
-end
diff --git a/test/web/pleroma_api/controllers/emoji_pack_controller_test.exs b/test/web/pleroma_api/controllers/emoji_pack_controller_test.exs
new file mode 100644
index 000000000..ee3d281a0
--- /dev/null
+++ b/test/web/pleroma_api/controllers/emoji_pack_controller_test.exs
@@ -0,0 +1,780 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.PleromaAPI.EmojiPackControllerTest do
+ use Pleroma.Web.ConnCase
+
+ import Tesla.Mock
+ import Pleroma.Factory
+
+ @emoji_path Path.join(
+ Pleroma.Config.get!([:instance, :static_dir]),
+ "emoji"
+ )
+ setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false)
+
+ setup do
+ admin = insert(:user, is_admin: true)
+ token = insert(:oauth_admin_token, user: admin)
+
+ admin_conn =
+ build_conn()
+ |> assign(:user, admin)
+ |> assign(:token, token)
+
+ Pleroma.Emoji.reload()
+ {:ok, %{admin_conn: admin_conn}}
+ end
+
+ test "GET /api/pleroma/emoji/packs", %{conn: conn} do
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
+
+ shared = resp["test_pack"]
+ assert shared["files"] == %{"blank" => "blank.png"}
+ assert Map.has_key?(shared["pack"], "download-sha256")
+ assert shared["pack"]["can-download"]
+ assert shared["pack"]["share-files"]
+
+ non_shared = resp["test_pack_nonshared"]
+ assert non_shared["pack"]["share-files"] == false
+ assert non_shared["pack"]["can-download"] == false
+ end
+
+ describe "GET /api/pleroma/emoji/packs/remote" do
+ test "shareable instance", %{admin_conn: admin_conn, conn: conn} do
+ resp =
+ conn
+ |> get("/api/pleroma/emoji/packs")
+ |> json_response_and_validate_schema(200)
+
+ mock(fn
+ %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
+
+ %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: ["shareable_emoji_packs"]}})
+
+ %{method: :get, url: "https://example.com/api/pleroma/emoji/packs"} ->
+ json(resp)
+ end)
+
+ assert admin_conn
+ |> get("/api/pleroma/emoji/packs/remote?url=https://example.com")
+ |> json_response_and_validate_schema(200) == resp
+ end
+
+ test "non shareable instance", %{admin_conn: admin_conn} do
+ mock(fn
+ %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
+
+ %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: []}})
+ end)
+
+ assert admin_conn
+ |> get("/api/pleroma/emoji/packs/remote?url=https://example.com")
+ |> json_response_and_validate_schema(500) == %{
+ "error" => "The requested instance does not support sharing emoji packs"
+ }
+ end
+ end
+
+ describe "GET /api/pleroma/emoji/packs/:name/archive" do
+ test "download shared pack", %{conn: conn} do
+ resp =
+ conn
+ |> get("/api/pleroma/emoji/packs/test_pack/archive")
+ |> response(200)
+
+ {:ok, arch} = :zip.unzip(resp, [:memory])
+
+ assert Enum.find(arch, fn {n, _} -> n == 'pack.json' end)
+ assert Enum.find(arch, fn {n, _} -> n == 'blank.png' end)
+ end
+
+ test "non existing pack", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/emoji/packs/test_pack_for_import/archive")
+ |> json_response_and_validate_schema(:not_found) == %{
+ "error" => "Pack test_pack_for_import does not exist"
+ }
+ end
+
+ test "non downloadable pack", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/emoji/packs/test_pack_nonshared/archive")
+ |> json_response_and_validate_schema(:forbidden) == %{
+ "error" =>
+ "Pack test_pack_nonshared cannot be downloaded from this instance, either pack sharing was disabled for this pack or some files are missing"
+ }
+ end
+ end
+
+ describe "POST /api/pleroma/emoji/packs/download" do
+ test "shared pack from remote and non shared from fallback-src", %{
+ admin_conn: admin_conn,
+ conn: conn
+ } do
+ mock(fn
+ %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
+
+ %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: ["shareable_emoji_packs"]}})
+
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/test_pack"
+ } ->
+ conn
+ |> get("/api/pleroma/emoji/packs/test_pack")
+ |> json_response_and_validate_schema(200)
+ |> json()
+
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/test_pack/archive"
+ } ->
+ conn
+ |> get("/api/pleroma/emoji/packs/test_pack/archive")
+ |> response(200)
+ |> text()
+
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/test_pack_nonshared"
+ } ->
+ conn
+ |> get("/api/pleroma/emoji/packs/test_pack_nonshared")
+ |> json_response_and_validate_schema(200)
+ |> json()
+
+ %{
+ method: :get,
+ url: "https://nonshared-pack"
+ } ->
+ text(File.read!("#{@emoji_path}/test_pack_nonshared/nonshared.zip"))
+ end)
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/pleroma/emoji/packs/download", %{
+ url: "https://example.com",
+ name: "test_pack",
+ as: "test_pack2"
+ })
+ |> json_response_and_validate_schema(200) == "ok"
+
+ assert File.exists?("#{@emoji_path}/test_pack2/pack.json")
+ assert File.exists?("#{@emoji_path}/test_pack2/blank.png")
+
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/test_pack2")
+ |> json_response_and_validate_schema(200) == "ok"
+
+ refute File.exists?("#{@emoji_path}/test_pack2")
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post(
+ "/api/pleroma/emoji/packs/download",
+ %{
+ url: "https://example.com",
+ name: "test_pack_nonshared",
+ as: "test_pack_nonshared2"
+ }
+ )
+ |> json_response_and_validate_schema(200) == "ok"
+
+ assert File.exists?("#{@emoji_path}/test_pack_nonshared2/pack.json")
+ assert File.exists?("#{@emoji_path}/test_pack_nonshared2/blank.png")
+
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/test_pack_nonshared2")
+ |> json_response_and_validate_schema(200) == "ok"
+
+ refute File.exists?("#{@emoji_path}/test_pack_nonshared2")
+ end
+
+ test "nonshareable instance", %{admin_conn: admin_conn} do
+ mock(fn
+ %{method: :get, url: "https://old-instance/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://old-instance/nodeinfo/2.1.json"}]})
+
+ %{method: :get, url: "https://old-instance/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: []}})
+ end)
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post(
+ "/api/pleroma/emoji/packs/download",
+ %{
+ url: "https://old-instance",
+ name: "test_pack",
+ as: "test_pack2"
+ }
+ )
+ |> json_response_and_validate_schema(500) == %{
+ "error" => "The requested instance does not support sharing emoji packs"
+ }
+ end
+
+ test "checksum fail", %{admin_conn: admin_conn} do
+ mock(fn
+ %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
+
+ %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: ["shareable_emoji_packs"]}})
+
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/pack_bad_sha"
+ } ->
+ {:ok, pack} = Pleroma.Emoji.Pack.load_pack("pack_bad_sha")
+ %Tesla.Env{status: 200, body: Jason.encode!(pack)}
+
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/pack_bad_sha/archive"
+ } ->
+ %Tesla.Env{
+ status: 200,
+ body: File.read!("test/instance_static/emoji/pack_bad_sha/pack_bad_sha.zip")
+ }
+ end)
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/pleroma/emoji/packs/download", %{
+ url: "https://example.com",
+ name: "pack_bad_sha",
+ as: "pack_bad_sha2"
+ })
+ |> json_response_and_validate_schema(:internal_server_error) == %{
+ "error" => "SHA256 for the pack doesn't match the one sent by the server"
+ }
+ end
+
+ test "other error", %{admin_conn: admin_conn} do
+ mock(fn
+ %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
+ json(%{links: [%{href: "https://example.com/nodeinfo/2.1.json"}]})
+
+ %{method: :get, url: "https://example.com/nodeinfo/2.1.json"} ->
+ json(%{metadata: %{features: ["shareable_emoji_packs"]}})
+
+ %{
+ method: :get,
+ url: "https://example.com/api/pleroma/emoji/packs/test_pack"
+ } ->
+ {:ok, pack} = Pleroma.Emoji.Pack.load_pack("test_pack")
+ %Tesla.Env{status: 200, body: Jason.encode!(pack)}
+ end)
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/pleroma/emoji/packs/download", %{
+ url: "https://example.com",
+ name: "test_pack",
+ as: "test_pack2"
+ })
+ |> json_response_and_validate_schema(:internal_server_error) == %{
+ "error" =>
+ "The pack was not set as shared and there is no fallback src to download from"
+ }
+ end
+ end
+
+ describe "PATCH /api/pleroma/emoji/packs/:name" do
+ setup do
+ pack_file = "#{@emoji_path}/test_pack/pack.json"
+ original_content = File.read!(pack_file)
+
+ on_exit(fn ->
+ File.write!(pack_file, original_content)
+ end)
+
+ {:ok,
+ pack_file: pack_file,
+ new_data: %{
+ "license" => "Test license changed",
+ "homepage" => "https://pleroma.social",
+ "description" => "Test description",
+ "share-files" => false
+ }}
+ end
+
+ test "for a pack without a fallback source", ctx do
+ assert ctx[:admin_conn]
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/pleroma/emoji/packs/test_pack", %{"metadata" => ctx[:new_data]})
+ |> json_response_and_validate_schema(200) == ctx[:new_data]
+
+ assert Jason.decode!(File.read!(ctx[:pack_file]))["pack"] == ctx[:new_data]
+ end
+
+ test "for a pack with a fallback source", ctx do
+ mock(fn
+ %{
+ method: :get,
+ url: "https://nonshared-pack"
+ } ->
+ text(File.read!("#{@emoji_path}/test_pack_nonshared/nonshared.zip"))
+ end)
+
+ new_data = Map.put(ctx[:new_data], "fallback-src", "https://nonshared-pack")
+
+ new_data_with_sha =
+ Map.put(
+ new_data,
+ "fallback-src-sha256",
+ "74409E2674DAA06C072729C6C8426C4CB3B7E0B85ED77792DB7A436E11D76DAF"
+ )
+
+ assert ctx[:admin_conn]
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/pleroma/emoji/packs/test_pack", %{metadata: new_data})
+ |> json_response_and_validate_schema(200) == new_data_with_sha
+
+ assert Jason.decode!(File.read!(ctx[:pack_file]))["pack"] == new_data_with_sha
+ end
+
+ test "when the fallback source doesn't have all the files", ctx do
+ mock(fn
+ %{
+ method: :get,
+ url: "https://nonshared-pack"
+ } ->
+ {:ok, {'empty.zip', empty_arch}} = :zip.zip('empty.zip', [], [:memory])
+ text(empty_arch)
+ end)
+
+ new_data = Map.put(ctx[:new_data], "fallback-src", "https://nonshared-pack")
+
+ assert ctx[:admin_conn]
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/pleroma/emoji/packs/test_pack", %{metadata: new_data})
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "The fallback archive does not have all files specified in pack.json"
+ }
+ end
+ end
+
+ describe "POST/PATCH/DELETE /api/pleroma/emoji/packs/:name/files" do
+ setup do
+ pack_file = "#{@emoji_path}/test_pack/pack.json"
+ original_content = File.read!(pack_file)
+
+ on_exit(fn ->
+ File.write!(pack_file, original_content)
+ end)
+
+ :ok
+ end
+
+ test "create shortcode exists", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank",
+ filename: "dir/blank.png",
+ file: %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
+ }
+ })
+ |> json_response_and_validate_schema(:conflict) == %{
+ "error" => "An emoji with the \"blank\" shortcode already exists"
+ }
+ end
+
+ test "don't rewrite old emoji", %{admin_conn: admin_conn} do
+ on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir/") end)
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank2",
+ filename: "dir/blank.png",
+ file: %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
+ }
+ })
+ |> json_response_and_validate_schema(200) == %{
+ "blank" => "blank.png",
+ "blank2" => "dir/blank.png"
+ }
+
+ assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank",
+ new_shortcode: "blank2",
+ new_filename: "dir_2/blank_3.png"
+ })
+ |> json_response_and_validate_schema(:conflict) == %{
+ "error" =>
+ "New shortcode \"blank2\" is already used. If you want to override emoji use 'force' option"
+ }
+ end
+
+ test "rewrite old emoji with force option", %{admin_conn: admin_conn} do
+ on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir_2/") end)
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank2",
+ filename: "dir/blank.png",
+ file: %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
+ }
+ })
+ |> json_response_and_validate_schema(200) == %{
+ "blank" => "blank.png",
+ "blank2" => "dir/blank.png"
+ }
+
+ assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank2",
+ new_shortcode: "blank3",
+ new_filename: "dir_2/blank_3.png",
+ force: true
+ })
+ |> json_response_and_validate_schema(200) == %{
+ "blank" => "blank.png",
+ "blank3" => "dir_2/blank_3.png"
+ }
+
+ assert File.exists?("#{@emoji_path}/test_pack/dir_2/blank_3.png")
+ end
+
+ test "with empty filename", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank2",
+ filename: "",
+ file: %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
+ }
+ })
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack name, shortcode or filename cannot be empty"
+ }
+ end
+
+ test "add file with not loaded pack", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/pleroma/emoji/packs/not_loaded/files", %{
+ shortcode: "blank2",
+ filename: "dir/blank.png",
+ file: %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
+ }
+ })
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack \"not_loaded\" is not found"
+ }
+ end
+
+ test "remove file with not loaded pack", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/not_loaded/files?shortcode=blank3")
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack \"not_loaded\" is not found"
+ }
+ end
+
+ test "remove file with empty shortcode", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/not_loaded/files?shortcode=")
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack name or shortcode cannot be empty"
+ }
+ end
+
+ test "update file with not loaded pack", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/pleroma/emoji/packs/not_loaded/files", %{
+ shortcode: "blank4",
+ new_shortcode: "blank3",
+ new_filename: "dir_2/blank_3.png"
+ })
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack \"not_loaded\" is not found"
+ }
+ end
+
+ test "new with shortcode as file with update", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank4",
+ filename: "dir/blank.png",
+ file: %Plug.Upload{
+ filename: "blank.png",
+ path: "#{@emoji_path}/test_pack/blank.png"
+ }
+ })
+ |> json_response_and_validate_schema(200) == %{
+ "blank" => "blank.png",
+ "blank4" => "dir/blank.png"
+ }
+
+ assert File.exists?("#{@emoji_path}/test_pack/dir/blank.png")
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank4",
+ new_shortcode: "blank3",
+ new_filename: "dir_2/blank_3.png"
+ })
+ |> json_response_and_validate_schema(200) == %{
+ "blank3" => "dir_2/blank_3.png",
+ "blank" => "blank.png"
+ }
+
+ refute File.exists?("#{@emoji_path}/test_pack/dir/")
+ assert File.exists?("#{@emoji_path}/test_pack/dir_2/blank_3.png")
+
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/test_pack/files?shortcode=blank3")
+ |> json_response_and_validate_schema(200) == %{"blank" => "blank.png"}
+
+ refute File.exists?("#{@emoji_path}/test_pack/dir_2/")
+
+ on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/dir") end)
+ end
+
+ test "new with shortcode from url", %{admin_conn: admin_conn} do
+ mock(fn
+ %{
+ method: :get,
+ url: "https://test-blank/blank_url.png"
+ } ->
+ text(File.read!("#{@emoji_path}/test_pack/blank.png"))
+ end)
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank_url",
+ file: "https://test-blank/blank_url.png"
+ })
+ |> json_response_and_validate_schema(200) == %{
+ "blank_url" => "blank_url.png",
+ "blank" => "blank.png"
+ }
+
+ assert File.exists?("#{@emoji_path}/test_pack/blank_url.png")
+
+ on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/blank_url.png") end)
+ end
+
+ test "new without shortcode", %{admin_conn: admin_conn} do
+ on_exit(fn -> File.rm_rf!("#{@emoji_path}/test_pack/shortcode.png") end)
+
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> post("/api/pleroma/emoji/packs/test_pack/files", %{
+ file: %Plug.Upload{
+ filename: "shortcode.png",
+ path: "#{Pleroma.Config.get([:instance, :static_dir])}/add/shortcode.png"
+ }
+ })
+ |> json_response_and_validate_schema(200) == %{
+ "shortcode" => "shortcode.png",
+ "blank" => "blank.png"
+ }
+ end
+
+ test "remove non existing shortcode in pack.json", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/test_pack/files?shortcode=blank2")
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "Emoji \"blank2\" does not exist"
+ }
+ end
+
+ test "update non existing emoji", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank2",
+ new_shortcode: "blank3",
+ new_filename: "dir_2/blank_3.png"
+ })
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "Emoji \"blank2\" does not exist"
+ }
+ end
+
+ test "update with empty shortcode", %{admin_conn: admin_conn} do
+ assert %{
+ "error" => "Missing field: new_shortcode."
+ } =
+ admin_conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> patch("/api/pleroma/emoji/packs/test_pack/files", %{
+ shortcode: "blank",
+ new_filename: "dir_2/blank_3.png"
+ })
+ |> json_response_and_validate_schema(:bad_request)
+ end
+ end
+
+ describe "POST/DELETE /api/pleroma/emoji/packs/:name" do
+ test "creating and deleting a pack", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_created")
+ |> json_response_and_validate_schema(200) == "ok"
+
+ assert File.exists?("#{@emoji_path}/test_created/pack.json")
+
+ assert Jason.decode!(File.read!("#{@emoji_path}/test_created/pack.json")) == %{
+ "pack" => %{},
+ "files" => %{}
+ }
+
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/test_created")
+ |> json_response_and_validate_schema(200) == "ok"
+
+ refute File.exists?("#{@emoji_path}/test_created/pack.json")
+ end
+
+ test "if pack exists", %{admin_conn: admin_conn} do
+ path = Path.join(@emoji_path, "test_created")
+ File.mkdir(path)
+ pack_file = Jason.encode!(%{files: %{}, pack: %{}})
+ File.write!(Path.join(path, "pack.json"), pack_file)
+
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/test_created")
+ |> json_response_and_validate_schema(:conflict) == %{
+ "error" => "A pack named \"test_created\" already exists"
+ }
+
+ on_exit(fn -> File.rm_rf(path) end)
+ end
+
+ test "with empty name", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> post("/api/pleroma/emoji/packs/ ")
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack name cannot be empty"
+ }
+ end
+ end
+
+ test "deleting nonexisting pack", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/non_existing")
+ |> json_response_and_validate_schema(:not_found) == %{
+ "error" => "Pack non_existing does not exist"
+ }
+ end
+
+ test "deleting with empty name", %{admin_conn: admin_conn} do
+ assert admin_conn
+ |> delete("/api/pleroma/emoji/packs/ ")
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack name cannot be empty"
+ }
+ end
+
+ test "filesystem import", %{admin_conn: admin_conn, conn: conn} do
+ on_exit(fn ->
+ File.rm!("#{@emoji_path}/test_pack_for_import/emoji.txt")
+ File.rm!("#{@emoji_path}/test_pack_for_import/pack.json")
+ end)
+
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
+
+ refute Map.has_key?(resp, "test_pack_for_import")
+
+ assert admin_conn
+ |> get("/api/pleroma/emoji/packs/import")
+ |> json_response_and_validate_schema(200) == ["test_pack_for_import"]
+
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
+ assert resp["test_pack_for_import"]["files"] == %{"blank" => "blank.png"}
+
+ File.rm!("#{@emoji_path}/test_pack_for_import/pack.json")
+ refute File.exists?("#{@emoji_path}/test_pack_for_import/pack.json")
+
+ emoji_txt_content = """
+ blank, blank.png, Fun
+ blank2, blank.png
+ foo, /emoji/test_pack_for_import/blank.png
+ bar
+ """
+
+ File.write!("#{@emoji_path}/test_pack_for_import/emoji.txt", emoji_txt_content)
+
+ assert admin_conn
+ |> get("/api/pleroma/emoji/packs/import")
+ |> json_response_and_validate_schema(200) == ["test_pack_for_import"]
+
+ resp = conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)
+
+ assert resp["test_pack_for_import"]["files"] == %{
+ "blank" => "blank.png",
+ "blank2" => "blank.png",
+ "foo" => "blank.png"
+ }
+ end
+
+ describe "GET /api/pleroma/emoji/packs/:name" do
+ test "shows pack.json", %{conn: conn} do
+ assert %{
+ "files" => %{"blank" => "blank.png"},
+ "pack" => %{
+ "can-download" => true,
+ "description" => "Test description",
+ "download-sha256" => _,
+ "homepage" => "https://pleroma.social",
+ "license" => "Test license",
+ "share-files" => true
+ }
+ } =
+ conn
+ |> get("/api/pleroma/emoji/packs/test_pack")
+ |> json_response_and_validate_schema(200)
+ end
+
+ test "non existing pack", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/emoji/packs/non_existing")
+ |> json_response_and_validate_schema(:not_found) == %{
+ "error" => "Pack non_existing does not exist"
+ }
+ end
+
+ test "error name", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/emoji/packs/ ")
+ |> json_response_and_validate_schema(:bad_request) == %{
+ "error" => "pack name cannot be empty"
+ }
+ end
+ end
+end
--
cgit v1.2.3
From 45c3a7240449133176bf27bd2f753bb71d7f455b Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 18 May 2020 20:58:59 +0400
Subject: [OpenAPI] Use BooleanLike in all request bodies
---
test/web/mastodon_api/controllers/status_controller_test.exs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/status_controller_test.exs b/test/web/mastodon_api/controllers/status_controller_test.exs
index bdee88fd3..962e64b03 100644
--- a/test/web/mastodon_api/controllers/status_controller_test.exs
+++ b/test/web/mastodon_api/controllers/status_controller_test.exs
@@ -62,7 +62,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
|> post("/api/v1/statuses", %{
"status" => "cofe",
"spoiler_text" => "2hu",
- "sensitive" => "false"
+ "sensitive" => "0"
})
{:ok, ttl} = Cachex.ttl(:idempotency_cache, idempotency_key)
@@ -81,7 +81,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
|> post("/api/v1/statuses", %{
"status" => "cofe",
"spoiler_text" => "2hu",
- "sensitive" => "false"
+ "sensitive" => 0
})
assert %{"id" => second_id} = json_response(conn_two, 200)
@@ -93,7 +93,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
|> post("/api/v1/statuses", %{
"status" => "cofe",
"spoiler_text" => "2hu",
- "sensitive" => "false"
+ "sensitive" => "False"
})
assert %{"id" => third_id} = json_response_and_validate_schema(conn_three, 200)
--
cgit v1.2.3
From fe5d423b43d6d4c4cd63aaee27b8aa0966441e02 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 18 May 2020 22:00:32 +0400
Subject: Add OpenAPI spec for MascotController
---
.../controllers/mascot_controller_test.exs | 25 +++++++++++++++-------
1 file changed, 17 insertions(+), 8 deletions(-)
(limited to 'test')
diff --git a/test/web/pleroma_api/controllers/mascot_controller_test.exs b/test/web/pleroma_api/controllers/mascot_controller_test.exs
index 617831b02..e2ead6e15 100644
--- a/test/web/pleroma_api/controllers/mascot_controller_test.exs
+++ b/test/web/pleroma_api/controllers/mascot_controller_test.exs
@@ -16,9 +16,12 @@ defmodule Pleroma.Web.PleromaAPI.MascotControllerTest do
filename: "sound.mp3"
}
- ret_conn = put(conn, "/api/v1/pleroma/mascot", %{"file" => non_image_file})
+ ret_conn =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> put("/api/v1/pleroma/mascot", %{"file" => non_image_file})
- assert json_response(ret_conn, 415)
+ assert json_response_and_validate_schema(ret_conn, 415)
file = %Plug.Upload{
content_type: "image/jpg",
@@ -26,9 +29,12 @@ defmodule Pleroma.Web.PleromaAPI.MascotControllerTest do
filename: "an_image.jpg"
}
- conn = put(conn, "/api/v1/pleroma/mascot", %{"file" => file})
+ conn =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> put("/api/v1/pleroma/mascot", %{"file" => file})
- assert %{"id" => _, "type" => image} = json_response(conn, 200)
+ assert %{"id" => _, "type" => image} = json_response_and_validate_schema(conn, 200)
end
test "mascot retrieving" do
@@ -37,7 +43,7 @@ defmodule Pleroma.Web.PleromaAPI.MascotControllerTest do
# When user hasn't set a mascot, we should just get pleroma tan back
ret_conn = get(conn, "/api/v1/pleroma/mascot")
- assert %{"url" => url} = json_response(ret_conn, 200)
+ assert %{"url" => url} = json_response_and_validate_schema(ret_conn, 200)
assert url =~ "pleroma-fox-tan-smol"
# When a user sets their mascot, we should get that back
@@ -47,9 +53,12 @@ defmodule Pleroma.Web.PleromaAPI.MascotControllerTest do
filename: "an_image.jpg"
}
- ret_conn = put(conn, "/api/v1/pleroma/mascot", %{"file" => file})
+ ret_conn =
+ conn
+ |> put_req_header("content-type", "multipart/form-data")
+ |> put("/api/v1/pleroma/mascot", %{"file" => file})
- assert json_response(ret_conn, 200)
+ assert json_response_and_validate_schema(ret_conn, 200)
user = User.get_cached_by_id(user.id)
@@ -58,7 +67,7 @@ defmodule Pleroma.Web.PleromaAPI.MascotControllerTest do
|> assign(:user, user)
|> get("/api/v1/pleroma/mascot")
- assert %{"url" => url, "type" => "image"} = json_response(conn, 200)
+ assert %{"url" => url, "type" => "image"} = json_response_and_validate_schema(conn, 200)
assert url =~ "an_image"
end
end
--
cgit v1.2.3
From 5f0a3ac74d51333a778e6be26876fe26b0ff625b Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Mon, 18 May 2020 09:22:26 +0300
Subject: added tests
---
test/web/media_proxy/invalidations/http_test.exs | 35 ++++++++++++++++++++++
test/web/media_proxy/invalidations/script_test.exs | 20 +++++++++++++
2 files changed, 55 insertions(+)
create mode 100644 test/web/media_proxy/invalidations/http_test.exs
create mode 100644 test/web/media_proxy/invalidations/script_test.exs
(limited to 'test')
diff --git a/test/web/media_proxy/invalidations/http_test.exs b/test/web/media_proxy/invalidations/http_test.exs
new file mode 100644
index 000000000..8a3b4141c
--- /dev/null
+++ b/test/web/media_proxy/invalidations/http_test.exs
@@ -0,0 +1,35 @@
+defmodule Pleroma.Web.MediaProxy.Invalidation.HttpTest do
+ use ExUnit.Case
+ alias Pleroma.Web.MediaProxy.Invalidation
+
+ import ExUnit.CaptureLog
+ import Tesla.Mock
+
+ test "logs hasn't error message when request is valid" do
+ mock(fn
+ %{method: :purge, url: "http://example.com/media/example.jpg"} ->
+ %Tesla.Env{status: 200}
+ end)
+
+ refute capture_log(fn ->
+ assert Invalidation.Http.purge(
+ ["http://example.com/media/example.jpg"],
+ %{}
+ ) == {:ok, "success"}
+ end) =~ "Error while cache purge"
+ end
+
+ test "it write error message in logs when request invalid" do
+ mock(fn
+ %{method: :purge, url: "http://example.com/media/example1.jpg"} ->
+ %Tesla.Env{status: 404}
+ end)
+
+ assert capture_log(fn ->
+ assert Invalidation.Http.purge(
+ ["http://example.com/media/example1.jpg"],
+ %{}
+ ) == {:ok, "success"}
+ end) =~ "Error while cache purge: url - http://example.com/media/example1.jpg"
+ end
+end
diff --git a/test/web/media_proxy/invalidations/script_test.exs b/test/web/media_proxy/invalidations/script_test.exs
new file mode 100644
index 000000000..1358963ab
--- /dev/null
+++ b/test/web/media_proxy/invalidations/script_test.exs
@@ -0,0 +1,20 @@
+defmodule Pleroma.Web.MediaProxy.Invalidation.ScriptTest do
+ use ExUnit.Case
+ alias Pleroma.Web.MediaProxy.Invalidation
+
+ import ExUnit.CaptureLog
+
+ test "it logger error when script not found" do
+ assert capture_log(fn ->
+ assert Invalidation.Script.purge(
+ ["http://example.com/media/example.jpg"],
+ %{script_path: "./example"}
+ ) == {:error, "\"%ErlangError{original: :enoent}\""}
+ end) =~ "Error while cache purge: \"%ErlangError{original: :enoent}\""
+
+ assert Invalidation.Script.purge(
+ ["http://example.com/media/example.jpg"],
+ %{}
+ ) == {:error, "not found script path"}
+ end
+end
--
cgit v1.2.3
From 41f8f172609910efc9543632fecbd544d131535b Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Tue, 19 May 2020 09:42:41 +0300
Subject: fix api/v1/accounts/update_credentials
---
.../controllers/account_controller/update_credentials_test.exs | 7 +++++++
1 file changed, 7 insertions(+)
(limited to 'test')
diff --git a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
index fdb6d4c5d..696228203 100644
--- a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs
@@ -112,6 +112,13 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
assert user_data["source"]["privacy"] == "unlisted"
end
+ test "updates the user's privacy", %{conn: conn} do
+ conn = patch(conn, "/api/v1/accounts/update_credentials", %{source: %{privacy: "unlisted"}})
+
+ assert user_data = json_response_and_validate_schema(conn, 200)
+ assert user_data["source"]["privacy"] == "unlisted"
+ end
+
test "updates the user's hide_followers status", %{conn: conn} do
conn = patch(conn, "/api/v1/accounts/update_credentials", %{hide_followers: "true"})
--
cgit v1.2.3
From 524d04d9218f8e72bf88ab5e7d4b407452ae40bc Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 19 May 2020 15:53:18 +0400
Subject: Add OpenAPI spec for PleromaAPI.ScrobbleController
---
test/web/common_api/common_api_test.exs | 18 +++++++--------
.../controllers/scrobble_controller_test.exs | 26 ++++++++++++----------
2 files changed, 23 insertions(+), 21 deletions(-)
(limited to 'test')
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index fd8299013..52e95397c 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -841,10 +841,10 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} =
CommonAPI.listen(user, %{
- "title" => "lain radio episode 1",
- "album" => "lain radio",
- "artist" => "lain",
- "length" => 180_000
+ title: "lain radio episode 1",
+ album: "lain radio",
+ artist: "lain",
+ length: 180_000
})
object = Object.normalize(activity)
@@ -859,11 +859,11 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} =
CommonAPI.listen(user, %{
- "title" => "lain radio episode 1",
- "album" => "lain radio",
- "artist" => "lain",
- "length" => 180_000,
- "visibility" => "private"
+ title: "lain radio episode 1",
+ album: "lain radio",
+ artist: "lain",
+ length: 180_000,
+ visibility: "private"
})
object = Object.normalize(activity)
diff --git a/test/web/pleroma_api/controllers/scrobble_controller_test.exs b/test/web/pleroma_api/controllers/scrobble_controller_test.exs
index 1b945040c..f39c07ac6 100644
--- a/test/web/pleroma_api/controllers/scrobble_controller_test.exs
+++ b/test/web/pleroma_api/controllers/scrobble_controller_test.exs
@@ -12,14 +12,16 @@ defmodule Pleroma.Web.PleromaAPI.ScrobbleControllerTest do
%{conn: conn} = oauth_access(["write"])
conn =
- post(conn, "/api/v1/pleroma/scrobble", %{
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/pleroma/scrobble", %{
"title" => "lain radio episode 1",
"artist" => "lain",
"album" => "lain radio",
"length" => "180000"
})
- assert %{"title" => "lain radio episode 1"} = json_response(conn, 200)
+ assert %{"title" => "lain radio episode 1"} = json_response_and_validate_schema(conn, 200)
end
end
@@ -29,28 +31,28 @@ defmodule Pleroma.Web.PleromaAPI.ScrobbleControllerTest do
{:ok, _activity} =
CommonAPI.listen(user, %{
- "title" => "lain radio episode 1",
- "artist" => "lain",
- "album" => "lain radio"
+ title: "lain radio episode 1",
+ artist: "lain",
+ album: "lain radio"
})
{:ok, _activity} =
CommonAPI.listen(user, %{
- "title" => "lain radio episode 2",
- "artist" => "lain",
- "album" => "lain radio"
+ title: "lain radio episode 2",
+ artist: "lain",
+ album: "lain radio"
})
{:ok, _activity} =
CommonAPI.listen(user, %{
- "title" => "lain radio episode 3",
- "artist" => "lain",
- "album" => "lain radio"
+ title: "lain radio episode 3",
+ artist: "lain",
+ album: "lain radio"
})
conn = get(conn, "/api/v1/pleroma/accounts/#{user.id}/scrobbles")
- result = json_response(conn, 200)
+ result = json_response_and_validate_schema(conn, 200)
assert length(result) == 3
end
--
cgit v1.2.3
From 6609714d6694058e28ed789dd65eb50ca816c425 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 19 May 2020 16:11:59 +0400
Subject: Move Scrobble views to ScrobbleView
---
test/web/mastodon_api/views/status_view_test.exs | 10 ----------
test/web/pleroma_api/views/scrobble_view_test.exs | 20 ++++++++++++++++++++
2 files changed, 20 insertions(+), 10 deletions(-)
create mode 100644 test/web/pleroma_api/views/scrobble_view_test.exs
(limited to 'test')
diff --git a/test/web/mastodon_api/views/status_view_test.exs b/test/web/mastodon_api/views/status_view_test.exs
index 5d7adbe29..43e3bdca1 100644
--- a/test/web/mastodon_api/views/status_view_test.exs
+++ b/test/web/mastodon_api/views/status_view_test.exs
@@ -620,14 +620,4 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
assert status.visibility == "list"
end
-
- test "successfully renders a Listen activity (pleroma extension)" do
- listen_activity = insert(:listen)
-
- status = StatusView.render("listen.json", activity: listen_activity)
-
- assert status.length == listen_activity.data["object"]["length"]
- assert status.title == listen_activity.data["object"]["title"]
- assert_schema(status, "Status", Pleroma.Web.ApiSpec.spec())
- end
end
diff --git a/test/web/pleroma_api/views/scrobble_view_test.exs b/test/web/pleroma_api/views/scrobble_view_test.exs
new file mode 100644
index 000000000..6bdb56509
--- /dev/null
+++ b/test/web/pleroma_api/views/scrobble_view_test.exs
@@ -0,0 +1,20 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.PleromaAPI.StatusViewTest do
+ use Pleroma.DataCase
+
+ alias Pleroma.Web.PleromaAPI.ScrobbleView
+
+ import Pleroma.Factory
+
+ test "successfully renders a Listen activity (pleroma extension)" do
+ listen_activity = insert(:listen)
+
+ status = ScrobbleView.render("show.json", activity: listen_activity)
+
+ assert status.length == listen_activity.data["object"]["length"]
+ assert status.title == listen_activity.data["object"]["title"]
+ end
+end
--
cgit v1.2.3
From 2328eff09c4f3fac8c1c6eea5920ef58b42ac377 Mon Sep 17 00:00:00 2001
From: lain
Date: Tue, 19 May 2020 14:36:13 +0200
Subject: UserTest: Hide warning in tests.
---
test/user_test.exs | 1 +
1 file changed, 1 insertion(+)
(limited to 'test')
diff --git a/test/user_test.exs b/test/user_test.exs
index 6b9df60a4..239d16799 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -555,6 +555,7 @@ defmodule Pleroma.UserTest do
assert user == fetched_user
end
+ @tag capture_log: true
test "returns nil if no user could be fetched" do
{:error, fetched_user} = User.get_or_fetch_by_nickname("nonexistant@social.heldscal.la")
assert fetched_user == "not found nonexistant@social.heldscal.la"
--
cgit v1.2.3
From 490a3a34b63fa10e9151e9a385920c10615a1a3c Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 19 May 2020 21:52:26 +0400
Subject: Add OpenAPI spec for PleromaAPI.PleromaAPIController
---
test/support/api_spec_helpers.ex | 2 +-
.../controllers/pleroma_api_controller_test.exs | 44 +++++++++++-----------
2 files changed, 23 insertions(+), 23 deletions(-)
(limited to 'test')
diff --git a/test/support/api_spec_helpers.ex b/test/support/api_spec_helpers.ex
index 80c69c788..46388f92c 100644
--- a/test/support/api_spec_helpers.ex
+++ b/test/support/api_spec_helpers.ex
@@ -51,7 +51,7 @@ defmodule Pleroma.Tests.ApiSpecHelpers do
|> Map.take([:delete, :get, :head, :options, :patch, :post, :put, :trace])
|> Map.values()
|> Enum.reject(&is_nil/1)
- |> Enum.uniq()
end)
+ |> Enum.uniq()
end
end
diff --git a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
index cfd1dbd24..f0cdc2f08 100644
--- a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
@@ -27,7 +27,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
|> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"]))
|> put("/api/v1/pleroma/statuses/#{activity.id}/reactions/☕")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
# We return the status, but this our implementation detail.
assert %{"id" => id} = result
@@ -53,7 +53,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"]))
|> delete("/api/v1/pleroma/statuses/#{activity.id}/reactions/☕")
- assert %{"id" => id} = json_response(result, 200)
+ assert %{"id" => id} = json_response_and_validate_schema(result, 200)
assert to_string(activity.id) == id
ObanHelpers.perform_all()
@@ -73,7 +73,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
result =
conn
|> get("/api/v1/pleroma/statuses/#{activity.id}/reactions")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert result == []
@@ -85,7 +85,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
result =
conn
|> get("/api/v1/pleroma/statuses/#{activity.id}/reactions")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
[%{"name" => "🎅", "count" => 1, "accounts" => [represented_user], "me" => false}] = result
@@ -96,7 +96,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
|> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:statuses"]))
|> get("/api/v1/pleroma/statuses/#{activity.id}/reactions")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert [%{"name" => "🎅", "count" => 1, "accounts" => [_represented_user], "me" => true}] =
result
@@ -111,7 +111,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
result =
conn
|> get("/api/v1/pleroma/statuses/#{activity.id}/reactions/🎅")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert result == []
@@ -121,7 +121,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
result =
conn
|> get("/api/v1/pleroma/statuses/#{activity.id}/reactions/🎅")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
[%{"name" => "🎅", "count" => 1, "accounts" => [represented_user], "me" => false}] = result
@@ -140,7 +140,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
result =
conn
|> get("/api/v1/pleroma/conversations/#{participation.id}")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert result["id"] == participation.id |> to_string()
end
@@ -168,7 +168,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
result =
conn
|> get("/api/v1/pleroma/conversations/#{participation.id}/statuses")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert length(result) == 2
@@ -186,12 +186,12 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
assert [%{"id" => ^id_two}, %{"id" => ^id_three}] =
conn
|> get("/api/v1/pleroma/conversations/#{participation.id}/statuses?limit=2")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert [%{"id" => ^id_three}] =
conn
|> get("/api/v1/pleroma/conversations/#{participation.id}/statuses?min_id=#{id_two}")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
end
test "PATCH /api/v1/pleroma/conversations/:id" do
@@ -208,12 +208,12 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
assert [user] == participation.recipients
assert other_user not in participation.recipients
+ query = "recipients[]=#{user.id}&recipients[]=#{other_user.id}"
+
result =
conn
- |> patch("/api/v1/pleroma/conversations/#{participation.id}", %{
- "recipients" => [user.id, other_user.id]
- })
- |> json_response(200)
+ |> patch("/api/v1/pleroma/conversations/#{participation.id}?#{query}")
+ |> json_response_and_validate_schema(200)
assert result["id"] == participation.id |> to_string
@@ -242,7 +242,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
[%{"unread" => false}, %{"unread" => false}] =
conn
|> post("/api/v1/pleroma/conversations/read", %{})
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
[participation2, participation1] = Participation.for_user(other_user)
assert Participation.get(participation2.id).read == true
@@ -262,8 +262,8 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
response =
conn
- |> post("/api/v1/pleroma/notifications/read", %{"id" => "#{notification1.id}"})
- |> json_response(:ok)
+ |> post("/api/v1/pleroma/notifications/read?id=#{notification1.id}")
+ |> json_response_and_validate_schema(:ok)
assert %{"pleroma" => %{"is_seen" => true}} = response
assert Repo.get(Notification, notification1.id).seen
@@ -280,8 +280,8 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
[response1, response2] =
conn
- |> post("/api/v1/pleroma/notifications/read", %{"max_id" => "#{notification2.id}"})
- |> json_response(:ok)
+ |> post("/api/v1/pleroma/notifications/read?max_id=#{notification2.id}")
+ |> json_response_and_validate_schema(:ok)
assert %{"pleroma" => %{"is_seen" => true}} = response1
assert %{"pleroma" => %{"is_seen" => true}} = response2
@@ -293,8 +293,8 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
test "it returns error when notification not found", %{conn: conn} do
response =
conn
- |> post("/api/v1/pleroma/notifications/read", %{"id" => "22222222222222"})
- |> json_response(:bad_request)
+ |> post("/api/v1/pleroma/notifications/read?id=22222222222222")
+ |> json_response_and_validate_schema(:bad_request)
assert response == %{"error" => "Cannot get notification"}
end
--
cgit v1.2.3
From 9a5de0f4548cfe6b62265596bbe3cef2d639b978 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Tue, 19 May 2020 23:50:49 +0400
Subject: Move reaction actions to EmojiReactionController
---
.../controllers/emoji_reaction_controller_test.exs | 125 +++++++++++++++++++++
.../controllers/pleroma_api_controller_test.exs | 115 -------------------
2 files changed, 125 insertions(+), 115 deletions(-)
create mode 100644 test/web/pleroma_api/controllers/emoji_reaction_controller_test.exs
(limited to 'test')
diff --git a/test/web/pleroma_api/controllers/emoji_reaction_controller_test.exs b/test/web/pleroma_api/controllers/emoji_reaction_controller_test.exs
new file mode 100644
index 000000000..ee66ebf87
--- /dev/null
+++ b/test/web/pleroma_api/controllers/emoji_reaction_controller_test.exs
@@ -0,0 +1,125 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.PleromaAPI.EmojiReactionControllerTest do
+ use Oban.Testing, repo: Pleroma.Repo
+ use Pleroma.Web.ConnCase
+
+ alias Pleroma.Object
+ alias Pleroma.Tests.ObanHelpers
+ alias Pleroma.User
+ alias Pleroma.Web.CommonAPI
+
+ import Pleroma.Factory
+
+ test "PUT /api/v1/pleroma/statuses/:id/reactions/:emoji", %{conn: conn} do
+ user = insert(:user)
+ other_user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
+
+ result =
+ conn
+ |> assign(:user, other_user)
+ |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"]))
+ |> put("/api/v1/pleroma/statuses/#{activity.id}/reactions/☕")
+ |> json_response_and_validate_schema(200)
+
+ # We return the status, but this our implementation detail.
+ assert %{"id" => id} = result
+ assert to_string(activity.id) == id
+
+ assert result["pleroma"]["emoji_reactions"] == [
+ %{"name" => "☕", "count" => 1, "me" => true}
+ ]
+ end
+
+ test "DELETE /api/v1/pleroma/statuses/:id/reactions/:emoji", %{conn: conn} do
+ user = insert(:user)
+ other_user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
+ {:ok, _reaction_activity} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
+
+ ObanHelpers.perform_all()
+
+ result =
+ conn
+ |> assign(:user, other_user)
+ |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"]))
+ |> delete("/api/v1/pleroma/statuses/#{activity.id}/reactions/☕")
+
+ assert %{"id" => id} = json_response_and_validate_schema(result, 200)
+ assert to_string(activity.id) == id
+
+ ObanHelpers.perform_all()
+
+ object = Object.get_by_ap_id(activity.data["object"])
+
+ assert object.data["reaction_count"] == 0
+ end
+
+ test "GET /api/v1/pleroma/statuses/:id/reactions", %{conn: conn} do
+ user = insert(:user)
+ other_user = insert(:user)
+ doomed_user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
+
+ result =
+ conn
+ |> get("/api/v1/pleroma/statuses/#{activity.id}/reactions")
+ |> json_response_and_validate_schema(200)
+
+ assert result == []
+
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, other_user, "🎅")
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, doomed_user, "🎅")
+
+ User.perform(:delete, doomed_user)
+
+ result =
+ conn
+ |> get("/api/v1/pleroma/statuses/#{activity.id}/reactions")
+ |> json_response_and_validate_schema(200)
+
+ [%{"name" => "🎅", "count" => 1, "accounts" => [represented_user], "me" => false}] = result
+
+ assert represented_user["id"] == other_user.id
+
+ result =
+ conn
+ |> assign(:user, other_user)
+ |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:statuses"]))
+ |> get("/api/v1/pleroma/statuses/#{activity.id}/reactions")
+ |> json_response_and_validate_schema(200)
+
+ assert [%{"name" => "🎅", "count" => 1, "accounts" => [_represented_user], "me" => true}] =
+ result
+ end
+
+ test "GET /api/v1/pleroma/statuses/:id/reactions/:emoji", %{conn: conn} do
+ user = insert(:user)
+ other_user = insert(:user)
+
+ {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
+
+ result =
+ conn
+ |> get("/api/v1/pleroma/statuses/#{activity.id}/reactions/🎅")
+ |> json_response_and_validate_schema(200)
+
+ assert result == []
+
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, other_user, "🎅")
+ {:ok, _} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
+
+ assert [%{"name" => "🎅", "count" => 1, "accounts" => [represented_user], "me" => false}] =
+ conn
+ |> get("/api/v1/pleroma/statuses/#{activity.id}/reactions/🎅")
+ |> json_response_and_validate_schema(200)
+
+ assert represented_user["id"] == other_user.id
+ end
+end
diff --git a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
index f0cdc2f08..6f4f01e6f 100644
--- a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
@@ -3,131 +3,16 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
- use Oban.Testing, repo: Pleroma.Repo
use Pleroma.Web.ConnCase
alias Pleroma.Conversation.Participation
alias Pleroma.Notification
- alias Pleroma.Object
alias Pleroma.Repo
- alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
alias Pleroma.Web.CommonAPI
import Pleroma.Factory
- test "PUT /api/v1/pleroma/statuses/:id/reactions/:emoji", %{conn: conn} do
- user = insert(:user)
- other_user = insert(:user)
-
- {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
-
- result =
- conn
- |> assign(:user, other_user)
- |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"]))
- |> put("/api/v1/pleroma/statuses/#{activity.id}/reactions/☕")
- |> json_response_and_validate_schema(200)
-
- # We return the status, but this our implementation detail.
- assert %{"id" => id} = result
- assert to_string(activity.id) == id
-
- assert result["pleroma"]["emoji_reactions"] == [
- %{"name" => "☕", "count" => 1, "me" => true}
- ]
- end
-
- test "DELETE /api/v1/pleroma/statuses/:id/reactions/:emoji", %{conn: conn} do
- user = insert(:user)
- other_user = insert(:user)
-
- {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
- {:ok, _reaction_activity} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
-
- ObanHelpers.perform_all()
-
- result =
- conn
- |> assign(:user, other_user)
- |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"]))
- |> delete("/api/v1/pleroma/statuses/#{activity.id}/reactions/☕")
-
- assert %{"id" => id} = json_response_and_validate_schema(result, 200)
- assert to_string(activity.id) == id
-
- ObanHelpers.perform_all()
-
- object = Object.get_by_ap_id(activity.data["object"])
-
- assert object.data["reaction_count"] == 0
- end
-
- test "GET /api/v1/pleroma/statuses/:id/reactions", %{conn: conn} do
- user = insert(:user)
- other_user = insert(:user)
- doomed_user = insert(:user)
-
- {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
-
- result =
- conn
- |> get("/api/v1/pleroma/statuses/#{activity.id}/reactions")
- |> json_response_and_validate_schema(200)
-
- assert result == []
-
- {:ok, _} = CommonAPI.react_with_emoji(activity.id, other_user, "🎅")
- {:ok, _} = CommonAPI.react_with_emoji(activity.id, doomed_user, "🎅")
-
- User.perform(:delete, doomed_user)
-
- result =
- conn
- |> get("/api/v1/pleroma/statuses/#{activity.id}/reactions")
- |> json_response_and_validate_schema(200)
-
- [%{"name" => "🎅", "count" => 1, "accounts" => [represented_user], "me" => false}] = result
-
- assert represented_user["id"] == other_user.id
-
- result =
- conn
- |> assign(:user, other_user)
- |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:statuses"]))
- |> get("/api/v1/pleroma/statuses/#{activity.id}/reactions")
- |> json_response_and_validate_schema(200)
-
- assert [%{"name" => "🎅", "count" => 1, "accounts" => [_represented_user], "me" => true}] =
- result
- end
-
- test "GET /api/v1/pleroma/statuses/:id/reactions/:emoji", %{conn: conn} do
- user = insert(:user)
- other_user = insert(:user)
-
- {:ok, activity} = CommonAPI.post(user, %{status: "#cofe"})
-
- result =
- conn
- |> get("/api/v1/pleroma/statuses/#{activity.id}/reactions/🎅")
- |> json_response_and_validate_schema(200)
-
- assert result == []
-
- {:ok, _} = CommonAPI.react_with_emoji(activity.id, other_user, "🎅")
- {:ok, _} = CommonAPI.react_with_emoji(activity.id, other_user, "☕")
-
- result =
- conn
- |> get("/api/v1/pleroma/statuses/#{activity.id}/reactions/🎅")
- |> json_response_and_validate_schema(200)
-
- [%{"name" => "🎅", "count" => 1, "accounts" => [represented_user], "me" => false}] = result
-
- assert represented_user["id"] == other_user.id
- end
-
test "/api/v1/pleroma/conversations/:id" do
user = insert(:user)
%{user: other_user, conn: conn} = oauth_access(["read:statuses"])
--
cgit v1.2.3
From f3fc8b22b1dca8d432d066417e2bb9b62a3f1520 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 20 May 2020 15:00:11 +0400
Subject: Move conversation actions to PleromaAPI.ConversationController
---
.../controllers/conversation_controller_test.exs | 136 +++++++++++++++++++++
.../controllers/pleroma_api_controller_test.exs | 124 -------------------
2 files changed, 136 insertions(+), 124 deletions(-)
create mode 100644 test/web/pleroma_api/controllers/conversation_controller_test.exs
(limited to 'test')
diff --git a/test/web/pleroma_api/controllers/conversation_controller_test.exs b/test/web/pleroma_api/controllers/conversation_controller_test.exs
new file mode 100644
index 000000000..e6d0b3e37
--- /dev/null
+++ b/test/web/pleroma_api/controllers/conversation_controller_test.exs
@@ -0,0 +1,136 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.PleromaAPI.ConversationControllerTest do
+ use Pleroma.Web.ConnCase
+
+ alias Pleroma.Conversation.Participation
+ alias Pleroma.Repo
+ alias Pleroma.User
+ alias Pleroma.Web.CommonAPI
+
+ import Pleroma.Factory
+
+ test "/api/v1/pleroma/conversations/:id" do
+ user = insert(:user)
+ %{user: other_user, conn: conn} = oauth_access(["read:statuses"])
+
+ {:ok, _activity} =
+ CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}!", visibility: "direct"})
+
+ [participation] = Participation.for_user(other_user)
+
+ result =
+ conn
+ |> get("/api/v1/pleroma/conversations/#{participation.id}")
+ |> json_response_and_validate_schema(200)
+
+ assert result["id"] == participation.id |> to_string()
+ end
+
+ test "/api/v1/pleroma/conversations/:id/statuses" do
+ user = insert(:user)
+ %{user: other_user, conn: conn} = oauth_access(["read:statuses"])
+ third_user = insert(:user)
+
+ {:ok, _activity} =
+ CommonAPI.post(user, %{status: "Hi @#{third_user.nickname}!", visibility: "direct"})
+
+ {:ok, activity} =
+ CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}!", visibility: "direct"})
+
+ [participation] = Participation.for_user(other_user)
+
+ {:ok, activity_two} =
+ CommonAPI.post(other_user, %{
+ status: "Hi!",
+ in_reply_to_status_id: activity.id,
+ in_reply_to_conversation_id: participation.id
+ })
+
+ result =
+ conn
+ |> get("/api/v1/pleroma/conversations/#{participation.id}/statuses")
+ |> json_response_and_validate_schema(200)
+
+ assert length(result) == 2
+
+ id_one = activity.id
+ id_two = activity_two.id
+ assert [%{"id" => ^id_one}, %{"id" => ^id_two}] = result
+
+ {:ok, %{id: id_three}} =
+ CommonAPI.post(other_user, %{
+ status: "Bye!",
+ in_reply_to_status_id: activity.id,
+ in_reply_to_conversation_id: participation.id
+ })
+
+ assert [%{"id" => ^id_two}, %{"id" => ^id_three}] =
+ conn
+ |> get("/api/v1/pleroma/conversations/#{participation.id}/statuses?limit=2")
+ |> json_response_and_validate_schema(:ok)
+
+ assert [%{"id" => ^id_three}] =
+ conn
+ |> get("/api/v1/pleroma/conversations/#{participation.id}/statuses?min_id=#{id_two}")
+ |> json_response_and_validate_schema(:ok)
+ end
+
+ test "PATCH /api/v1/pleroma/conversations/:id" do
+ %{user: user, conn: conn} = oauth_access(["write:conversations"])
+ other_user = insert(:user)
+
+ {:ok, _activity} = CommonAPI.post(user, %{status: "Hi", visibility: "direct"})
+
+ [participation] = Participation.for_user(user)
+
+ participation = Repo.preload(participation, :recipients)
+
+ user = User.get_cached_by_id(user.id)
+ assert [user] == participation.recipients
+ assert other_user not in participation.recipients
+
+ query = "recipients[]=#{user.id}&recipients[]=#{other_user.id}"
+
+ result =
+ conn
+ |> patch("/api/v1/pleroma/conversations/#{participation.id}?#{query}")
+ |> json_response_and_validate_schema(200)
+
+ assert result["id"] == participation.id |> to_string
+
+ [participation] = Participation.for_user(user)
+ participation = Repo.preload(participation, :recipients)
+
+ assert user in participation.recipients
+ assert other_user in participation.recipients
+ end
+
+ test "POST /api/v1/pleroma/conversations/read" do
+ user = insert(:user)
+ %{user: other_user, conn: conn} = oauth_access(["write:conversations"])
+
+ {:ok, _activity} =
+ CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}", visibility: "direct"})
+
+ {:ok, _activity} =
+ CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}", visibility: "direct"})
+
+ [participation2, participation1] = Participation.for_user(other_user)
+ assert Participation.get(participation2.id).read == false
+ assert Participation.get(participation1.id).read == false
+ assert User.get_cached_by_id(other_user.id).unread_conversation_count == 2
+
+ [%{"unread" => false}, %{"unread" => false}] =
+ conn
+ |> post("/api/v1/pleroma/conversations/read", %{})
+ |> json_response_and_validate_schema(200)
+
+ [participation2, participation1] = Participation.for_user(other_user)
+ assert Participation.get(participation2.id).read == true
+ assert Participation.get(participation1.id).read == true
+ assert User.get_cached_by_id(other_user.id).unread_conversation_count == 0
+ end
+end
diff --git a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
index 6f4f01e6f..c4c661266 100644
--- a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
+++ b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
@@ -5,136 +5,12 @@
defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
use Pleroma.Web.ConnCase
- alias Pleroma.Conversation.Participation
alias Pleroma.Notification
alias Pleroma.Repo
- alias Pleroma.User
alias Pleroma.Web.CommonAPI
import Pleroma.Factory
- test "/api/v1/pleroma/conversations/:id" do
- user = insert(:user)
- %{user: other_user, conn: conn} = oauth_access(["read:statuses"])
-
- {:ok, _activity} =
- CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}!", visibility: "direct"})
-
- [participation] = Participation.for_user(other_user)
-
- result =
- conn
- |> get("/api/v1/pleroma/conversations/#{participation.id}")
- |> json_response_and_validate_schema(200)
-
- assert result["id"] == participation.id |> to_string()
- end
-
- test "/api/v1/pleroma/conversations/:id/statuses" do
- user = insert(:user)
- %{user: other_user, conn: conn} = oauth_access(["read:statuses"])
- third_user = insert(:user)
-
- {:ok, _activity} =
- CommonAPI.post(user, %{status: "Hi @#{third_user.nickname}!", visibility: "direct"})
-
- {:ok, activity} =
- CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}!", visibility: "direct"})
-
- [participation] = Participation.for_user(other_user)
-
- {:ok, activity_two} =
- CommonAPI.post(other_user, %{
- status: "Hi!",
- in_reply_to_status_id: activity.id,
- in_reply_to_conversation_id: participation.id
- })
-
- result =
- conn
- |> get("/api/v1/pleroma/conversations/#{participation.id}/statuses")
- |> json_response_and_validate_schema(200)
-
- assert length(result) == 2
-
- id_one = activity.id
- id_two = activity_two.id
- assert [%{"id" => ^id_one}, %{"id" => ^id_two}] = result
-
- {:ok, %{id: id_three}} =
- CommonAPI.post(other_user, %{
- status: "Bye!",
- in_reply_to_status_id: activity.id,
- in_reply_to_conversation_id: participation.id
- })
-
- assert [%{"id" => ^id_two}, %{"id" => ^id_three}] =
- conn
- |> get("/api/v1/pleroma/conversations/#{participation.id}/statuses?limit=2")
- |> json_response_and_validate_schema(:ok)
-
- assert [%{"id" => ^id_three}] =
- conn
- |> get("/api/v1/pleroma/conversations/#{participation.id}/statuses?min_id=#{id_two}")
- |> json_response_and_validate_schema(:ok)
- end
-
- test "PATCH /api/v1/pleroma/conversations/:id" do
- %{user: user, conn: conn} = oauth_access(["write:conversations"])
- other_user = insert(:user)
-
- {:ok, _activity} = CommonAPI.post(user, %{status: "Hi", visibility: "direct"})
-
- [participation] = Participation.for_user(user)
-
- participation = Repo.preload(participation, :recipients)
-
- user = User.get_cached_by_id(user.id)
- assert [user] == participation.recipients
- assert other_user not in participation.recipients
-
- query = "recipients[]=#{user.id}&recipients[]=#{other_user.id}"
-
- result =
- conn
- |> patch("/api/v1/pleroma/conversations/#{participation.id}?#{query}")
- |> json_response_and_validate_schema(200)
-
- assert result["id"] == participation.id |> to_string
-
- [participation] = Participation.for_user(user)
- participation = Repo.preload(participation, :recipients)
-
- assert user in participation.recipients
- assert other_user in participation.recipients
- end
-
- test "POST /api/v1/pleroma/conversations/read" do
- user = insert(:user)
- %{user: other_user, conn: conn} = oauth_access(["write:conversations"])
-
- {:ok, _activity} =
- CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}", visibility: "direct"})
-
- {:ok, _activity} =
- CommonAPI.post(user, %{status: "Hi @#{other_user.nickname}", visibility: "direct"})
-
- [participation2, participation1] = Participation.for_user(other_user)
- assert Participation.get(participation2.id).read == false
- assert Participation.get(participation1.id).read == false
- assert User.get_cached_by_id(other_user.id).unread_conversation_count == 2
-
- [%{"unread" => false}, %{"unread" => false}] =
- conn
- |> post("/api/v1/pleroma/conversations/read", %{})
- |> json_response_and_validate_schema(200)
-
- [participation2, participation1] = Participation.for_user(other_user)
- assert Participation.get(participation2.id).read == true
- assert Participation.get(participation1.id).read == true
- assert User.get_cached_by_id(other_user.id).unread_conversation_count == 0
- end
-
describe "POST /api/v1/pleroma/notifications/read" do
setup do: oauth_access(["write:notifications"])
--
cgit v1.2.3
From 5ba6e1c322c0937849eca53fc816f348659fb34c Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 20 May 2020 15:14:11 +0400
Subject: Move notification actions to PleromaAPI.NotificationController
---
.../controllers/notification_controller_test.exs | 63 ++++++++++++++++++++++
.../controllers/pleroma_api_controller_test.exs | 63 ----------------------
2 files changed, 63 insertions(+), 63 deletions(-)
create mode 100644 test/web/pleroma_api/controllers/notification_controller_test.exs
delete mode 100644 test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
(limited to 'test')
diff --git a/test/web/pleroma_api/controllers/notification_controller_test.exs b/test/web/pleroma_api/controllers/notification_controller_test.exs
new file mode 100644
index 000000000..7c5ace804
--- /dev/null
+++ b/test/web/pleroma_api/controllers/notification_controller_test.exs
@@ -0,0 +1,63 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.PleromaAPI.NotificationControllerTest do
+ use Pleroma.Web.ConnCase
+
+ alias Pleroma.Notification
+ alias Pleroma.Repo
+ alias Pleroma.Web.CommonAPI
+
+ import Pleroma.Factory
+
+ describe "POST /api/v1/pleroma/notifications/read" do
+ setup do: oauth_access(["write:notifications"])
+
+ test "it marks a single notification as read", %{user: user1, conn: conn} do
+ user2 = insert(:user)
+ {:ok, activity1} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
+ {:ok, activity2} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
+ {:ok, [notification1]} = Notification.create_notifications(activity1)
+ {:ok, [notification2]} = Notification.create_notifications(activity2)
+
+ response =
+ conn
+ |> post("/api/v1/pleroma/notifications/read?id=#{notification1.id}")
+ |> json_response_and_validate_schema(:ok)
+
+ assert %{"pleroma" => %{"is_seen" => true}} = response
+ assert Repo.get(Notification, notification1.id).seen
+ refute Repo.get(Notification, notification2.id).seen
+ end
+
+ test "it marks multiple notifications as read", %{user: user1, conn: conn} do
+ user2 = insert(:user)
+ {:ok, _activity1} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
+ {:ok, _activity2} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
+ {:ok, _activity3} = CommonAPI.post(user2, %{status: "HIE @#{user1.nickname}"})
+
+ [notification3, notification2, notification1] = Notification.for_user(user1, %{limit: 3})
+
+ [response1, response2] =
+ conn
+ |> post("/api/v1/pleroma/notifications/read?max_id=#{notification2.id}")
+ |> json_response_and_validate_schema(:ok)
+
+ assert %{"pleroma" => %{"is_seen" => true}} = response1
+ assert %{"pleroma" => %{"is_seen" => true}} = response2
+ assert Repo.get(Notification, notification1.id).seen
+ assert Repo.get(Notification, notification2.id).seen
+ refute Repo.get(Notification, notification3.id).seen
+ end
+
+ test "it returns error when notification not found", %{conn: conn} do
+ response =
+ conn
+ |> post("/api/v1/pleroma/notifications/read?id=22222222222222")
+ |> json_response_and_validate_schema(:bad_request)
+
+ assert response == %{"error" => "Cannot get notification"}
+ end
+ end
+end
diff --git a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
deleted file mode 100644
index c4c661266..000000000
--- a/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs
+++ /dev/null
@@ -1,63 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Web.PleromaAPI.PleromaAPIControllerTest do
- use Pleroma.Web.ConnCase
-
- alias Pleroma.Notification
- alias Pleroma.Repo
- alias Pleroma.Web.CommonAPI
-
- import Pleroma.Factory
-
- describe "POST /api/v1/pleroma/notifications/read" do
- setup do: oauth_access(["write:notifications"])
-
- test "it marks a single notification as read", %{user: user1, conn: conn} do
- user2 = insert(:user)
- {:ok, activity1} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
- {:ok, activity2} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
- {:ok, [notification1]} = Notification.create_notifications(activity1)
- {:ok, [notification2]} = Notification.create_notifications(activity2)
-
- response =
- conn
- |> post("/api/v1/pleroma/notifications/read?id=#{notification1.id}")
- |> json_response_and_validate_schema(:ok)
-
- assert %{"pleroma" => %{"is_seen" => true}} = response
- assert Repo.get(Notification, notification1.id).seen
- refute Repo.get(Notification, notification2.id).seen
- end
-
- test "it marks multiple notifications as read", %{user: user1, conn: conn} do
- user2 = insert(:user)
- {:ok, _activity1} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
- {:ok, _activity2} = CommonAPI.post(user2, %{status: "hi @#{user1.nickname}"})
- {:ok, _activity3} = CommonAPI.post(user2, %{status: "HIE @#{user1.nickname}"})
-
- [notification3, notification2, notification1] = Notification.for_user(user1, %{limit: 3})
-
- [response1, response2] =
- conn
- |> post("/api/v1/pleroma/notifications/read?max_id=#{notification2.id}")
- |> json_response_and_validate_schema(:ok)
-
- assert %{"pleroma" => %{"is_seen" => true}} = response1
- assert %{"pleroma" => %{"is_seen" => true}} = response2
- assert Repo.get(Notification, notification1.id).seen
- assert Repo.get(Notification, notification2.id).seen
- refute Repo.get(Notification, notification3.id).seen
- end
-
- test "it returns error when notification not found", %{conn: conn} do
- response =
- conn
- |> post("/api/v1/pleroma/notifications/read?id=22222222222222")
- |> json_response_and_validate_schema(:bad_request)
-
- assert response == %{"error" => "Cannot get notification"}
- end
- end
-end
--
cgit v1.2.3
From eb5f4285651c923aa3d776a2bc317c2a902031cc Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 20 May 2020 13:38:47 +0200
Subject: CommonAPI: Change public->private implicit addressing.
This will not add the OP to the `to` field anymore when going from
public to private.
---
test/web/common_api/common_api_test.exs | 26 ++++++++++++++++++++++++++
test/web/common_api/common_api_utils_test.exs | 12 ++++++++++--
2 files changed, 36 insertions(+), 2 deletions(-)
(limited to 'test')
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index 52e95397c..6014ffdac 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -335,6 +335,32 @@ defmodule Pleroma.Web.CommonAPITest do
end)
end
+ test "replying with a direct message will NOT auto-add the author of the reply to the recipient list" do
+ user = insert(:user)
+ other_user = insert(:user)
+ third_user = insert(:user)
+
+ {:ok, post} = CommonAPI.post(user, %{status: "I'm stupid"})
+
+ {:ok, open_answer} =
+ CommonAPI.post(other_user, %{status: "No ur smart", in_reply_to_status_id: post.id})
+
+ # The OP is implicitly added
+ assert user.ap_id in open_answer.recipients
+
+ {:ok, secret_answer} =
+ CommonAPI.post(other_user, %{
+ status: "lol, that guy really is stupid, right, @#{third_user.nickname}?",
+ in_reply_to_status_id: post.id,
+ visibility: "direct"
+ })
+
+ assert third_user.ap_id in secret_answer.recipients
+
+ # The OP is not added
+ refute user.ap_id in secret_answer.recipients
+ end
+
test "it allows to address a list" do
user = insert(:user)
{:ok, list} = Pleroma.List.create("foo", user)
diff --git a/test/web/common_api/common_api_utils_test.exs b/test/web/common_api/common_api_utils_test.exs
index 5708db6a4..d7d2d10d5 100644
--- a/test/web/common_api/common_api_utils_test.exs
+++ b/test/web/common_api/common_api_utils_test.exs
@@ -297,11 +297,10 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
{to, cc} = Utils.get_to_and_cc(user, mentions, activity, "private", nil)
- assert length(to) == 3
+ assert length(to) == 2
assert Enum.empty?(cc)
assert mentioned_user.ap_id in to
- assert third_user.ap_id in to
assert user.follower_address in to
end
@@ -327,6 +326,15 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
{to, cc} = Utils.get_to_and_cc(user, mentions, activity, "direct", nil)
+ assert length(to) == 1
+ assert Enum.empty?(cc)
+
+ assert mentioned_user.ap_id in to
+
+ {:ok, direct_activity} = CommonAPI.post(third_user, %{status: "uguu", visibility: "direct"})
+
+ {to, cc} = Utils.get_to_and_cc(user, mentions, direct_activity, "direct", nil)
+
assert length(to) == 2
assert Enum.empty?(cc)
--
cgit v1.2.3
From e42bc5f55732d42bf40ed9129ec737e654a911b8 Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 20 May 2020 15:44:37 +0200
Subject: Announcements: Handle through common pipeline.
---
test/fixtures/mastodon-note-object.json | 50 +++++++++++++++++++---
test/web/activity_pub/side_effects_test.exs | 25 +++++++++++
.../transmogrifier/announce_handling_test.exs | 20 +++++++--
test/web/common_api/common_api_test.exs | 13 +++---
4 files changed, 92 insertions(+), 16 deletions(-)
(limited to 'test')
diff --git a/test/fixtures/mastodon-note-object.json b/test/fixtures/mastodon-note-object.json
index 75bed9625..d28c7fbe9 100644
--- a/test/fixtures/mastodon-note-object.json
+++ b/test/fixtures/mastodon-note-object.json
@@ -1,9 +1,45 @@
-{"@context":["https://www.w3.org/ns/activitystreams","https://w3id.org/security/v1",{"manuallyApprovesFollowers":"as:manuallyApprovesFollowers","sensitive":"as:sensitive","movedTo":"as:movedTo","Hashtag":"as:Hashtag","ostatus":"http://ostatus.org#","atomUri":"ostatus:atomUri","inReplyToAtomUri":"ostatus:inReplyToAtomUri","conversation":"ostatus:conversation","toot":"http://joinmastodon.org/ns#","Emoji":"toot:Emoji"}],"id":"http://mastodon.example.org/users/admin/statuses/99541947525187367","type":"Note","summary":null,"content":"\u003cp\u003eyeah.\u003c/p\u003e","inReplyTo":null,"published":"2018-02-17T17:46:20Z","url":"http://mastodon.example.org/@admin/99541947525187367","attributedTo":"http://mastodon.example.org/users/admin","to":["https://www.w3.org/ns/activitystreams#Public"],"cc":["http://mastodon.example.org/users/admin/followers"],"sensitive":false,"atomUri":"http://mastodon.example.org/users/admin/statuses/99541947525187367","inReplyToAtomUri":null,"conversation":"tag:mastodon.example.org,2018-02-17:objectId=59:objectType=Conversation","tag":[],
- "attachment": [
+{
+ "@context" : [
+ "https://www.w3.org/ns/activitystreams",
+ "https://w3id.org/security/v1",
{
- "url": "http://mastodon.example.org/system/media_attachments/files/000/000/002/original/334ce029e7bfb920.jpg",
- "type": "Document",
- "name": null,
- "mediaType": "image/jpeg"
+ "Emoji" : "toot:Emoji",
+ "Hashtag" : "as:Hashtag",
+ "atomUri" : "ostatus:atomUri",
+ "conversation" : "ostatus:conversation",
+ "inReplyToAtomUri" : "ostatus:inReplyToAtomUri",
+ "manuallyApprovesFollowers" : "as:manuallyApprovesFollowers",
+ "movedTo" : "as:movedTo",
+ "ostatus" : "http://ostatus.org#",
+ "sensitive" : "as:sensitive",
+ "toot" : "http://joinmastodon.org/ns#"
}
- ]}
+ ],
+ "atomUri" : "http://mastodon.example.org/users/admin/statuses/99541947525187367",
+ "attachment" : [
+ {
+ "mediaType" : "image/jpeg",
+ "name" : null,
+ "type" : "Document",
+ "url" : "http://mastodon.example.org/system/media_attachments/files/000/000/002/original/334ce029e7bfb920.jpg"
+ }
+ ],
+ "attributedTo" : "http://mastodon.example.org/users/admin",
+ "cc" : [
+ "http://mastodon.example.org/users/admin/followers"
+ ],
+ "content" : "yeah.
",
+ "conversation" : "tag:mastodon.example.org,2018-02-17:objectId=59:objectType=Conversation",
+ "id" : "http://mastodon.example.org/users/admin/statuses/99541947525187367",
+ "inReplyTo" : null,
+ "inReplyToAtomUri" : null,
+ "published" : "2018-02-17T17:46:20Z",
+ "sensitive" : false,
+ "summary" : null,
+ "tag" : [],
+ "to" : [
+ "https://www.w3.org/ns/activitystreams#Public"
+ ],
+ "type" : "Note",
+ "url" : "http://mastodon.example.org/@admin/99541947525187367"
+}
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index a46254a05..5dede3957 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -289,4 +289,29 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
assert Repo.get_by(Notification, user_id: poster.id, activity_id: like.id)
end
end
+
+ describe "announce objects" do
+ setup do
+ poster = insert(:user)
+ user = insert(:user)
+ {:ok, post} = CommonAPI.post(poster, %{status: "hey"})
+
+ {:ok, announce_data, _meta} = Builder.announce(user, post.object)
+ {:ok, announce, _meta} = ActivityPub.persist(announce_data, local: true)
+
+ %{announce: announce, user: user, poster: poster}
+ end
+
+ test "add the announce to the original object", %{announce: announce, user: user} do
+ {:ok, announce, _} = SideEffects.handle(announce)
+ object = Object.get_by_ap_id(announce.data["object"])
+ assert object.data["announcement_count"] == 1
+ assert user.ap_id in object.data["announcements"]
+ end
+
+ test "creates a notification", %{announce: announce, poster: poster} do
+ {:ok, announce, _} = SideEffects.handle(announce)
+ assert Repo.get_by(Notification, user_id: poster.id, activity_id: announce.id)
+ end
+ end
end
diff --git a/test/web/activity_pub/transmogrifier/announce_handling_test.exs b/test/web/activity_pub/transmogrifier/announce_handling_test.exs
index 8a4af6546..50bcb307f 100644
--- a/test/web/activity_pub/transmogrifier/announce_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/announce_handling_test.exs
@@ -13,7 +13,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnnounceHandlingTest do
import Pleroma.Factory
test "it works for incoming honk announces" do
- _user = insert(:user, ap_id: "https://honktest/u/test", local: false)
+ user = insert(:user, ap_id: "https://honktest/u/test", local: false)
other_user = insert(:user)
{:ok, post} = CommonAPI.post(other_user, %{status: "bonkeronk"})
@@ -28,6 +28,11 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnnounceHandlingTest do
}
{:ok, %Activity{local: false}} = Transmogrifier.handle_incoming(announce)
+
+ object = Object.get_by_ap_id(post.data["object"])
+
+ assert length(object.data["announcements"]) == 1
+ assert user.ap_id in object.data["announcements"]
end
test "it works for incoming announces with actor being inlined (kroeg)" do
@@ -48,8 +53,15 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnnounceHandlingTest do
end
test "it works for incoming announces, fetching the announced object" do
- Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
- data = File.read!("test/fixtures/mastodon-announce.json") |> Poison.decode!()
+ data =
+ File.read!("test/fixtures/mastodon-announce.json")
+ |> Poison.decode!()
+ |> Map.put("object", "http://mastodon.example.org/users/admin/statuses/99541947525187367")
+
+ Tesla.Mock.mock(fn
+ %{method: :get} ->
+ %Tesla.Env{status: 200, body: File.read!("test/fixtures/mastodon-note-object.json")}
+ end)
_user = insert(:user, local: false, ap_id: data["actor"])
@@ -92,6 +104,8 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnnounceHandlingTest do
assert Activity.get_create_by_object_ap_id(data["object"]).id == activity.id
end
+ # Ignore inlined activities for now
+ @tag skip: true
test "it works for incoming announces with an inlined activity" do
data =
File.read!("test/fixtures/mastodon-announce-private.json")
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index 52e95397c..e68a6a7d2 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -416,7 +416,8 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
- {:ok, %Activity{}, _} = CommonAPI.repeat(activity.id, user)
+ {:ok, %Activity{} = announce_activity} = CommonAPI.repeat(activity.id, user)
+ assert Visibility.is_public?(announce_activity)
end
test "can't repeat a repeat" do
@@ -424,9 +425,9 @@ defmodule Pleroma.Web.CommonAPITest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
- {:ok, %Activity{} = announce, _} = CommonAPI.repeat(activity.id, other_user)
+ {:ok, %Activity{} = announce} = CommonAPI.repeat(activity.id, other_user)
- refute match?({:ok, %Activity{}, _}, CommonAPI.repeat(announce.id, user))
+ refute match?({:ok, %Activity{}}, CommonAPI.repeat(announce.id, user))
end
test "repeating a status privately" do
@@ -435,7 +436,7 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
- {:ok, %Activity{} = announce_activity, _} =
+ {:ok, %Activity{} = announce_activity} =
CommonAPI.repeat(activity.id, user, %{visibility: "private"})
assert Visibility.is_private?(announce_activity)
@@ -458,8 +459,8 @@ defmodule Pleroma.Web.CommonAPITest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{status: "cofe"})
- {:ok, %Activity{} = announce, object} = CommonAPI.repeat(activity.id, user)
- {:ok, ^announce, ^object} = CommonAPI.repeat(activity.id, user)
+ {:ok, %Activity{} = announce} = CommonAPI.repeat(activity.id, user)
+ {:ok, ^announce} = CommonAPI.repeat(activity.id, user)
end
test "favoriting a status twice returns ok, but without the like activity" do
--
cgit v1.2.3
From 39031f4860c91dee9418f69cc3b295cdfc9316bd Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 20 May 2020 16:36:55 +0200
Subject: Pipeline: Don't federate if federation is disabled.
---
test/web/activity_pub/pipeline_test.exs | 44 +++++++++++++++++++++++++++++++++
1 file changed, 44 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/pipeline_test.exs b/test/web/activity_pub/pipeline_test.exs
index f3c437498..26557720b 100644
--- a/test/web/activity_pub/pipeline_test.exs
+++ b/test/web/activity_pub/pipeline_test.exs
@@ -9,6 +9,11 @@ defmodule Pleroma.Web.ActivityPub.PipelineTest do
import Pleroma.Factory
describe "common_pipeline/2" do
+ setup do
+ clear_config([:instance, :federating], true)
+ :ok
+ end
+
test "it goes through validation, filtering, persisting, side effects and federation for local activities" do
activity = insert(:note_activity)
meta = [local: true]
@@ -83,5 +88,44 @@ defmodule Pleroma.Web.ActivityPub.PipelineTest do
assert_called(Pleroma.Web.ActivityPub.SideEffects.handle(activity, meta))
end
end
+
+ test "it goes through validation, filtering, persisting, side effects without federation for local activities if federation is deactivated" do
+ clear_config([:instance, :federating], false)
+
+ activity = insert(:note_activity)
+ meta = [local: true]
+
+ with_mocks([
+ {Pleroma.Web.ActivityPub.ObjectValidator, [], [validate: fn o, m -> {:ok, o, m} end]},
+ {
+ Pleroma.Web.ActivityPub.MRF,
+ [],
+ [filter: fn o -> {:ok, o} end]
+ },
+ {
+ Pleroma.Web.ActivityPub.ActivityPub,
+ [],
+ [persist: fn o, m -> {:ok, o, m} end]
+ },
+ {
+ Pleroma.Web.ActivityPub.SideEffects,
+ [],
+ [handle: fn o, m -> {:ok, o, m} end]
+ },
+ {
+ Pleroma.Web.Federator,
+ [],
+ []
+ }
+ ]) do
+ assert {:ok, ^activity, ^meta} =
+ Pleroma.Web.ActivityPub.Pipeline.common_pipeline(activity, meta)
+
+ assert_called(Pleroma.Web.ActivityPub.ObjectValidator.validate(activity, meta))
+ assert_called(Pleroma.Web.ActivityPub.MRF.filter(activity))
+ assert_called(Pleroma.Web.ActivityPub.ActivityPub.persist(activity, meta))
+ assert_called(Pleroma.Web.ActivityPub.SideEffects.handle(activity, meta))
+ end
+ end
end
end
--
cgit v1.2.3
From c96f425cb0fbac04b2ad5be2cff3805903bbd9b9 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Wed, 20 May 2020 21:16:40 +0300
Subject: fixed `mix pleroma.instance gen`
---
test/tasks/instance_test.exs | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/tasks/instance_test.exs b/test/tasks/instance_test.exs
index f6a4ba508..3b4c041d9 100644
--- a/test/tasks/instance_test.exs
+++ b/test/tasks/instance_test.exs
@@ -63,7 +63,7 @@ defmodule Pleroma.InstanceTest do
"--uploads-dir",
"test/uploads",
"--static-dir",
- "instance/static/"
+ "./test/../test/instance/static/"
])
end
@@ -83,6 +83,7 @@ defmodule Pleroma.InstanceTest do
assert generated_config =~ "configurable_from_database: true"
assert generated_config =~ "http: [ip: {127, 0, 0, 1}, port: 4000]"
assert File.read!(tmp_path() <> "setup.psql") == generated_setup_psql()
+ assert File.exists?(Path.expand("./test/instance/static/robots.txt"))
end
defp generated_setup_psql do
--
cgit v1.2.3
From b7fc61e17b995e3aa4e52f85b91d320a1cd1e106 Mon Sep 17 00:00:00 2001
From: eugenijm
Date: Sun, 12 Apr 2020 22:54:43 +0300
Subject: Added the ability to upload background, logo, default user avatar,
instance thumbnail, and the NSFW hiding image via AdminFE
---
test/user_test.exs | 12 ++++++++++++
test/workers/cron/new_users_digest_worker_test.exs | 1 +
2 files changed, 13 insertions(+)
(limited to 'test')
diff --git a/test/user_test.exs b/test/user_test.exs
index 863e0106c..ea192ad10 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -1777,4 +1777,16 @@ defmodule Pleroma.UserTest do
assert result.email_notifications["digest"] == false
end
end
+
+ test "avatar fallback" do
+ user = insert(:user)
+ assert User.avatar_url(user) =~ "/images/avi.png"
+
+ Pleroma.Config.put([:assets, :default_user_avatar], "avatar.png")
+
+ user = User.get_cached_by_nickname_or_id(user.nickname)
+ assert User.avatar_url(user) =~ "avatar.png"
+
+ assert User.avatar_url(user, no_default: true) == nil
+ end
end
diff --git a/test/workers/cron/new_users_digest_worker_test.exs b/test/workers/cron/new_users_digest_worker_test.exs
index 54cf0ca46..ee589bb55 100644
--- a/test/workers/cron/new_users_digest_worker_test.exs
+++ b/test/workers/cron/new_users_digest_worker_test.exs
@@ -28,6 +28,7 @@ defmodule Pleroma.Workers.Cron.NewUsersDigestWorkerTest do
assert email.html_body =~ user.nickname
assert email.html_body =~ user2.nickname
assert email.html_body =~ "cofe"
+ assert email.html_body =~ "#{Pleroma.Web.Endpoint.url()}/static/logo.png"
end
test "it doesn't fail when admin has no email" do
--
cgit v1.2.3
From 9bc5e18adeef2c68c5fae2435ed01555f1b29c93 Mon Sep 17 00:00:00 2001
From: Maksim Pechnikov
Date: Thu, 21 May 2020 08:06:57 +0300
Subject: rename mix task: `pleroma.user unsubscribe` -> `pleroma.user
deactivate`
---
test/tasks/user_test.exs | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/tasks/user_test.exs b/test/tasks/user_test.exs
index 4b3ab5a87..ab7637511 100644
--- a/test/tasks/user_test.exs
+++ b/test/tasks/user_test.exs
@@ -169,7 +169,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do
end
end
- describe "running unsubscribe" do
+ describe "running deactivate" do
test "user is unsubscribed" do
followed = insert(:user)
remote_followed = insert(:user, local: false)
@@ -178,7 +178,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do
User.follow(user, followed, :follow_accept)
User.follow(user, remote_followed, :follow_accept)
- Mix.Tasks.Pleroma.User.run(["unsubscribe", user.nickname])
+ Mix.Tasks.Pleroma.User.run(["deactivate", user.nickname])
assert_received {:mix_shell, :info, [message]}
assert message =~ "Deactivating"
@@ -192,8 +192,8 @@ defmodule Mix.Tasks.Pleroma.UserTest do
assert user.deactivated
end
- test "no user to unsubscribe" do
- Mix.Tasks.Pleroma.User.run(["unsubscribe", "nonexistent"])
+ test "no user to deactivate" do
+ Mix.Tasks.Pleroma.User.run(["deactivate", "nonexistent"])
assert_received {:mix_shell, :error, [message]}
assert message =~ "No user"
--
cgit v1.2.3
From 9de9760aa696657400c762d46dced273c3475be4 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Wed, 20 May 2020 18:00:41 +0400
Subject: Move status actions to AdminAPI.StatusController
---
test/web/admin_api/admin_api_controller_test.exs | 3864 --------------------
.../controllers/admin_api_controller_test.exs | 3707 +++++++++++++++++++
.../controllers/status_controller_test.exs | 185 +
3 files changed, 3892 insertions(+), 3864 deletions(-)
delete mode 100644 test/web/admin_api/admin_api_controller_test.exs
create mode 100644 test/web/admin_api/controllers/admin_api_controller_test.exs
create mode 100644 test/web/admin_api/controllers/status_controller_test.exs
(limited to 'test')
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
deleted file mode 100644
index 370d876d0..000000000
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ /dev/null
@@ -1,3864 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2020 Pleroma Authors
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
- use Pleroma.Web.ConnCase
- use Oban.Testing, repo: Pleroma.Repo
-
- import ExUnit.CaptureLog
- import Mock
- import Pleroma.Factory
-
- alias Pleroma.Activity
- alias Pleroma.Config
- alias Pleroma.ConfigDB
- alias Pleroma.HTML
- alias Pleroma.MFA
- alias Pleroma.ModerationLog
- alias Pleroma.Repo
- alias Pleroma.ReportNote
- alias Pleroma.Tests.ObanHelpers
- alias Pleroma.User
- alias Pleroma.UserInviteToken
- alias Pleroma.Web
- alias Pleroma.Web.ActivityPub.Relay
- alias Pleroma.Web.CommonAPI
- alias Pleroma.Web.MediaProxy
-
- setup_all do
- Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
-
- :ok
- end
-
- setup do
- admin = insert(:user, is_admin: true)
- token = insert(:oauth_admin_token, user: admin)
-
- conn =
- build_conn()
- |> assign(:user, admin)
- |> assign(:token, token)
-
- {:ok, %{admin: admin, token: token, conn: conn}}
- end
-
- describe "with [:auth, :enforce_oauth_admin_scope_usage]," do
- setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], true)
-
- test "GET /api/pleroma/admin/users/:nickname requires admin:read:accounts or broader scope",
- %{admin: admin} do
- user = insert(:user)
- url = "/api/pleroma/admin/users/#{user.nickname}"
-
- good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"])
- good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"])
- good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"])
-
- bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts"])
- bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"])
- bad_token3 = nil
-
- for good_token <- [good_token1, good_token2, good_token3] do
- conn =
- build_conn()
- |> assign(:user, admin)
- |> assign(:token, good_token)
- |> get(url)
-
- assert json_response(conn, 200)
- end
-
- for good_token <- [good_token1, good_token2, good_token3] do
- conn =
- build_conn()
- |> assign(:user, nil)
- |> assign(:token, good_token)
- |> get(url)
-
- assert json_response(conn, :forbidden)
- end
-
- for bad_token <- [bad_token1, bad_token2, bad_token3] do
- conn =
- build_conn()
- |> assign(:user, admin)
- |> assign(:token, bad_token)
- |> get(url)
-
- assert json_response(conn, :forbidden)
- end
- end
- end
-
- describe "unless [:auth, :enforce_oauth_admin_scope_usage]," do
- setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false)
-
- test "GET /api/pleroma/admin/users/:nickname requires " <>
- "read:accounts or admin:read:accounts or broader scope",
- %{admin: admin} do
- user = insert(:user)
- url = "/api/pleroma/admin/users/#{user.nickname}"
-
- good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"])
- good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"])
- good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"])
- good_token4 = insert(:oauth_token, user: admin, scopes: ["read:accounts"])
- good_token5 = insert(:oauth_token, user: admin, scopes: ["read"])
-
- good_tokens = [good_token1, good_token2, good_token3, good_token4, good_token5]
-
- bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts:partial"])
- bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"])
- bad_token3 = nil
-
- for good_token <- good_tokens do
- conn =
- build_conn()
- |> assign(:user, admin)
- |> assign(:token, good_token)
- |> get(url)
-
- assert json_response(conn, 200)
- end
-
- for good_token <- good_tokens do
- conn =
- build_conn()
- |> assign(:user, nil)
- |> assign(:token, good_token)
- |> get(url)
-
- assert json_response(conn, :forbidden)
- end
-
- for bad_token <- [bad_token1, bad_token2, bad_token3] do
- conn =
- build_conn()
- |> assign(:user, admin)
- |> assign(:token, bad_token)
- |> get(url)
-
- assert json_response(conn, :forbidden)
- end
- end
- end
-
- describe "DELETE /api/pleroma/admin/users" do
- test "single user", %{admin: admin, conn: conn} do
- user = insert(:user)
-
- with_mock Pleroma.Web.Federator,
- publish: fn _ -> nil end do
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> delete("/api/pleroma/admin/users?nickname=#{user.nickname}")
-
- ObanHelpers.perform_all()
-
- assert User.get_by_nickname(user.nickname).deactivated
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} deleted users: @#{user.nickname}"
-
- assert json_response(conn, 200) == [user.nickname]
-
- assert called(Pleroma.Web.Federator.publish(:_))
- end
- end
-
- test "multiple users", %{admin: admin, conn: conn} do
- user_one = insert(:user)
- user_two = insert(:user)
-
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> delete("/api/pleroma/admin/users", %{
- nicknames: [user_one.nickname, user_two.nickname]
- })
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} deleted users: @#{user_one.nickname}, @#{user_two.nickname}"
-
- response = json_response(conn, 200)
- assert response -- [user_one.nickname, user_two.nickname] == []
- end
- end
-
- describe "/api/pleroma/admin/users" do
- test "Create", %{conn: conn} do
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> post("/api/pleroma/admin/users", %{
- "users" => [
- %{
- "nickname" => "lain",
- "email" => "lain@example.org",
- "password" => "test"
- },
- %{
- "nickname" => "lain2",
- "email" => "lain2@example.org",
- "password" => "test"
- }
- ]
- })
-
- response = json_response(conn, 200) |> Enum.map(&Map.get(&1, "type"))
- assert response == ["success", "success"]
-
- log_entry = Repo.one(ModerationLog)
-
- assert ["lain", "lain2"] -- Enum.map(log_entry.data["subjects"], & &1["nickname"]) == []
- end
-
- test "Cannot create user with existing email", %{conn: conn} do
- user = insert(:user)
-
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> post("/api/pleroma/admin/users", %{
- "users" => [
- %{
- "nickname" => "lain",
- "email" => user.email,
- "password" => "test"
- }
- ]
- })
-
- assert json_response(conn, 409) == [
- %{
- "code" => 409,
- "data" => %{
- "email" => user.email,
- "nickname" => "lain"
- },
- "error" => "email has already been taken",
- "type" => "error"
- }
- ]
- end
-
- test "Cannot create user with existing nickname", %{conn: conn} do
- user = insert(:user)
-
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> post("/api/pleroma/admin/users", %{
- "users" => [
- %{
- "nickname" => user.nickname,
- "email" => "someuser@plerama.social",
- "password" => "test"
- }
- ]
- })
-
- assert json_response(conn, 409) == [
- %{
- "code" => 409,
- "data" => %{
- "email" => "someuser@plerama.social",
- "nickname" => user.nickname
- },
- "error" => "nickname has already been taken",
- "type" => "error"
- }
- ]
- end
-
- test "Multiple user creation works in transaction", %{conn: conn} do
- user = insert(:user)
-
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> post("/api/pleroma/admin/users", %{
- "users" => [
- %{
- "nickname" => "newuser",
- "email" => "newuser@pleroma.social",
- "password" => "test"
- },
- %{
- "nickname" => "lain",
- "email" => user.email,
- "password" => "test"
- }
- ]
- })
-
- assert json_response(conn, 409) == [
- %{
- "code" => 409,
- "data" => %{
- "email" => user.email,
- "nickname" => "lain"
- },
- "error" => "email has already been taken",
- "type" => "error"
- },
- %{
- "code" => 409,
- "data" => %{
- "email" => "newuser@pleroma.social",
- "nickname" => "newuser"
- },
- "error" => "",
- "type" => "error"
- }
- ]
-
- assert User.get_by_nickname("newuser") === nil
- end
- end
-
- describe "/api/pleroma/admin/users/:nickname" do
- test "Show", %{conn: conn} do
- user = insert(:user)
-
- conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}")
-
- expected = %{
- "deactivated" => false,
- "id" => to_string(user.id),
- "local" => true,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "tags" => [],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- }
-
- assert expected == json_response(conn, 200)
- end
-
- test "when the user doesn't exist", %{conn: conn} do
- user = build(:user)
-
- conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}")
-
- assert "Not found" == json_response(conn, 404)
- end
- end
-
- describe "/api/pleroma/admin/users/follow" do
- test "allows to force-follow another user", %{admin: admin, conn: conn} do
- user = insert(:user)
- follower = insert(:user)
-
- conn
- |> put_req_header("accept", "application/json")
- |> post("/api/pleroma/admin/users/follow", %{
- "follower" => follower.nickname,
- "followed" => user.nickname
- })
-
- user = User.get_cached_by_id(user.id)
- follower = User.get_cached_by_id(follower.id)
-
- assert User.following?(follower, user)
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} made @#{follower.nickname} follow @#{user.nickname}"
- end
- end
-
- describe "/api/pleroma/admin/users/unfollow" do
- test "allows to force-unfollow another user", %{admin: admin, conn: conn} do
- user = insert(:user)
- follower = insert(:user)
-
- User.follow(follower, user)
-
- conn
- |> put_req_header("accept", "application/json")
- |> post("/api/pleroma/admin/users/unfollow", %{
- "follower" => follower.nickname,
- "followed" => user.nickname
- })
-
- user = User.get_cached_by_id(user.id)
- follower = User.get_cached_by_id(follower.id)
-
- refute User.following?(follower, user)
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} made @#{follower.nickname} unfollow @#{user.nickname}"
- end
- end
-
- describe "PUT /api/pleroma/admin/users/tag" do
- setup %{conn: conn} do
- user1 = insert(:user, %{tags: ["x"]})
- user2 = insert(:user, %{tags: ["y"]})
- user3 = insert(:user, %{tags: ["unchanged"]})
-
- conn =
- conn
- |> 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,
- admin: admin,
- user1: user1,
- user2: user2
- } do
- assert json_response(conn, :no_content)
- assert User.get_cached_by_id(user1.id).tags == ["x", "foo", "bar"]
- assert User.get_cached_by_id(user2.id).tags == ["y", "foo", "bar"]
-
- log_entry = Repo.one(ModerationLog)
-
- users =
- [user1.nickname, user2.nickname]
- |> Enum.map(&"@#{&1}")
- |> Enum.join(", ")
-
- tags = ["foo", "bar"] |> Enum.join(", ")
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} added tags: #{tags} to users: #{users}"
- end
-
- test "it does not modify tags of not specified users", %{conn: conn, user3: user3} do
- assert json_response(conn, :no_content)
- assert User.get_cached_by_id(user3.id).tags == ["unchanged"]
- end
- end
-
- describe "DELETE /api/pleroma/admin/users/tag" do
- setup %{conn: conn} do
- user1 = insert(:user, %{tags: ["x"]})
- user2 = insert(:user, %{tags: ["y", "z"]})
- user3 = insert(:user, %{tags: ["unchanged"]})
-
- conn =
- conn
- |> 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,
- admin: admin,
- user1: user1,
- user2: user2
- } do
- assert json_response(conn, :no_content)
- assert User.get_cached_by_id(user1.id).tags == []
- assert User.get_cached_by_id(user2.id).tags == ["y"]
-
- log_entry = Repo.one(ModerationLog)
-
- users =
- [user1.nickname, user2.nickname]
- |> Enum.map(&"@#{&1}")
- |> Enum.join(", ")
-
- tags = ["x", "z"] |> Enum.join(", ")
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} removed tags: #{tags} from users: #{users}"
- end
-
- test "it does not modify tags of not specified users", %{conn: conn, user3: user3} do
- assert json_response(conn, :no_content)
- assert User.get_cached_by_id(user3.id).tags == ["unchanged"]
- end
- end
-
- describe "/api/pleroma/admin/users/:nickname/permission_group" do
- test "GET is giving user_info", %{admin: admin, conn: conn} do
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> get("/api/pleroma/admin/users/#{admin.nickname}/permission_group/")
-
- assert json_response(conn, 200) == %{
- "is_admin" => true,
- "is_moderator" => false
- }
- end
-
- test "/:right POST, can add to a permission group", %{admin: admin, conn: conn} do
- user = insert(:user)
-
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> post("/api/pleroma/admin/users/#{user.nickname}/permission_group/admin")
-
- assert json_response(conn, 200) == %{
- "is_admin" => true
- }
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} made @#{user.nickname} admin"
- end
-
- test "/:right POST, can add to a permission group (multiple)", %{admin: admin, conn: conn} do
- user_one = insert(:user)
- user_two = insert(:user)
-
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> post("/api/pleroma/admin/users/permission_group/admin", %{
- nicknames: [user_one.nickname, user_two.nickname]
- })
-
- assert json_response(conn, 200) == %{"is_admin" => true}
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} made @#{user_one.nickname}, @#{user_two.nickname} admin"
- end
-
- test "/:right DELETE, can remove from a permission group", %{admin: admin, conn: conn} do
- user = insert(:user, is_admin: true)
-
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> delete("/api/pleroma/admin/users/#{user.nickname}/permission_group/admin")
-
- assert json_response(conn, 200) == %{"is_admin" => false}
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} revoked admin role from @#{user.nickname}"
- end
-
- test "/:right DELETE, can remove from a permission group (multiple)", %{
- admin: admin,
- conn: conn
- } do
- user_one = insert(:user, is_admin: true)
- user_two = insert(:user, is_admin: true)
-
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> delete("/api/pleroma/admin/users/permission_group/admin", %{
- nicknames: [user_one.nickname, user_two.nickname]
- })
-
- assert json_response(conn, 200) == %{"is_admin" => false}
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} revoked admin role from @#{user_one.nickname}, @#{
- user_two.nickname
- }"
- end
- end
-
- describe "POST /api/pleroma/admin/email_invite, with valid config" do
- setup do: clear_config([:instance, :registrations_open], false)
- setup do: clear_config([:instance, :invites_enabled], true)
-
- test "sends invitation and returns 204", %{admin: admin, conn: conn} do
- recipient_email = "foo@bar.com"
- recipient_name = "J. D."
-
- conn =
- post(
- conn,
- "/api/pleroma/admin/users/email_invite?email=#{recipient_email}&name=#{recipient_name}"
- )
-
- assert json_response(conn, :no_content)
-
- token_record = List.last(Repo.all(Pleroma.UserInviteToken))
- assert token_record
- refute token_record.used
-
- notify_email = Config.get([:instance, :notify_email])
- instance_name = Config.get([:instance, :name])
-
- email =
- Pleroma.Emails.UserEmail.user_invitation_email(
- admin,
- token_record,
- recipient_email,
- recipient_name
- )
-
- Swoosh.TestAssertions.assert_email_sent(
- from: {instance_name, notify_email},
- to: {recipient_name, recipient_email},
- html_body: email.html_body
- )
- end
-
- test "it returns 403 if requested by a non-admin" do
- non_admin_user = insert(:user)
- token = insert(:oauth_token, user: non_admin_user)
-
- conn =
- build_conn()
- |> assign(:user, non_admin_user)
- |> assign(:token, token)
- |> post("/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
-
- assert json_response(conn, :forbidden)
- end
-
- test "email with +", %{conn: conn, admin: admin} do
- recipient_email = "foo+bar@baz.com"
-
- conn
- |> put_req_header("content-type", "application/json;charset=utf-8")
- |> post("/api/pleroma/admin/users/email_invite", %{email: recipient_email})
- |> json_response(:no_content)
-
- token_record =
- Pleroma.UserInviteToken
- |> Repo.all()
- |> List.last()
-
- assert token_record
- refute token_record.used
-
- notify_email = Config.get([:instance, :notify_email])
- instance_name = Config.get([:instance, :name])
-
- email =
- Pleroma.Emails.UserEmail.user_invitation_email(
- admin,
- token_record,
- recipient_email
- )
-
- Swoosh.TestAssertions.assert_email_sent(
- from: {instance_name, notify_email},
- to: recipient_email,
- html_body: email.html_body
- )
- end
- end
-
- describe "POST /api/pleroma/admin/users/email_invite, with invalid config" do
- setup do: clear_config([:instance, :registrations_open])
- setup do: clear_config([:instance, :invites_enabled])
-
- test "it returns 500 if `invites_enabled` is not enabled", %{conn: conn} do
- Config.put([:instance, :registrations_open], false)
- Config.put([:instance, :invites_enabled], false)
-
- conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
-
- assert json_response(conn, :bad_request) ==
- "To send invites you need to set the `invites_enabled` option to true."
- end
-
- test "it returns 500 if `registrations_open` is enabled", %{conn: conn} do
- Config.put([:instance, :registrations_open], true)
- Config.put([:instance, :invites_enabled], true)
-
- conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
-
- assert json_response(conn, :bad_request) ==
- "To send invites you need to set the `registrations_open` option to false."
- end
- end
-
- test "/api/pleroma/admin/users/:nickname/password_reset", %{conn: conn} do
- user = insert(:user)
-
- conn =
- conn
- |> put_req_header("accept", "application/json")
- |> get("/api/pleroma/admin/users/#{user.nickname}/password_reset")
-
- resp = json_response(conn, 200)
-
- assert Regex.match?(~r/(http:\/\/|https:\/\/)/, resp["link"])
- end
-
- describe "GET /api/pleroma/admin/users" do
- test "renders users array for the first page", %{conn: conn, admin: admin} do
- user = insert(:user, local: false, tags: ["foo", "bar"])
- conn = get(conn, "/api/pleroma/admin/users?page=1")
-
- users =
- [
- %{
- "deactivated" => admin.deactivated,
- "id" => admin.id,
- "nickname" => admin.nickname,
- "roles" => %{"admin" => true, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(admin) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(admin.name || admin.nickname),
- "confirmation_pending" => false
- },
- %{
- "deactivated" => user.deactivated,
- "id" => user.id,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => false,
- "tags" => ["foo", "bar"],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- }
- ]
- |> Enum.sort_by(& &1["nickname"])
-
- assert json_response(conn, 200) == %{
- "count" => 2,
- "page_size" => 50,
- "users" => users
- }
- end
-
- test "pagination works correctly with service users", %{conn: conn} do
- service1 = insert(:user, ap_id: Web.base_url() <> "/relay")
- service2 = insert(:user, ap_id: Web.base_url() <> "/internal/fetch")
- insert_list(25, :user)
-
- assert %{"count" => 26, "page_size" => 10, "users" => users1} =
- conn
- |> get("/api/pleroma/admin/users?page=1&filters=", %{page_size: "10"})
- |> json_response(200)
-
- assert Enum.count(users1) == 10
- assert service1 not in [users1]
- assert service2 not in [users1]
-
- assert %{"count" => 26, "page_size" => 10, "users" => users2} =
- conn
- |> get("/api/pleroma/admin/users?page=2&filters=", %{page_size: "10"})
- |> json_response(200)
-
- assert Enum.count(users2) == 10
- assert service1 not in [users2]
- assert service2 not in [users2]
-
- assert %{"count" => 26, "page_size" => 10, "users" => users3} =
- conn
- |> get("/api/pleroma/admin/users?page=3&filters=", %{page_size: "10"})
- |> json_response(200)
-
- assert Enum.count(users3) == 6
- assert service1 not in [users3]
- assert service2 not in [users3]
- end
-
- test "renders empty array for the second page", %{conn: conn} do
- insert(:user)
-
- conn = get(conn, "/api/pleroma/admin/users?page=2")
-
- assert json_response(conn, 200) == %{
- "count" => 2,
- "page_size" => 50,
- "users" => []
- }
- end
-
- test "regular search", %{conn: conn} do
- user = insert(:user, nickname: "bob")
-
- conn = get(conn, "/api/pleroma/admin/users?query=bo")
-
- assert json_response(conn, 200) == %{
- "count" => 1,
- "page_size" => 50,
- "users" => [
- %{
- "deactivated" => user.deactivated,
- "id" => user.id,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- }
- ]
- }
- end
-
- test "search by domain", %{conn: conn} do
- user = insert(:user, nickname: "nickname@domain.com")
- insert(:user)
-
- conn = get(conn, "/api/pleroma/admin/users?query=domain.com")
-
- assert json_response(conn, 200) == %{
- "count" => 1,
- "page_size" => 50,
- "users" => [
- %{
- "deactivated" => user.deactivated,
- "id" => user.id,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- }
- ]
- }
- end
-
- test "search by full nickname", %{conn: conn} do
- user = insert(:user, nickname: "nickname@domain.com")
- insert(:user)
-
- conn = get(conn, "/api/pleroma/admin/users?query=nickname@domain.com")
-
- assert json_response(conn, 200) == %{
- "count" => 1,
- "page_size" => 50,
- "users" => [
- %{
- "deactivated" => user.deactivated,
- "id" => user.id,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- }
- ]
- }
- end
-
- test "search by display name", %{conn: conn} do
- user = insert(:user, name: "Display name")
- insert(:user)
-
- conn = get(conn, "/api/pleroma/admin/users?name=display")
-
- assert json_response(conn, 200) == %{
- "count" => 1,
- "page_size" => 50,
- "users" => [
- %{
- "deactivated" => user.deactivated,
- "id" => user.id,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- }
- ]
- }
- end
-
- test "search by email", %{conn: conn} do
- user = insert(:user, email: "email@example.com")
- insert(:user)
-
- conn = get(conn, "/api/pleroma/admin/users?email=email@example.com")
-
- assert json_response(conn, 200) == %{
- "count" => 1,
- "page_size" => 50,
- "users" => [
- %{
- "deactivated" => user.deactivated,
- "id" => user.id,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- }
- ]
- }
- end
-
- test "regular search with page size", %{conn: conn} do
- user = insert(:user, nickname: "aalice")
- user2 = insert(:user, nickname: "alice")
-
- conn1 = get(conn, "/api/pleroma/admin/users?query=a&page_size=1&page=1")
-
- assert json_response(conn1, 200) == %{
- "count" => 2,
- "page_size" => 1,
- "users" => [
- %{
- "deactivated" => user.deactivated,
- "id" => user.id,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- }
- ]
- }
-
- conn2 = get(conn, "/api/pleroma/admin/users?query=a&page_size=1&page=2")
-
- assert json_response(conn2, 200) == %{
- "count" => 2,
- "page_size" => 1,
- "users" => [
- %{
- "deactivated" => user2.deactivated,
- "id" => user2.id,
- "nickname" => user2.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(user2) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user2.name || user2.nickname),
- "confirmation_pending" => false
- }
- ]
- }
- end
-
- test "only local users" do
- admin = insert(:user, is_admin: true, nickname: "john")
- token = insert(:oauth_admin_token, user: admin)
- user = insert(:user, nickname: "bob")
-
- insert(:user, nickname: "bobb", local: false)
-
- conn =
- build_conn()
- |> assign(:user, admin)
- |> assign(:token, token)
- |> get("/api/pleroma/admin/users?query=bo&filters=local")
-
- assert json_response(conn, 200) == %{
- "count" => 1,
- "page_size" => 50,
- "users" => [
- %{
- "deactivated" => user.deactivated,
- "id" => user.id,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- }
- ]
- }
- end
-
- test "only local users with no query", %{conn: conn, admin: old_admin} do
- admin = insert(:user, is_admin: true, nickname: "john")
- user = insert(:user, nickname: "bob")
-
- insert(:user, nickname: "bobb", local: false)
-
- conn = get(conn, "/api/pleroma/admin/users?filters=local")
-
- users =
- [
- %{
- "deactivated" => user.deactivated,
- "id" => user.id,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- },
- %{
- "deactivated" => admin.deactivated,
- "id" => admin.id,
- "nickname" => admin.nickname,
- "roles" => %{"admin" => true, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(admin) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(admin.name || admin.nickname),
- "confirmation_pending" => false
- },
- %{
- "deactivated" => false,
- "id" => old_admin.id,
- "local" => true,
- "nickname" => old_admin.nickname,
- "roles" => %{"admin" => true, "moderator" => false},
- "tags" => [],
- "avatar" => User.avatar_url(old_admin) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(old_admin.name || old_admin.nickname),
- "confirmation_pending" => false
- }
- ]
- |> Enum.sort_by(& &1["nickname"])
-
- assert json_response(conn, 200) == %{
- "count" => 3,
- "page_size" => 50,
- "users" => users
- }
- end
-
- test "load only admins", %{conn: conn, admin: admin} do
- second_admin = insert(:user, is_admin: true)
- insert(:user)
- insert(:user)
-
- conn = get(conn, "/api/pleroma/admin/users?filters=is_admin")
-
- users =
- [
- %{
- "deactivated" => false,
- "id" => admin.id,
- "nickname" => admin.nickname,
- "roles" => %{"admin" => true, "moderator" => false},
- "local" => admin.local,
- "tags" => [],
- "avatar" => User.avatar_url(admin) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(admin.name || admin.nickname),
- "confirmation_pending" => false
- },
- %{
- "deactivated" => false,
- "id" => second_admin.id,
- "nickname" => second_admin.nickname,
- "roles" => %{"admin" => true, "moderator" => false},
- "local" => second_admin.local,
- "tags" => [],
- "avatar" => User.avatar_url(second_admin) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(second_admin.name || second_admin.nickname),
- "confirmation_pending" => false
- }
- ]
- |> Enum.sort_by(& &1["nickname"])
-
- assert json_response(conn, 200) == %{
- "count" => 2,
- "page_size" => 50,
- "users" => users
- }
- end
-
- test "load only moderators", %{conn: conn} do
- moderator = insert(:user, is_moderator: true)
- insert(:user)
- insert(:user)
-
- conn = get(conn, "/api/pleroma/admin/users?filters=is_moderator")
-
- assert json_response(conn, 200) == %{
- "count" => 1,
- "page_size" => 50,
- "users" => [
- %{
- "deactivated" => false,
- "id" => moderator.id,
- "nickname" => moderator.nickname,
- "roles" => %{"admin" => false, "moderator" => true},
- "local" => moderator.local,
- "tags" => [],
- "avatar" => User.avatar_url(moderator) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(moderator.name || moderator.nickname),
- "confirmation_pending" => false
- }
- ]
- }
- end
-
- test "load users with tags list", %{conn: conn} do
- user1 = insert(:user, tags: ["first"])
- user2 = insert(:user, tags: ["second"])
- insert(:user)
- insert(:user)
-
- conn = get(conn, "/api/pleroma/admin/users?tags[]=first&tags[]=second")
-
- users =
- [
- %{
- "deactivated" => false,
- "id" => user1.id,
- "nickname" => user1.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => user1.local,
- "tags" => ["first"],
- "avatar" => User.avatar_url(user1) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user1.name || user1.nickname),
- "confirmation_pending" => false
- },
- %{
- "deactivated" => false,
- "id" => user2.id,
- "nickname" => user2.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => user2.local,
- "tags" => ["second"],
- "avatar" => User.avatar_url(user2) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user2.name || user2.nickname),
- "confirmation_pending" => false
- }
- ]
- |> Enum.sort_by(& &1["nickname"])
-
- assert json_response(conn, 200) == %{
- "count" => 2,
- "page_size" => 50,
- "users" => users
- }
- end
-
- test "it works with multiple filters" do
- admin = insert(:user, nickname: "john", is_admin: true)
- token = insert(:oauth_admin_token, user: admin)
- user = insert(:user, nickname: "bob", local: false, deactivated: true)
-
- insert(:user, nickname: "ken", local: true, deactivated: true)
- insert(:user, nickname: "bobb", local: false, deactivated: false)
-
- conn =
- build_conn()
- |> assign(:user, admin)
- |> assign(:token, token)
- |> get("/api/pleroma/admin/users?filters=deactivated,external")
-
- assert json_response(conn, 200) == %{
- "count" => 1,
- "page_size" => 50,
- "users" => [
- %{
- "deactivated" => user.deactivated,
- "id" => user.id,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => user.local,
- "tags" => [],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- }
- ]
- }
- end
-
- test "it omits relay user", %{admin: admin, conn: conn} do
- assert %User{} = Relay.get_actor()
-
- conn = get(conn, "/api/pleroma/admin/users")
-
- assert json_response(conn, 200) == %{
- "count" => 1,
- "page_size" => 50,
- "users" => [
- %{
- "deactivated" => admin.deactivated,
- "id" => admin.id,
- "nickname" => admin.nickname,
- "roles" => %{"admin" => true, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(admin) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(admin.name || admin.nickname),
- "confirmation_pending" => false
- }
- ]
- }
- end
- end
-
- test "PATCH /api/pleroma/admin/users/activate", %{admin: admin, conn: conn} do
- user_one = insert(:user, deactivated: true)
- user_two = insert(:user, deactivated: true)
-
- conn =
- patch(
- conn,
- "/api/pleroma/admin/users/activate",
- %{nicknames: [user_one.nickname, user_two.nickname]}
- )
-
- response = json_response(conn, 200)
- assert Enum.map(response["users"], & &1["deactivated"]) == [false, false]
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} activated users: @#{user_one.nickname}, @#{user_two.nickname}"
- end
-
- test "PATCH /api/pleroma/admin/users/deactivate", %{admin: admin, conn: conn} do
- user_one = insert(:user, deactivated: false)
- user_two = insert(:user, deactivated: false)
-
- conn =
- patch(
- conn,
- "/api/pleroma/admin/users/deactivate",
- %{nicknames: [user_one.nickname, user_two.nickname]}
- )
-
- response = json_response(conn, 200)
- assert Enum.map(response["users"], & &1["deactivated"]) == [true, true]
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} deactivated users: @#{user_one.nickname}, @#{user_two.nickname}"
- end
-
- test "PATCH /api/pleroma/admin/users/:nickname/toggle_activation", %{admin: admin, conn: conn} do
- user = insert(:user)
-
- conn = patch(conn, "/api/pleroma/admin/users/#{user.nickname}/toggle_activation")
-
- assert json_response(conn, 200) ==
- %{
- "deactivated" => !user.deactivated,
- "id" => user.id,
- "nickname" => user.nickname,
- "roles" => %{"admin" => false, "moderator" => false},
- "local" => true,
- "tags" => [],
- "avatar" => User.avatar_url(user) |> MediaProxy.url(),
- "display_name" => HTML.strip_tags(user.name || user.nickname),
- "confirmation_pending" => false
- }
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} deactivated users: @#{user.nickname}"
- end
-
- describe "PUT disable_mfa" do
- test "returns 200 and disable 2fa", %{conn: conn} do
- user =
- insert(:user,
- multi_factor_authentication_settings: %MFA.Settings{
- enabled: true,
- totp: %MFA.Settings.TOTP{secret: "otp_secret", confirmed: true}
- }
- )
-
- response =
- conn
- |> put("/api/pleroma/admin/users/disable_mfa", %{nickname: user.nickname})
- |> json_response(200)
-
- assert response == user.nickname
- mfa_settings = refresh_record(user).multi_factor_authentication_settings
-
- refute mfa_settings.enabled
- refute mfa_settings.totp.confirmed
- end
-
- test "returns 404 if user not found", %{conn: conn} do
- response =
- conn
- |> put("/api/pleroma/admin/users/disable_mfa", %{nickname: "nickname"})
- |> json_response(404)
-
- assert response == "Not found"
- end
- end
-
- describe "POST /api/pleroma/admin/users/invite_token" do
- test "without options", %{conn: conn} do
- conn = post(conn, "/api/pleroma/admin/users/invite_token")
-
- invite_json = json_response(conn, 200)
- invite = UserInviteToken.find_by_token!(invite_json["token"])
- refute invite.used
- refute invite.expires_at
- refute invite.max_use
- assert invite.invite_type == "one_time"
- end
-
- test "with expires_at", %{conn: conn} do
- conn =
- post(conn, "/api/pleroma/admin/users/invite_token", %{
- "expires_at" => Date.to_string(Date.utc_today())
- })
-
- invite_json = json_response(conn, 200)
- invite = UserInviteToken.find_by_token!(invite_json["token"])
-
- refute invite.used
- assert invite.expires_at == Date.utc_today()
- refute invite.max_use
- assert invite.invite_type == "date_limited"
- end
-
- test "with max_use", %{conn: conn} do
- conn = post(conn, "/api/pleroma/admin/users/invite_token", %{"max_use" => 150})
-
- invite_json = json_response(conn, 200)
- invite = UserInviteToken.find_by_token!(invite_json["token"])
- refute invite.used
- refute invite.expires_at
- assert invite.max_use == 150
- assert invite.invite_type == "reusable"
- end
-
- test "with max use and expires_at", %{conn: conn} do
- conn =
- post(conn, "/api/pleroma/admin/users/invite_token", %{
- "max_use" => 150,
- "expires_at" => Date.to_string(Date.utc_today())
- })
-
- invite_json = json_response(conn, 200)
- invite = UserInviteToken.find_by_token!(invite_json["token"])
- refute invite.used
- assert invite.expires_at == Date.utc_today()
- assert invite.max_use == 150
- assert invite.invite_type == "reusable_date_limited"
- end
- end
-
- describe "GET /api/pleroma/admin/users/invites" do
- test "no invites", %{conn: conn} do
- conn = get(conn, "/api/pleroma/admin/users/invites")
-
- assert json_response(conn, 200) == %{"invites" => []}
- end
-
- test "with invite", %{conn: conn} do
- {:ok, invite} = UserInviteToken.create_invite()
-
- conn = get(conn, "/api/pleroma/admin/users/invites")
-
- assert json_response(conn, 200) == %{
- "invites" => [
- %{
- "expires_at" => nil,
- "id" => invite.id,
- "invite_type" => "one_time",
- "max_use" => nil,
- "token" => invite.token,
- "used" => false,
- "uses" => 0
- }
- ]
- }
- end
- end
-
- describe "POST /api/pleroma/admin/users/revoke_invite" do
- test "with token", %{conn: conn} do
- {:ok, invite} = UserInviteToken.create_invite()
-
- conn = post(conn, "/api/pleroma/admin/users/revoke_invite", %{"token" => invite.token})
-
- assert json_response(conn, 200) == %{
- "expires_at" => nil,
- "id" => invite.id,
- "invite_type" => "one_time",
- "max_use" => nil,
- "token" => invite.token,
- "used" => true,
- "uses" => 0
- }
- end
-
- test "with invalid token", %{conn: conn} do
- conn = post(conn, "/api/pleroma/admin/users/revoke_invite", %{"token" => "foo"})
-
- assert json_response(conn, :not_found) == "Not found"
- end
- end
-
- describe "GET /api/pleroma/admin/reports/:id" do
- test "returns report by its id", %{conn: conn} do
- [reporter, target_user] = insert_pair(:user)
- activity = insert(:note_activity, user: target_user)
-
- {:ok, %{id: report_id}} =
- CommonAPI.report(reporter, %{
- account_id: target_user.id,
- comment: "I feel offended",
- status_ids: [activity.id]
- })
-
- response =
- conn
- |> get("/api/pleroma/admin/reports/#{report_id}")
- |> json_response(:ok)
-
- assert response["id"] == report_id
- end
-
- test "returns 404 when report id is invalid", %{conn: conn} do
- conn = get(conn, "/api/pleroma/admin/reports/test")
-
- assert json_response(conn, :not_found) == "Not found"
- end
- end
-
- describe "PATCH /api/pleroma/admin/reports" do
- setup do
- [reporter, target_user] = insert_pair(:user)
- activity = insert(:note_activity, user: target_user)
-
- {:ok, %{id: report_id}} =
- CommonAPI.report(reporter, %{
- account_id: target_user.id,
- comment: "I feel offended",
- status_ids: [activity.id]
- })
-
- {:ok, %{id: second_report_id}} =
- CommonAPI.report(reporter, %{
- account_id: target_user.id,
- comment: "I feel very offended",
- status_ids: [activity.id]
- })
-
- %{
- id: report_id,
- second_report_id: second_report_id
- }
- end
-
- test "requires admin:write:reports scope", %{conn: conn, id: id, admin: admin} do
- read_token = insert(:oauth_token, user: admin, scopes: ["admin:read"])
- write_token = insert(:oauth_token, user: admin, scopes: ["admin:write:reports"])
-
- response =
- conn
- |> assign(:token, read_token)
- |> patch("/api/pleroma/admin/reports", %{
- "reports" => [%{"state" => "resolved", "id" => id}]
- })
- |> json_response(403)
-
- assert response == %{
- "error" => "Insufficient permissions: admin:write:reports."
- }
-
- conn
- |> assign(:token, write_token)
- |> patch("/api/pleroma/admin/reports", %{
- "reports" => [%{"state" => "resolved", "id" => id}]
- })
- |> json_response(:no_content)
- end
-
- test "mark report as resolved", %{conn: conn, id: id, admin: admin} do
- conn
- |> patch("/api/pleroma/admin/reports", %{
- "reports" => [
- %{"state" => "resolved", "id" => id}
- ]
- })
- |> json_response(:no_content)
-
- activity = Activity.get_by_id(id)
- assert activity.data["state"] == "resolved"
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} updated report ##{id} with 'resolved' state"
- end
-
- test "closes report", %{conn: conn, id: id, admin: admin} do
- conn
- |> patch("/api/pleroma/admin/reports", %{
- "reports" => [
- %{"state" => "closed", "id" => id}
- ]
- })
- |> json_response(:no_content)
-
- activity = Activity.get_by_id(id)
- assert activity.data["state"] == "closed"
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} updated report ##{id} with 'closed' state"
- end
-
- test "returns 400 when state is unknown", %{conn: conn, id: id} do
- conn =
- conn
- |> patch("/api/pleroma/admin/reports", %{
- "reports" => [
- %{"state" => "test", "id" => id}
- ]
- })
-
- assert hd(json_response(conn, :bad_request))["error"] == "Unsupported state"
- end
-
- test "returns 404 when report is not exist", %{conn: conn} do
- conn =
- conn
- |> patch("/api/pleroma/admin/reports", %{
- "reports" => [
- %{"state" => "closed", "id" => "test"}
- ]
- })
-
- assert hd(json_response(conn, :bad_request))["error"] == "not_found"
- end
-
- test "updates state of multiple reports", %{
- conn: conn,
- id: id,
- admin: admin,
- second_report_id: second_report_id
- } do
- conn
- |> patch("/api/pleroma/admin/reports", %{
- "reports" => [
- %{"state" => "resolved", "id" => id},
- %{"state" => "closed", "id" => second_report_id}
- ]
- })
- |> json_response(:no_content)
-
- activity = Activity.get_by_id(id)
- second_activity = Activity.get_by_id(second_report_id)
- assert activity.data["state"] == "resolved"
- assert second_activity.data["state"] == "closed"
-
- [first_log_entry, second_log_entry] = Repo.all(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(first_log_entry) ==
- "@#{admin.nickname} updated report ##{id} with 'resolved' state"
-
- assert ModerationLog.get_log_entry_message(second_log_entry) ==
- "@#{admin.nickname} updated report ##{second_report_id} with 'closed' state"
- end
- end
-
- describe "GET /api/pleroma/admin/reports" do
- test "returns empty response when no reports created", %{conn: conn} do
- response =
- conn
- |> get("/api/pleroma/admin/reports")
- |> json_response(:ok)
-
- assert Enum.empty?(response["reports"])
- assert response["total"] == 0
- end
-
- test "returns reports", %{conn: conn} do
- [reporter, target_user] = insert_pair(:user)
- activity = insert(:note_activity, user: target_user)
-
- {:ok, %{id: report_id}} =
- CommonAPI.report(reporter, %{
- account_id: target_user.id,
- comment: "I feel offended",
- status_ids: [activity.id]
- })
-
- response =
- conn
- |> get("/api/pleroma/admin/reports")
- |> json_response(:ok)
-
- [report] = response["reports"]
-
- assert length(response["reports"]) == 1
- assert report["id"] == report_id
-
- assert response["total"] == 1
- end
-
- test "returns reports with specified state", %{conn: conn} do
- [reporter, target_user] = insert_pair(:user)
- activity = insert(:note_activity, user: target_user)
-
- {:ok, %{id: first_report_id}} =
- CommonAPI.report(reporter, %{
- account_id: target_user.id,
- comment: "I feel offended",
- status_ids: [activity.id]
- })
-
- {:ok, %{id: second_report_id}} =
- CommonAPI.report(reporter, %{
- account_id: target_user.id,
- comment: "I don't like this user"
- })
-
- CommonAPI.update_report_state(second_report_id, "closed")
-
- response =
- conn
- |> get("/api/pleroma/admin/reports", %{
- "state" => "open"
- })
- |> json_response(:ok)
-
- [open_report] = response["reports"]
-
- assert length(response["reports"]) == 1
- assert open_report["id"] == first_report_id
-
- assert response["total"] == 1
-
- response =
- conn
- |> get("/api/pleroma/admin/reports", %{
- "state" => "closed"
- })
- |> json_response(:ok)
-
- [closed_report] = response["reports"]
-
- assert length(response["reports"]) == 1
- assert closed_report["id"] == second_report_id
-
- assert response["total"] == 1
-
- response =
- conn
- |> get("/api/pleroma/admin/reports", %{
- "state" => "resolved"
- })
- |> json_response(:ok)
-
- assert Enum.empty?(response["reports"])
- assert response["total"] == 0
- end
-
- test "returns 403 when requested by a non-admin" do
- user = insert(:user)
- token = insert(:oauth_token, user: user)
-
- conn =
- build_conn()
- |> assign(:user, user)
- |> assign(:token, token)
- |> get("/api/pleroma/admin/reports")
-
- assert json_response(conn, :forbidden) ==
- %{"error" => "User is not an admin or OAuth admin scope is not granted."}
- end
-
- test "returns 403 when requested by anonymous" do
- conn = get(build_conn(), "/api/pleroma/admin/reports")
-
- assert json_response(conn, :forbidden) == %{"error" => "Invalid credentials."}
- end
- end
-
- describe "GET /api/pleroma/admin/statuses/:id" do
- test "not found", %{conn: conn} do
- assert conn
- |> get("/api/pleroma/admin/statuses/not_found")
- |> json_response(:not_found)
- end
-
- test "shows activity", %{conn: conn} do
- activity = insert(:note_activity)
-
- response =
- conn
- |> get("/api/pleroma/admin/statuses/#{activity.id}")
- |> json_response(200)
-
- assert response["id"] == activity.id
- end
- end
-
- describe "PUT /api/pleroma/admin/statuses/:id" do
- setup do
- activity = insert(:note_activity)
-
- %{id: activity.id}
- end
-
- test "toggle sensitive flag", %{conn: conn, id: id, admin: admin} do
- response =
- conn
- |> put("/api/pleroma/admin/statuses/#{id}", %{"sensitive" => "true"})
- |> json_response(:ok)
-
- assert response["sensitive"]
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} updated status ##{id}, set sensitive: 'true'"
-
- response =
- conn
- |> put("/api/pleroma/admin/statuses/#{id}", %{"sensitive" => "false"})
- |> json_response(:ok)
-
- refute response["sensitive"]
- end
-
- test "change visibility flag", %{conn: conn, id: id, admin: admin} do
- response =
- conn
- |> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "public"})
- |> json_response(:ok)
-
- assert response["visibility"] == "public"
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} updated status ##{id}, set visibility: 'public'"
-
- response =
- conn
- |> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "private"})
- |> json_response(:ok)
-
- assert response["visibility"] == "private"
-
- response =
- conn
- |> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "unlisted"})
- |> json_response(:ok)
-
- assert response["visibility"] == "unlisted"
- end
-
- test "returns 400 when visibility is unknown", %{conn: conn, id: id} do
- conn = put(conn, "/api/pleroma/admin/statuses/#{id}", %{visibility: "test"})
-
- assert json_response(conn, :bad_request) == "Unsupported visibility"
- end
- end
-
- describe "DELETE /api/pleroma/admin/statuses/:id" do
- setup do
- activity = insert(:note_activity)
-
- %{id: activity.id}
- end
-
- test "deletes status", %{conn: conn, id: id, admin: admin} do
- conn
- |> delete("/api/pleroma/admin/statuses/#{id}")
- |> json_response(:ok)
-
- refute Activity.get_by_id(id)
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} deleted status ##{id}"
- end
-
- test "returns 404 when the status does not exist", %{conn: conn} do
- conn = delete(conn, "/api/pleroma/admin/statuses/test")
-
- assert json_response(conn, :not_found) == "Not found"
- end
- end
-
- describe "GET /api/pleroma/admin/config" do
- setup do: clear_config(:configurable_from_database, true)
-
- test "when configuration from database is off", %{conn: conn} do
- Config.put(:configurable_from_database, false)
- conn = get(conn, "/api/pleroma/admin/config")
-
- assert json_response(conn, 400) ==
- "To use this endpoint you need to enable configuration from database."
- end
-
- test "with settings only in db", %{conn: conn} do
- config1 = insert(:config)
- config2 = insert(:config)
-
- conn = get(conn, "/api/pleroma/admin/config", %{"only_db" => true})
-
- %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => key1,
- "value" => _
- },
- %{
- "group" => ":pleroma",
- "key" => key2,
- "value" => _
- }
- ]
- } = json_response(conn, 200)
-
- assert key1 == config1.key
- assert key2 == config2.key
- end
-
- test "db is added to settings that are in db", %{conn: conn} do
- _config = insert(:config, key: ":instance", value: ConfigDB.to_binary(name: "Some name"))
-
- %{"configs" => configs} =
- conn
- |> get("/api/pleroma/admin/config")
- |> json_response(200)
-
- [instance_config] =
- Enum.filter(configs, fn %{"group" => group, "key" => key} ->
- group == ":pleroma" and key == ":instance"
- end)
-
- assert instance_config["db"] == [":name"]
- end
-
- test "merged default setting with db settings", %{conn: conn} do
- config1 = insert(:config)
- config2 = insert(:config)
-
- config3 =
- insert(:config,
- value: ConfigDB.to_binary(k1: :v1, k2: :v2)
- )
-
- %{"configs" => configs} =
- conn
- |> get("/api/pleroma/admin/config")
- |> json_response(200)
-
- assert length(configs) > 3
-
- received_configs =
- Enum.filter(configs, fn %{"group" => group, "key" => key} ->
- group == ":pleroma" and key in [config1.key, config2.key, config3.key]
- end)
-
- assert length(received_configs) == 3
-
- db_keys =
- config3.value
- |> ConfigDB.from_binary()
- |> Keyword.keys()
- |> ConfigDB.convert()
-
- Enum.each(received_configs, fn %{"value" => value, "db" => db} ->
- assert db in [[config1.key], [config2.key], db_keys]
-
- assert value in [
- ConfigDB.from_binary_with_convert(config1.value),
- ConfigDB.from_binary_with_convert(config2.value),
- ConfigDB.from_binary_with_convert(config3.value)
- ]
- end)
- end
-
- test "subkeys with full update right merge", %{conn: conn} do
- config1 =
- insert(:config,
- key: ":emoji",
- value: ConfigDB.to_binary(groups: [a: 1, b: 2], key: [a: 1])
- )
-
- config2 =
- insert(:config,
- key: ":assets",
- value: ConfigDB.to_binary(mascots: [a: 1, b: 2], key: [a: 1])
- )
-
- %{"configs" => configs} =
- conn
- |> get("/api/pleroma/admin/config")
- |> json_response(200)
-
- vals =
- Enum.filter(configs, fn %{"group" => group, "key" => key} ->
- group == ":pleroma" and key in [config1.key, config2.key]
- end)
-
- emoji = Enum.find(vals, fn %{"key" => key} -> key == ":emoji" end)
- assets = Enum.find(vals, fn %{"key" => key} -> key == ":assets" end)
-
- emoji_val = ConfigDB.transform_with_out_binary(emoji["value"])
- assets_val = ConfigDB.transform_with_out_binary(assets["value"])
-
- assert emoji_val[:groups] == [a: 1, b: 2]
- assert assets_val[:mascots] == [a: 1, b: 2]
- end
- end
-
- test "POST /api/pleroma/admin/config error", %{conn: conn} do
- conn = post(conn, "/api/pleroma/admin/config", %{"configs" => []})
-
- assert json_response(conn, 400) ==
- "To use this endpoint you need to enable configuration from database."
- end
-
- describe "POST /api/pleroma/admin/config" do
- setup do
- http = Application.get_env(:pleroma, :http)
-
- on_exit(fn ->
- Application.delete_env(:pleroma, :key1)
- Application.delete_env(:pleroma, :key2)
- Application.delete_env(:pleroma, :key3)
- Application.delete_env(:pleroma, :key4)
- Application.delete_env(:pleroma, :keyaa1)
- Application.delete_env(:pleroma, :keyaa2)
- Application.delete_env(:pleroma, Pleroma.Web.Endpoint.NotReal)
- Application.delete_env(:pleroma, Pleroma.Captcha.NotReal)
- Application.put_env(:pleroma, :http, http)
- Application.put_env(:tesla, :adapter, Tesla.Mock)
- Restarter.Pleroma.refresh()
- end)
- end
-
- setup do: clear_config(:configurable_from_database, true)
-
- @tag capture_log: true
- test "create new config setting in db", %{conn: conn} do
- ueberauth = Application.get_env(:ueberauth, Ueberauth)
- on_exit(fn -> Application.put_env(:ueberauth, Ueberauth, ueberauth) end)
-
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{group: ":pleroma", key: ":key1", value: "value1"},
- %{
- group: ":ueberauth",
- key: "Ueberauth",
- value: [%{"tuple" => [":consumer_secret", "aaaa"]}]
- },
- %{
- group: ":pleroma",
- key: ":key2",
- value: %{
- ":nested_1" => "nested_value1",
- ":nested_2" => [
- %{":nested_22" => "nested_value222"},
- %{":nested_33" => %{":nested_44" => "nested_444"}}
- ]
- }
- },
- %{
- group: ":pleroma",
- key: ":key3",
- value: [
- %{"nested_3" => ":nested_3", "nested_33" => "nested_33"},
- %{"nested_4" => true}
- ]
- },
- %{
- group: ":pleroma",
- key: ":key4",
- value: %{":nested_5" => ":upload", "endpoint" => "https://example.com"}
- },
- %{
- group: ":idna",
- key: ":key5",
- value: %{"tuple" => ["string", "Pleroma.Captcha.NotReal", []]}
- }
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":key1",
- "value" => "value1",
- "db" => [":key1"]
- },
- %{
- "group" => ":ueberauth",
- "key" => "Ueberauth",
- "value" => [%{"tuple" => [":consumer_secret", "aaaa"]}],
- "db" => [":consumer_secret"]
- },
- %{
- "group" => ":pleroma",
- "key" => ":key2",
- "value" => %{
- ":nested_1" => "nested_value1",
- ":nested_2" => [
- %{":nested_22" => "nested_value222"},
- %{":nested_33" => %{":nested_44" => "nested_444"}}
- ]
- },
- "db" => [":key2"]
- },
- %{
- "group" => ":pleroma",
- "key" => ":key3",
- "value" => [
- %{"nested_3" => ":nested_3", "nested_33" => "nested_33"},
- %{"nested_4" => true}
- ],
- "db" => [":key3"]
- },
- %{
- "group" => ":pleroma",
- "key" => ":key4",
- "value" => %{"endpoint" => "https://example.com", ":nested_5" => ":upload"},
- "db" => [":key4"]
- },
- %{
- "group" => ":idna",
- "key" => ":key5",
- "value" => %{"tuple" => ["string", "Pleroma.Captcha.NotReal", []]},
- "db" => [":key5"]
- }
- ]
- }
-
- assert Application.get_env(:pleroma, :key1) == "value1"
-
- assert Application.get_env(:pleroma, :key2) == %{
- nested_1: "nested_value1",
- nested_2: [
- %{nested_22: "nested_value222"},
- %{nested_33: %{nested_44: "nested_444"}}
- ]
- }
-
- assert Application.get_env(:pleroma, :key3) == [
- %{"nested_3" => :nested_3, "nested_33" => "nested_33"},
- %{"nested_4" => true}
- ]
-
- assert Application.get_env(:pleroma, :key4) == %{
- "endpoint" => "https://example.com",
- nested_5: :upload
- }
-
- assert Application.get_env(:idna, :key5) == {"string", Pleroma.Captcha.NotReal, []}
- end
-
- test "save configs setting without explicit key", %{conn: conn} do
- level = Application.get_env(:quack, :level)
- meta = Application.get_env(:quack, :meta)
- webhook_url = Application.get_env(:quack, :webhook_url)
-
- on_exit(fn ->
- Application.put_env(:quack, :level, level)
- Application.put_env(:quack, :meta, meta)
- Application.put_env(:quack, :webhook_url, webhook_url)
- end)
-
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- group: ":quack",
- key: ":level",
- value: ":info"
- },
- %{
- group: ":quack",
- key: ":meta",
- value: [":none"]
- },
- %{
- group: ":quack",
- key: ":webhook_url",
- value: "https://hooks.slack.com/services/KEY"
- }
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":quack",
- "key" => ":level",
- "value" => ":info",
- "db" => [":level"]
- },
- %{
- "group" => ":quack",
- "key" => ":meta",
- "value" => [":none"],
- "db" => [":meta"]
- },
- %{
- "group" => ":quack",
- "key" => ":webhook_url",
- "value" => "https://hooks.slack.com/services/KEY",
- "db" => [":webhook_url"]
- }
- ]
- }
-
- assert Application.get_env(:quack, :level) == :info
- assert Application.get_env(:quack, :meta) == [:none]
- assert Application.get_env(:quack, :webhook_url) == "https://hooks.slack.com/services/KEY"
- end
-
- test "saving config with partial update", %{conn: conn} do
- config = insert(:config, key: ":key1", value: :erlang.term_to_binary(key1: 1, key2: 2))
-
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{group: config.group, key: config.key, value: [%{"tuple" => [":key3", 3]}]}
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":key1",
- "value" => [
- %{"tuple" => [":key1", 1]},
- %{"tuple" => [":key2", 2]},
- %{"tuple" => [":key3", 3]}
- ],
- "db" => [":key1", ":key2", ":key3"]
- }
- ]
- }
- end
-
- test "saving config which need pleroma reboot", %{conn: conn} do
- chat = Config.get(:chat)
- on_exit(fn -> Config.put(:chat, chat) end)
-
- assert post(
- conn,
- "/api/pleroma/admin/config",
- %{
- configs: [
- %{group: ":pleroma", key: ":chat", value: [%{"tuple" => [":enabled", true]}]}
- ]
- }
- )
- |> json_response(200) == %{
- "configs" => [
- %{
- "db" => [":enabled"],
- "group" => ":pleroma",
- "key" => ":chat",
- "value" => [%{"tuple" => [":enabled", true]}]
- }
- ],
- "need_reboot" => true
- }
-
- configs =
- conn
- |> get("/api/pleroma/admin/config")
- |> json_response(200)
-
- assert configs["need_reboot"]
-
- capture_log(fn ->
- assert conn |> get("/api/pleroma/admin/restart") |> json_response(200) == %{}
- end) =~ "pleroma restarted"
-
- configs =
- conn
- |> get("/api/pleroma/admin/config")
- |> json_response(200)
-
- assert configs["need_reboot"] == false
- end
-
- test "update setting which need reboot, don't change reboot flag until reboot", %{conn: conn} do
- chat = Config.get(:chat)
- on_exit(fn -> Config.put(:chat, chat) end)
-
- assert post(
- conn,
- "/api/pleroma/admin/config",
- %{
- configs: [
- %{group: ":pleroma", key: ":chat", value: [%{"tuple" => [":enabled", true]}]}
- ]
- }
- )
- |> json_response(200) == %{
- "configs" => [
- %{
- "db" => [":enabled"],
- "group" => ":pleroma",
- "key" => ":chat",
- "value" => [%{"tuple" => [":enabled", true]}]
- }
- ],
- "need_reboot" => true
- }
-
- assert post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{group: ":pleroma", key: ":key1", value: [%{"tuple" => [":key3", 3]}]}
- ]
- })
- |> json_response(200) == %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":key1",
- "value" => [
- %{"tuple" => [":key3", 3]}
- ],
- "db" => [":key3"]
- }
- ],
- "need_reboot" => true
- }
-
- capture_log(fn ->
- assert conn |> get("/api/pleroma/admin/restart") |> json_response(200) == %{}
- end) =~ "pleroma restarted"
-
- configs =
- conn
- |> get("/api/pleroma/admin/config")
- |> json_response(200)
-
- assert configs["need_reboot"] == false
- end
-
- test "saving config with nested merge", %{conn: conn} do
- config =
- insert(:config, key: ":key1", value: :erlang.term_to_binary(key1: 1, key2: [k1: 1, k2: 2]))
-
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- group: config.group,
- key: config.key,
- value: [
- %{"tuple" => [":key3", 3]},
- %{
- "tuple" => [
- ":key2",
- [
- %{"tuple" => [":k2", 1]},
- %{"tuple" => [":k3", 3]}
- ]
- ]
- }
- ]
- }
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":key1",
- "value" => [
- %{"tuple" => [":key1", 1]},
- %{"tuple" => [":key3", 3]},
- %{
- "tuple" => [
- ":key2",
- [
- %{"tuple" => [":k1", 1]},
- %{"tuple" => [":k2", 1]},
- %{"tuple" => [":k3", 3]}
- ]
- ]
- }
- ],
- "db" => [":key1", ":key3", ":key2"]
- }
- ]
- }
- end
-
- test "saving special atoms", %{conn: conn} do
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":key1",
- "value" => [
- %{
- "tuple" => [
- ":ssl_options",
- [%{"tuple" => [":versions", [":tlsv1", ":tlsv1.1", ":tlsv1.2"]]}]
- ]
- }
- ]
- }
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":key1",
- "value" => [
- %{
- "tuple" => [
- ":ssl_options",
- [%{"tuple" => [":versions", [":tlsv1", ":tlsv1.1", ":tlsv1.2"]]}]
- ]
- }
- ],
- "db" => [":ssl_options"]
- }
- ]
- }
-
- assert Application.get_env(:pleroma, :key1) == [
- ssl_options: [versions: [:tlsv1, :"tlsv1.1", :"tlsv1.2"]]
- ]
- end
-
- test "saving full setting if value is in full_key_update list", %{conn: conn} do
- backends = Application.get_env(:logger, :backends)
- on_exit(fn -> Application.put_env(:logger, :backends, backends) end)
-
- config =
- insert(:config,
- group: ":logger",
- key: ":backends",
- value: :erlang.term_to_binary([])
- )
-
- Pleroma.Config.TransferTask.load_and_update_env([], false)
-
- assert Application.get_env(:logger, :backends) == []
-
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- group: config.group,
- key: config.key,
- value: [":console"]
- }
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":logger",
- "key" => ":backends",
- "value" => [
- ":console"
- ],
- "db" => [":backends"]
- }
- ]
- }
-
- assert Application.get_env(:logger, :backends) == [
- :console
- ]
- end
-
- test "saving full setting if value is not keyword", %{conn: conn} do
- config =
- insert(:config,
- group: ":tesla",
- key: ":adapter",
- value: :erlang.term_to_binary(Tesla.Adapter.Hackey)
- )
-
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{group: config.group, key: config.key, value: "Tesla.Adapter.Httpc"}
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":tesla",
- "key" => ":adapter",
- "value" => "Tesla.Adapter.Httpc",
- "db" => [":adapter"]
- }
- ]
- }
- end
-
- test "update config setting & delete with fallback to default value", %{
- conn: conn,
- admin: admin,
- token: token
- } do
- ueberauth = Application.get_env(:ueberauth, Ueberauth)
- config1 = insert(:config, key: ":keyaa1")
- config2 = insert(:config, key: ":keyaa2")
-
- config3 =
- insert(:config,
- group: ":ueberauth",
- key: "Ueberauth"
- )
-
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{group: config1.group, key: config1.key, value: "another_value"},
- %{group: config2.group, key: config2.key, value: "another_value"}
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => config1.key,
- "value" => "another_value",
- "db" => [":keyaa1"]
- },
- %{
- "group" => ":pleroma",
- "key" => config2.key,
- "value" => "another_value",
- "db" => [":keyaa2"]
- }
- ]
- }
-
- assert Application.get_env(:pleroma, :keyaa1) == "another_value"
- assert Application.get_env(:pleroma, :keyaa2) == "another_value"
- assert Application.get_env(:ueberauth, Ueberauth) == ConfigDB.from_binary(config3.value)
-
- conn =
- build_conn()
- |> assign(:user, admin)
- |> assign(:token, token)
- |> post("/api/pleroma/admin/config", %{
- configs: [
- %{group: config2.group, key: config2.key, delete: true},
- %{
- group: ":ueberauth",
- key: "Ueberauth",
- delete: true
- }
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => []
- }
-
- assert Application.get_env(:ueberauth, Ueberauth) == ueberauth
- refute Keyword.has_key?(Application.get_all_env(:pleroma), :keyaa2)
- end
-
- test "common config example", %{conn: conn} do
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- "group" => ":pleroma",
- "key" => "Pleroma.Captcha.NotReal",
- "value" => [
- %{"tuple" => [":enabled", false]},
- %{"tuple" => [":method", "Pleroma.Captcha.Kocaptcha"]},
- %{"tuple" => [":seconds_valid", 60]},
- %{"tuple" => [":path", ""]},
- %{"tuple" => [":key1", nil]},
- %{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]},
- %{"tuple" => [":regex1", "~r/https:\/\/example.com/"]},
- %{"tuple" => [":regex2", "~r/https:\/\/example.com/u"]},
- %{"tuple" => [":regex3", "~r/https:\/\/example.com/i"]},
- %{"tuple" => [":regex4", "~r/https:\/\/example.com/s"]},
- %{"tuple" => [":name", "Pleroma"]}
- ]
- }
- ]
- })
-
- assert Config.get([Pleroma.Captcha.NotReal, :name]) == "Pleroma"
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => "Pleroma.Captcha.NotReal",
- "value" => [
- %{"tuple" => [":enabled", false]},
- %{"tuple" => [":method", "Pleroma.Captcha.Kocaptcha"]},
- %{"tuple" => [":seconds_valid", 60]},
- %{"tuple" => [":path", ""]},
- %{"tuple" => [":key1", nil]},
- %{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]},
- %{"tuple" => [":regex1", "~r/https:\\/\\/example.com/"]},
- %{"tuple" => [":regex2", "~r/https:\\/\\/example.com/u"]},
- %{"tuple" => [":regex3", "~r/https:\\/\\/example.com/i"]},
- %{"tuple" => [":regex4", "~r/https:\\/\\/example.com/s"]},
- %{"tuple" => [":name", "Pleroma"]}
- ],
- "db" => [
- ":enabled",
- ":method",
- ":seconds_valid",
- ":path",
- ":key1",
- ":partial_chain",
- ":regex1",
- ":regex2",
- ":regex3",
- ":regex4",
- ":name"
- ]
- }
- ]
- }
- end
-
- test "tuples with more than two values", %{conn: conn} do
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- "group" => ":pleroma",
- "key" => "Pleroma.Web.Endpoint.NotReal",
- "value" => [
- %{
- "tuple" => [
- ":http",
- [
- %{
- "tuple" => [
- ":key2",
- [
- %{
- "tuple" => [
- ":_",
- [
- %{
- "tuple" => [
- "/api/v1/streaming",
- "Pleroma.Web.MastodonAPI.WebsocketHandler",
- []
- ]
- },
- %{
- "tuple" => [
- "/websocket",
- "Phoenix.Endpoint.CowboyWebSocket",
- %{
- "tuple" => [
- "Phoenix.Transports.WebSocket",
- %{
- "tuple" => [
- "Pleroma.Web.Endpoint",
- "Pleroma.Web.UserSocket",
- []
- ]
- }
- ]
- }
- ]
- },
- %{
- "tuple" => [
- ":_",
- "Phoenix.Endpoint.Cowboy2Handler",
- %{"tuple" => ["Pleroma.Web.Endpoint", []]}
- ]
- }
- ]
- ]
- }
- ]
- ]
- }
- ]
- ]
- }
- ]
- }
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => "Pleroma.Web.Endpoint.NotReal",
- "value" => [
- %{
- "tuple" => [
- ":http",
- [
- %{
- "tuple" => [
- ":key2",
- [
- %{
- "tuple" => [
- ":_",
- [
- %{
- "tuple" => [
- "/api/v1/streaming",
- "Pleroma.Web.MastodonAPI.WebsocketHandler",
- []
- ]
- },
- %{
- "tuple" => [
- "/websocket",
- "Phoenix.Endpoint.CowboyWebSocket",
- %{
- "tuple" => [
- "Phoenix.Transports.WebSocket",
- %{
- "tuple" => [
- "Pleroma.Web.Endpoint",
- "Pleroma.Web.UserSocket",
- []
- ]
- }
- ]
- }
- ]
- },
- %{
- "tuple" => [
- ":_",
- "Phoenix.Endpoint.Cowboy2Handler",
- %{"tuple" => ["Pleroma.Web.Endpoint", []]}
- ]
- }
- ]
- ]
- }
- ]
- ]
- }
- ]
- ]
- }
- ],
- "db" => [":http"]
- }
- ]
- }
- end
-
- test "settings with nesting map", %{conn: conn} do
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- "group" => ":pleroma",
- "key" => ":key1",
- "value" => [
- %{"tuple" => [":key2", "some_val"]},
- %{
- "tuple" => [
- ":key3",
- %{
- ":max_options" => 20,
- ":max_option_chars" => 200,
- ":min_expiration" => 0,
- ":max_expiration" => 31_536_000,
- "nested" => %{
- ":max_options" => 20,
- ":max_option_chars" => 200,
- ":min_expiration" => 0,
- ":max_expiration" => 31_536_000
- }
- }
- ]
- }
- ]
- }
- ]
- })
-
- assert json_response(conn, 200) ==
- %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":key1",
- "value" => [
- %{"tuple" => [":key2", "some_val"]},
- %{
- "tuple" => [
- ":key3",
- %{
- ":max_expiration" => 31_536_000,
- ":max_option_chars" => 200,
- ":max_options" => 20,
- ":min_expiration" => 0,
- "nested" => %{
- ":max_expiration" => 31_536_000,
- ":max_option_chars" => 200,
- ":max_options" => 20,
- ":min_expiration" => 0
- }
- }
- ]
- }
- ],
- "db" => [":key2", ":key3"]
- }
- ]
- }
- end
-
- test "value as map", %{conn: conn} do
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- "group" => ":pleroma",
- "key" => ":key1",
- "value" => %{"key" => "some_val"}
- }
- ]
- })
-
- assert json_response(conn, 200) ==
- %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":key1",
- "value" => %{"key" => "some_val"},
- "db" => [":key1"]
- }
- ]
- }
- end
-
- test "queues key as atom", %{conn: conn} do
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- "group" => ":oban",
- "key" => ":queues",
- "value" => [
- %{"tuple" => [":federator_incoming", 50]},
- %{"tuple" => [":federator_outgoing", 50]},
- %{"tuple" => [":web_push", 50]},
- %{"tuple" => [":mailer", 10]},
- %{"tuple" => [":transmogrifier", 20]},
- %{"tuple" => [":scheduled_activities", 10]},
- %{"tuple" => [":background", 5]}
- ]
- }
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":oban",
- "key" => ":queues",
- "value" => [
- %{"tuple" => [":federator_incoming", 50]},
- %{"tuple" => [":federator_outgoing", 50]},
- %{"tuple" => [":web_push", 50]},
- %{"tuple" => [":mailer", 10]},
- %{"tuple" => [":transmogrifier", 20]},
- %{"tuple" => [":scheduled_activities", 10]},
- %{"tuple" => [":background", 5]}
- ],
- "db" => [
- ":federator_incoming",
- ":federator_outgoing",
- ":web_push",
- ":mailer",
- ":transmogrifier",
- ":scheduled_activities",
- ":background"
- ]
- }
- ]
- }
- end
-
- test "delete part of settings by atom subkeys", %{conn: conn} do
- config =
- insert(:config,
- key: ":keyaa1",
- value: :erlang.term_to_binary(subkey1: "val1", subkey2: "val2", subkey3: "val3")
- )
-
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- group: config.group,
- key: config.key,
- subkeys: [":subkey1", ":subkey3"],
- delete: true
- }
- ]
- })
-
- assert json_response(conn, 200) == %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":keyaa1",
- "value" => [%{"tuple" => [":subkey2", "val2"]}],
- "db" => [":subkey2"]
- }
- ]
- }
- end
-
- test "proxy tuple localhost", %{conn: conn} do
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- group: ":pleroma",
- key: ":http",
- value: [
- %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "localhost", 1234]}]}
- ]
- }
- ]
- })
-
- assert %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":http",
- "value" => value,
- "db" => db
- }
- ]
- } = json_response(conn, 200)
-
- assert %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "localhost", 1234]}]} in value
- assert ":proxy_url" in db
- end
-
- test "proxy tuple domain", %{conn: conn} do
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- group: ":pleroma",
- key: ":http",
- value: [
- %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "domain.com", 1234]}]}
- ]
- }
- ]
- })
-
- assert %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":http",
- "value" => value,
- "db" => db
- }
- ]
- } = json_response(conn, 200)
-
- assert %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "domain.com", 1234]}]} in value
- assert ":proxy_url" in db
- end
-
- test "proxy tuple ip", %{conn: conn} do
- conn =
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{
- group: ":pleroma",
- key: ":http",
- value: [
- %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "127.0.0.1", 1234]}]}
- ]
- }
- ]
- })
-
- assert %{
- "configs" => [
- %{
- "group" => ":pleroma",
- "key" => ":http",
- "value" => value,
- "db" => db
- }
- ]
- } = json_response(conn, 200)
-
- assert %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "127.0.0.1", 1234]}]} in value
- assert ":proxy_url" in db
- end
-
- test "doesn't set keys not in the whitelist", %{conn: conn} do
- clear_config(:database_config_whitelist, [
- {:pleroma, :key1},
- {:pleroma, :key2},
- {:pleroma, Pleroma.Captcha.NotReal},
- {:not_real}
- ])
-
- post(conn, "/api/pleroma/admin/config", %{
- configs: [
- %{group: ":pleroma", key: ":key1", value: "value1"},
- %{group: ":pleroma", key: ":key2", value: "value2"},
- %{group: ":pleroma", key: ":key3", value: "value3"},
- %{group: ":pleroma", key: "Pleroma.Web.Endpoint.NotReal", value: "value4"},
- %{group: ":pleroma", key: "Pleroma.Captcha.NotReal", value: "value5"},
- %{group: ":not_real", key: ":anything", value: "value6"}
- ]
- })
-
- assert Application.get_env(:pleroma, :key1) == "value1"
- assert Application.get_env(:pleroma, :key2) == "value2"
- assert Application.get_env(:pleroma, :key3) == nil
- assert Application.get_env(:pleroma, Pleroma.Web.Endpoint.NotReal) == nil
- assert Application.get_env(:pleroma, Pleroma.Captcha.NotReal) == "value5"
- assert Application.get_env(:not_real, :anything) == "value6"
- end
- end
-
- describe "GET /api/pleroma/admin/restart" do
- setup do: clear_config(:configurable_from_database, true)
-
- test "pleroma restarts", %{conn: conn} do
- capture_log(fn ->
- assert conn |> get("/api/pleroma/admin/restart") |> json_response(200) == %{}
- end) =~ "pleroma restarted"
-
- refute Restarter.Pleroma.need_reboot?()
- end
- end
-
- test "need_reboot flag", %{conn: conn} do
- assert conn
- |> get("/api/pleroma/admin/need_reboot")
- |> json_response(200) == %{"need_reboot" => false}
-
- Restarter.Pleroma.need_reboot()
-
- assert conn
- |> get("/api/pleroma/admin/need_reboot")
- |> json_response(200) == %{"need_reboot" => true}
-
- on_exit(fn -> Restarter.Pleroma.refresh() end)
- end
-
- describe "GET /api/pleroma/admin/statuses" do
- test "returns all public and unlisted statuses", %{conn: conn, admin: admin} do
- blocked = insert(:user)
- user = insert(:user)
- User.block(admin, blocked)
-
- {:ok, _} = CommonAPI.post(user, %{status: "@#{admin.nickname}", visibility: "direct"})
-
- {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "unlisted"})
- {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "private"})
- {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "public"})
- {:ok, _} = CommonAPI.post(blocked, %{status: ".", visibility: "public"})
-
- response =
- conn
- |> get("/api/pleroma/admin/statuses")
- |> json_response(200)
-
- refute "private" in Enum.map(response, & &1["visibility"])
- assert length(response) == 3
- end
-
- test "returns only local statuses with local_only on", %{conn: conn} do
- user = insert(:user)
- remote_user = insert(:user, local: false, nickname: "archaeme@archae.me")
- insert(:note_activity, user: user, local: true)
- insert(:note_activity, user: remote_user, local: false)
-
- response =
- conn
- |> get("/api/pleroma/admin/statuses?local_only=true")
- |> json_response(200)
-
- assert length(response) == 1
- end
-
- test "returns private and direct statuses with godmode on", %{conn: conn, admin: admin} do
- user = insert(:user)
-
- {:ok, _} = CommonAPI.post(user, %{status: "@#{admin.nickname}", visibility: "direct"})
-
- {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "private"})
- {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "public"})
- conn = get(conn, "/api/pleroma/admin/statuses?godmode=true")
- assert json_response(conn, 200) |> length() == 3
- end
- end
-
- describe "GET /api/pleroma/admin/users/:nickname/statuses" do
- setup do
- user = insert(:user)
-
- date1 = (DateTime.to_unix(DateTime.utc_now()) + 2000) |> DateTime.from_unix!()
- date2 = (DateTime.to_unix(DateTime.utc_now()) + 1000) |> DateTime.from_unix!()
- date3 = (DateTime.to_unix(DateTime.utc_now()) + 3000) |> DateTime.from_unix!()
-
- insert(:note_activity, user: user, published: date1)
- insert(:note_activity, user: user, published: date2)
- insert(:note_activity, user: user, published: date3)
-
- %{user: user}
- end
-
- test "renders user's statuses", %{conn: conn, user: user} do
- conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses")
-
- assert json_response(conn, 200) |> length() == 3
- end
-
- test "renders user's statuses with a limit", %{conn: conn, user: user} do
- conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses?page_size=2")
-
- assert json_response(conn, 200) |> length() == 2
- end
-
- test "doesn't return private statuses by default", %{conn: conn, user: user} do
- {:ok, _private_status} = CommonAPI.post(user, %{status: "private", visibility: "private"})
-
- {:ok, _public_status} = CommonAPI.post(user, %{status: "public", visibility: "public"})
-
- conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses")
-
- assert json_response(conn, 200) |> length() == 4
- end
-
- test "returns private statuses with godmode on", %{conn: conn, user: user} do
- {:ok, _private_status} = CommonAPI.post(user, %{status: "private", visibility: "private"})
-
- {:ok, _public_status} = CommonAPI.post(user, %{status: "public", visibility: "public"})
-
- conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses?godmode=true")
-
- assert json_response(conn, 200) |> length() == 5
- end
-
- test "excludes reblogs by default", %{conn: conn, user: user} do
- other_user = insert(:user)
- {:ok, activity} = CommonAPI.post(user, %{status: "."})
- {:ok, %Activity{}, _} = CommonAPI.repeat(activity.id, other_user)
-
- conn_res = get(conn, "/api/pleroma/admin/users/#{other_user.nickname}/statuses")
- assert json_response(conn_res, 200) |> length() == 0
-
- conn_res =
- get(conn, "/api/pleroma/admin/users/#{other_user.nickname}/statuses?with_reblogs=true")
-
- assert json_response(conn_res, 200) |> length() == 1
- end
- end
-
- describe "GET /api/pleroma/admin/moderation_log" do
- setup do
- moderator = insert(:user, is_moderator: true)
-
- %{moderator: moderator}
- end
-
- test "returns the log", %{conn: conn, admin: admin} do
- Repo.insert(%ModerationLog{
- data: %{
- actor: %{
- "id" => admin.id,
- "nickname" => admin.nickname,
- "type" => "user"
- },
- action: "relay_follow",
- target: "https://example.org/relay"
- },
- inserted_at: NaiveDateTime.truncate(~N[2017-08-15 15:47:06.597036], :second)
- })
-
- Repo.insert(%ModerationLog{
- data: %{
- actor: %{
- "id" => admin.id,
- "nickname" => admin.nickname,
- "type" => "user"
- },
- action: "relay_unfollow",
- target: "https://example.org/relay"
- },
- inserted_at: NaiveDateTime.truncate(~N[2017-08-16 15:47:06.597036], :second)
- })
-
- conn = get(conn, "/api/pleroma/admin/moderation_log")
-
- response = json_response(conn, 200)
- [first_entry, second_entry] = response["items"]
-
- assert response["total"] == 2
- assert first_entry["data"]["action"] == "relay_unfollow"
-
- assert first_entry["message"] ==
- "@#{admin.nickname} unfollowed relay: https://example.org/relay"
-
- assert second_entry["data"]["action"] == "relay_follow"
-
- assert second_entry["message"] ==
- "@#{admin.nickname} followed relay: https://example.org/relay"
- end
-
- test "returns the log with pagination", %{conn: conn, admin: admin} do
- Repo.insert(%ModerationLog{
- data: %{
- actor: %{
- "id" => admin.id,
- "nickname" => admin.nickname,
- "type" => "user"
- },
- action: "relay_follow",
- target: "https://example.org/relay"
- },
- inserted_at: NaiveDateTime.truncate(~N[2017-08-15 15:47:06.597036], :second)
- })
-
- Repo.insert(%ModerationLog{
- data: %{
- actor: %{
- "id" => admin.id,
- "nickname" => admin.nickname,
- "type" => "user"
- },
- action: "relay_unfollow",
- target: "https://example.org/relay"
- },
- inserted_at: NaiveDateTime.truncate(~N[2017-08-16 15:47:06.597036], :second)
- })
-
- conn1 = get(conn, "/api/pleroma/admin/moderation_log?page_size=1&page=1")
-
- response1 = json_response(conn1, 200)
- [first_entry] = response1["items"]
-
- assert response1["total"] == 2
- assert response1["items"] |> length() == 1
- assert first_entry["data"]["action"] == "relay_unfollow"
-
- assert first_entry["message"] ==
- "@#{admin.nickname} unfollowed relay: https://example.org/relay"
-
- conn2 = get(conn, "/api/pleroma/admin/moderation_log?page_size=1&page=2")
-
- response2 = json_response(conn2, 200)
- [second_entry] = response2["items"]
-
- assert response2["total"] == 2
- assert response2["items"] |> length() == 1
- assert second_entry["data"]["action"] == "relay_follow"
-
- assert second_entry["message"] ==
- "@#{admin.nickname} followed relay: https://example.org/relay"
- end
-
- test "filters log by date", %{conn: conn, admin: admin} do
- first_date = "2017-08-15T15:47:06Z"
- second_date = "2017-08-20T15:47:06Z"
-
- Repo.insert(%ModerationLog{
- data: %{
- actor: %{
- "id" => admin.id,
- "nickname" => admin.nickname,
- "type" => "user"
- },
- action: "relay_follow",
- target: "https://example.org/relay"
- },
- inserted_at: NaiveDateTime.from_iso8601!(first_date)
- })
-
- Repo.insert(%ModerationLog{
- data: %{
- actor: %{
- "id" => admin.id,
- "nickname" => admin.nickname,
- "type" => "user"
- },
- action: "relay_unfollow",
- target: "https://example.org/relay"
- },
- inserted_at: NaiveDateTime.from_iso8601!(second_date)
- })
-
- conn1 =
- get(
- conn,
- "/api/pleroma/admin/moderation_log?start_date=#{second_date}"
- )
-
- response1 = json_response(conn1, 200)
- [first_entry] = response1["items"]
-
- assert response1["total"] == 1
- assert first_entry["data"]["action"] == "relay_unfollow"
-
- assert first_entry["message"] ==
- "@#{admin.nickname} unfollowed relay: https://example.org/relay"
- end
-
- test "returns log filtered by user", %{conn: conn, admin: admin, moderator: moderator} do
- Repo.insert(%ModerationLog{
- data: %{
- actor: %{
- "id" => admin.id,
- "nickname" => admin.nickname,
- "type" => "user"
- },
- action: "relay_follow",
- target: "https://example.org/relay"
- }
- })
-
- Repo.insert(%ModerationLog{
- data: %{
- actor: %{
- "id" => moderator.id,
- "nickname" => moderator.nickname,
- "type" => "user"
- },
- action: "relay_unfollow",
- target: "https://example.org/relay"
- }
- })
-
- conn1 = get(conn, "/api/pleroma/admin/moderation_log?user_id=#{moderator.id}")
-
- response1 = json_response(conn1, 200)
- [first_entry] = response1["items"]
-
- assert response1["total"] == 1
- assert get_in(first_entry, ["data", "actor", "id"]) == moderator.id
- end
-
- test "returns log filtered by search", %{conn: conn, moderator: moderator} do
- ModerationLog.insert_log(%{
- actor: moderator,
- action: "relay_follow",
- target: "https://example.org/relay"
- })
-
- ModerationLog.insert_log(%{
- actor: moderator,
- action: "relay_unfollow",
- target: "https://example.org/relay"
- })
-
- conn1 = get(conn, "/api/pleroma/admin/moderation_log?search=unfo")
-
- response1 = json_response(conn1, 200)
- [first_entry] = response1["items"]
-
- assert response1["total"] == 1
-
- assert get_in(first_entry, ["data", "message"]) ==
- "@#{moderator.nickname} unfollowed relay: https://example.org/relay"
- end
- end
-
- describe "GET /users/:nickname/credentials" do
- test "gets the user credentials", %{conn: conn} do
- user = insert(:user)
- conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/credentials")
-
- response = assert json_response(conn, 200)
- assert response["email"] == user.email
- end
-
- test "returns 403 if requested by a non-admin" do
- user = insert(:user)
-
- conn =
- build_conn()
- |> assign(:user, user)
- |> get("/api/pleroma/admin/users/#{user.nickname}/credentials")
-
- assert json_response(conn, :forbidden)
- end
- end
-
- describe "PATCH /users/:nickname/credentials" do
- test "changes password and email", %{conn: conn, admin: admin} do
- user = insert(:user)
- assert user.password_reset_pending == false
-
- conn =
- patch(conn, "/api/pleroma/admin/users/#{user.nickname}/credentials", %{
- "password" => "new_password",
- "email" => "new_email@example.com",
- "name" => "new_name"
- })
-
- assert json_response(conn, 200) == %{"status" => "success"}
-
- ObanHelpers.perform_all()
-
- updated_user = User.get_by_id(user.id)
-
- assert updated_user.email == "new_email@example.com"
- assert updated_user.name == "new_name"
- assert updated_user.password_hash != user.password_hash
- assert updated_user.password_reset_pending == true
-
- [log_entry2, log_entry1] = ModerationLog |> Repo.all() |> Enum.sort()
-
- assert ModerationLog.get_log_entry_message(log_entry1) ==
- "@#{admin.nickname} updated users: @#{user.nickname}"
-
- assert ModerationLog.get_log_entry_message(log_entry2) ==
- "@#{admin.nickname} forced password reset for users: @#{user.nickname}"
- end
-
- test "returns 403 if requested by a non-admin" do
- user = insert(:user)
-
- conn =
- build_conn()
- |> assign(:user, user)
- |> patch("/api/pleroma/admin/users/#{user.nickname}/credentials", %{
- "password" => "new_password",
- "email" => "new_email@example.com",
- "name" => "new_name"
- })
-
- assert json_response(conn, :forbidden)
- end
- end
-
- describe "PATCH /users/:nickname/force_password_reset" do
- test "sets password_reset_pending to true", %{conn: conn} do
- user = insert(:user)
- assert user.password_reset_pending == false
-
- conn =
- patch(conn, "/api/pleroma/admin/users/force_password_reset", %{nicknames: [user.nickname]})
-
- assert json_response(conn, 204) == ""
-
- ObanHelpers.perform_all()
-
- assert User.get_by_id(user.id).password_reset_pending == true
- end
- end
-
- describe "relays" do
- test "POST /relay", %{conn: conn, admin: admin} do
- conn =
- post(conn, "/api/pleroma/admin/relay", %{
- relay_url: "http://mastodon.example.org/users/admin"
- })
-
- assert json_response(conn, 200) == "http://mastodon.example.org/users/admin"
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} followed relay: http://mastodon.example.org/users/admin"
- end
-
- test "GET /relay", %{conn: conn} do
- relay_user = Pleroma.Web.ActivityPub.Relay.get_actor()
-
- ["http://mastodon.example.org/users/admin", "https://mstdn.io/users/mayuutann"]
- |> Enum.each(fn ap_id ->
- {:ok, user} = User.get_or_fetch_by_ap_id(ap_id)
- User.follow(relay_user, user)
- end)
-
- conn = get(conn, "/api/pleroma/admin/relay")
-
- assert json_response(conn, 200)["relays"] -- ["mastodon.example.org", "mstdn.io"] == []
- end
-
- test "DELETE /relay", %{conn: conn, admin: admin} do
- post(conn, "/api/pleroma/admin/relay", %{
- relay_url: "http://mastodon.example.org/users/admin"
- })
-
- conn =
- delete(conn, "/api/pleroma/admin/relay", %{
- relay_url: "http://mastodon.example.org/users/admin"
- })
-
- assert json_response(conn, 200) == "http://mastodon.example.org/users/admin"
-
- [log_entry_one, log_entry_two] = Repo.all(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry_one) ==
- "@#{admin.nickname} followed relay: http://mastodon.example.org/users/admin"
-
- assert ModerationLog.get_log_entry_message(log_entry_two) ==
- "@#{admin.nickname} unfollowed relay: http://mastodon.example.org/users/admin"
- end
- end
-
- describe "instances" do
- test "GET /instances/:instance/statuses", %{conn: conn} do
- user = insert(:user, local: false, nickname: "archaeme@archae.me")
- user2 = insert(:user, local: false, nickname: "test@test.com")
- insert_pair(:note_activity, user: user)
- activity = insert(:note_activity, user: user2)
-
- ret_conn = get(conn, "/api/pleroma/admin/instances/archae.me/statuses")
-
- response = json_response(ret_conn, 200)
-
- assert length(response) == 2
-
- ret_conn = get(conn, "/api/pleroma/admin/instances/test.com/statuses")
-
- response = json_response(ret_conn, 200)
-
- assert length(response) == 1
-
- ret_conn = get(conn, "/api/pleroma/admin/instances/nonexistent.com/statuses")
-
- response = json_response(ret_conn, 200)
-
- assert Enum.empty?(response)
-
- CommonAPI.repeat(activity.id, user)
-
- ret_conn = get(conn, "/api/pleroma/admin/instances/archae.me/statuses")
- response = json_response(ret_conn, 200)
- assert length(response) == 2
-
- ret_conn = get(conn, "/api/pleroma/admin/instances/archae.me/statuses?with_reblogs=true")
- response = json_response(ret_conn, 200)
- assert length(response) == 3
- end
- end
-
- describe "PATCH /confirm_email" do
- test "it confirms emails of two users", %{conn: conn, admin: admin} do
- [first_user, second_user] = insert_pair(:user, confirmation_pending: true)
-
- assert first_user.confirmation_pending == true
- assert second_user.confirmation_pending == true
-
- ret_conn =
- patch(conn, "/api/pleroma/admin/users/confirm_email", %{
- nicknames: [
- first_user.nickname,
- second_user.nickname
- ]
- })
-
- assert ret_conn.status == 200
-
- assert first_user.confirmation_pending == true
- assert second_user.confirmation_pending == true
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} confirmed email for users: @#{first_user.nickname}, @#{
- second_user.nickname
- }"
- end
- end
-
- describe "PATCH /resend_confirmation_email" do
- test "it resend emails for two users", %{conn: conn, admin: admin} do
- [first_user, second_user] = insert_pair(:user, confirmation_pending: true)
-
- ret_conn =
- patch(conn, "/api/pleroma/admin/users/resend_confirmation_email", %{
- nicknames: [
- first_user.nickname,
- second_user.nickname
- ]
- })
-
- assert ret_conn.status == 200
-
- log_entry = Repo.one(ModerationLog)
-
- assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} re-sent confirmation email for users: @#{first_user.nickname}, @#{
- second_user.nickname
- }"
- end
- end
-
- describe "POST /reports/:id/notes" do
- setup %{conn: conn, admin: admin} do
- [reporter, target_user] = insert_pair(:user)
- activity = insert(:note_activity, user: target_user)
-
- {:ok, %{id: report_id}} =
- CommonAPI.report(reporter, %{
- account_id: target_user.id,
- comment: "I feel offended",
- status_ids: [activity.id]
- })
-
- post(conn, "/api/pleroma/admin/reports/#{report_id}/notes", %{
- content: "this is disgusting!"
- })
-
- post(conn, "/api/pleroma/admin/reports/#{report_id}/notes", %{
- content: "this is disgusting2!"
- })
-
- %{
- admin_id: admin.id,
- report_id: report_id
- }
- end
-
- test "it creates report note", %{admin_id: admin_id, report_id: report_id} do
- [note, _] = Repo.all(ReportNote)
-
- assert %{
- activity_id: ^report_id,
- content: "this is disgusting!",
- user_id: ^admin_id
- } = note
- end
-
- test "it returns reports with notes", %{conn: conn, admin: admin} do
- conn = get(conn, "/api/pleroma/admin/reports")
-
- response = json_response(conn, 200)
- notes = hd(response["reports"])["notes"]
- [note, _] = notes
-
- assert note["user"]["nickname"] == admin.nickname
- assert note["content"] == "this is disgusting!"
- assert note["created_at"]
- assert response["total"] == 1
- end
-
- test "it deletes the note", %{conn: conn, report_id: report_id} do
- assert ReportNote |> Repo.all() |> length() == 2
-
- [note, _] = Repo.all(ReportNote)
-
- delete(conn, "/api/pleroma/admin/reports/#{report_id}/notes/#{note.id}")
-
- assert ReportNote |> Repo.all() |> length() == 1
- end
- end
-
- describe "GET /api/pleroma/admin/config/descriptions" do
- test "structure", %{conn: conn} do
- admin = insert(:user, is_admin: true)
-
- conn =
- assign(conn, :user, admin)
- |> get("/api/pleroma/admin/config/descriptions")
-
- assert [child | _others] = json_response(conn, 200)
-
- assert child["children"]
- assert child["key"]
- assert String.starts_with?(child["group"], ":")
- assert child["description"]
- end
-
- test "filters by database configuration whitelist", %{conn: conn} do
- clear_config(:database_config_whitelist, [
- {:pleroma, :instance},
- {:pleroma, :activitypub},
- {:pleroma, Pleroma.Upload},
- {:esshd}
- ])
-
- admin = insert(:user, is_admin: true)
-
- conn =
- assign(conn, :user, admin)
- |> get("/api/pleroma/admin/config/descriptions")
-
- children = json_response(conn, 200)
-
- assert length(children) == 4
-
- assert Enum.count(children, fn c -> c["group"] == ":pleroma" end) == 3
-
- instance = Enum.find(children, fn c -> c["key"] == ":instance" end)
- assert instance["children"]
-
- activitypub = Enum.find(children, fn c -> c["key"] == ":activitypub" end)
- assert activitypub["children"]
-
- web_endpoint = Enum.find(children, fn c -> c["key"] == "Pleroma.Upload" end)
- assert web_endpoint["children"]
-
- esshd = Enum.find(children, fn c -> c["group"] == ":esshd" end)
- assert esshd["children"]
- end
- end
-
- describe "/api/pleroma/admin/stats" do
- test "status visibility count", %{conn: conn} do
- admin = insert(:user, is_admin: true)
- user = insert(:user)
- CommonAPI.post(user, %{visibility: "public", status: "hey"})
- CommonAPI.post(user, %{visibility: "unlisted", status: "hey"})
- CommonAPI.post(user, %{visibility: "unlisted", status: "hey"})
-
- response =
- conn
- |> assign(:user, admin)
- |> get("/api/pleroma/admin/stats")
- |> json_response(200)
-
- assert %{"direct" => 0, "private" => 0, "public" => 1, "unlisted" => 2} =
- response["status_visibility"]
- end
- end
-
- describe "POST /api/pleroma/admin/oauth_app" do
- test "errors", %{conn: conn} do
- response = conn |> post("/api/pleroma/admin/oauth_app", %{}) |> json_response(200)
-
- assert response == %{"name" => "can't be blank", "redirect_uris" => "can't be blank"}
- end
-
- test "success", %{conn: conn} do
- base_url = Web.base_url()
- app_name = "Trusted app"
-
- response =
- conn
- |> post("/api/pleroma/admin/oauth_app", %{
- name: app_name,
- redirect_uris: base_url
- })
- |> json_response(200)
-
- assert %{
- "client_id" => _,
- "client_secret" => _,
- "name" => ^app_name,
- "redirect_uri" => ^base_url,
- "trusted" => false
- } = response
- end
-
- test "with trusted", %{conn: conn} do
- base_url = Web.base_url()
- app_name = "Trusted app"
-
- response =
- conn
- |> post("/api/pleroma/admin/oauth_app", %{
- name: app_name,
- redirect_uris: base_url,
- trusted: true
- })
- |> json_response(200)
-
- assert %{
- "client_id" => _,
- "client_secret" => _,
- "name" => ^app_name,
- "redirect_uri" => ^base_url,
- "trusted" => true
- } = response
- end
- end
-
- describe "GET /api/pleroma/admin/oauth_app" do
- setup do
- app = insert(:oauth_app)
- {:ok, app: app}
- end
-
- test "list", %{conn: conn} do
- response =
- conn
- |> get("/api/pleroma/admin/oauth_app")
- |> json_response(200)
-
- assert %{"apps" => apps, "count" => count, "page_size" => _} = response
-
- assert length(apps) == count
- end
-
- test "with page size", %{conn: conn} do
- insert(:oauth_app)
- page_size = 1
-
- response =
- conn
- |> get("/api/pleroma/admin/oauth_app", %{page_size: to_string(page_size)})
- |> json_response(200)
-
- assert %{"apps" => apps, "count" => _, "page_size" => ^page_size} = response
-
- assert length(apps) == page_size
- end
-
- test "search by client name", %{conn: conn, app: app} do
- response =
- conn
- |> get("/api/pleroma/admin/oauth_app", %{name: app.client_name})
- |> json_response(200)
-
- assert %{"apps" => [returned], "count" => _, "page_size" => _} = response
-
- assert returned["client_id"] == app.client_id
- assert returned["name"] == app.client_name
- end
-
- test "search by client id", %{conn: conn, app: app} do
- response =
- conn
- |> get("/api/pleroma/admin/oauth_app", %{client_id: app.client_id})
- |> json_response(200)
-
- assert %{"apps" => [returned], "count" => _, "page_size" => _} = response
-
- assert returned["client_id"] == app.client_id
- assert returned["name"] == app.client_name
- end
-
- test "only trusted", %{conn: conn} do
- app = insert(:oauth_app, trusted: true)
-
- response =
- conn
- |> get("/api/pleroma/admin/oauth_app", %{trusted: true})
- |> json_response(200)
-
- assert %{"apps" => [returned], "count" => _, "page_size" => _} = response
-
- assert returned["client_id"] == app.client_id
- assert returned["name"] == app.client_name
- end
- end
-
- describe "DELETE /api/pleroma/admin/oauth_app/:id" do
- test "with id", %{conn: conn} do
- app = insert(:oauth_app)
-
- response =
- conn
- |> delete("/api/pleroma/admin/oauth_app/" <> to_string(app.id))
- |> json_response(:no_content)
-
- assert response == ""
- end
-
- test "with non existance id", %{conn: conn} do
- response =
- conn
- |> delete("/api/pleroma/admin/oauth_app/0")
- |> json_response(:bad_request)
-
- assert response == ""
- end
- end
-
- describe "PATCH /api/pleroma/admin/oauth_app/:id" do
- test "with id", %{conn: conn} do
- app = insert(:oauth_app)
-
- name = "another name"
- url = "https://example.com"
- scopes = ["admin"]
- id = app.id
- website = "http://website.com"
-
- response =
- conn
- |> patch("/api/pleroma/admin/oauth_app/" <> to_string(app.id), %{
- name: name,
- trusted: true,
- redirect_uris: url,
- scopes: scopes,
- website: website
- })
- |> json_response(200)
-
- assert %{
- "client_id" => _,
- "client_secret" => _,
- "id" => ^id,
- "name" => ^name,
- "redirect_uri" => ^url,
- "trusted" => true,
- "website" => ^website
- } = response
- end
-
- test "without id", %{conn: conn} do
- response =
- conn
- |> patch("/api/pleroma/admin/oauth_app/0")
- |> json_response(:bad_request)
-
- assert response == ""
- end
- end
-end
-
-# Needed for testing
-defmodule Pleroma.Web.Endpoint.NotReal do
-end
-
-defmodule Pleroma.Captcha.NotReal do
-end
diff --git a/test/web/admin_api/controllers/admin_api_controller_test.exs b/test/web/admin_api/controllers/admin_api_controller_test.exs
new file mode 100644
index 000000000..2c317e0fe
--- /dev/null
+++ b/test/web/admin_api/controllers/admin_api_controller_test.exs
@@ -0,0 +1,3707 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
+ use Pleroma.Web.ConnCase
+ use Oban.Testing, repo: Pleroma.Repo
+
+ import ExUnit.CaptureLog
+ import Mock
+ import Pleroma.Factory
+
+ alias Pleroma.Activity
+ alias Pleroma.Config
+ alias Pleroma.ConfigDB
+ alias Pleroma.HTML
+ alias Pleroma.MFA
+ alias Pleroma.ModerationLog
+ alias Pleroma.Repo
+ alias Pleroma.ReportNote
+ alias Pleroma.Tests.ObanHelpers
+ alias Pleroma.User
+ alias Pleroma.UserInviteToken
+ alias Pleroma.Web
+ alias Pleroma.Web.ActivityPub.Relay
+ alias Pleroma.Web.CommonAPI
+ alias Pleroma.Web.MediaProxy
+
+ setup_all do
+ Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
+
+ :ok
+ end
+
+ setup do
+ admin = insert(:user, is_admin: true)
+ token = insert(:oauth_admin_token, user: admin)
+
+ conn =
+ build_conn()
+ |> assign(:user, admin)
+ |> assign(:token, token)
+
+ {:ok, %{admin: admin, token: token, conn: conn}}
+ end
+
+ describe "with [:auth, :enforce_oauth_admin_scope_usage]," do
+ setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], true)
+
+ test "GET /api/pleroma/admin/users/:nickname requires admin:read:accounts or broader scope",
+ %{admin: admin} do
+ user = insert(:user)
+ url = "/api/pleroma/admin/users/#{user.nickname}"
+
+ good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"])
+ good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"])
+ good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"])
+
+ bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts"])
+ bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"])
+ bad_token3 = nil
+
+ for good_token <- [good_token1, good_token2, good_token3] do
+ conn =
+ build_conn()
+ |> assign(:user, admin)
+ |> assign(:token, good_token)
+ |> get(url)
+
+ assert json_response(conn, 200)
+ end
+
+ for good_token <- [good_token1, good_token2, good_token3] do
+ conn =
+ build_conn()
+ |> assign(:user, nil)
+ |> assign(:token, good_token)
+ |> get(url)
+
+ assert json_response(conn, :forbidden)
+ end
+
+ for bad_token <- [bad_token1, bad_token2, bad_token3] do
+ conn =
+ build_conn()
+ |> assign(:user, admin)
+ |> assign(:token, bad_token)
+ |> get(url)
+
+ assert json_response(conn, :forbidden)
+ end
+ end
+ end
+
+ describe "unless [:auth, :enforce_oauth_admin_scope_usage]," do
+ setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false)
+
+ test "GET /api/pleroma/admin/users/:nickname requires " <>
+ "read:accounts or admin:read:accounts or broader scope",
+ %{admin: admin} do
+ user = insert(:user)
+ url = "/api/pleroma/admin/users/#{user.nickname}"
+
+ good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"])
+ good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"])
+ good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"])
+ good_token4 = insert(:oauth_token, user: admin, scopes: ["read:accounts"])
+ good_token5 = insert(:oauth_token, user: admin, scopes: ["read"])
+
+ good_tokens = [good_token1, good_token2, good_token3, good_token4, good_token5]
+
+ bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts:partial"])
+ bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"])
+ bad_token3 = nil
+
+ for good_token <- good_tokens do
+ conn =
+ build_conn()
+ |> assign(:user, admin)
+ |> assign(:token, good_token)
+ |> get(url)
+
+ assert json_response(conn, 200)
+ end
+
+ for good_token <- good_tokens do
+ conn =
+ build_conn()
+ |> assign(:user, nil)
+ |> assign(:token, good_token)
+ |> get(url)
+
+ assert json_response(conn, :forbidden)
+ end
+
+ for bad_token <- [bad_token1, bad_token2, bad_token3] do
+ conn =
+ build_conn()
+ |> assign(:user, admin)
+ |> assign(:token, bad_token)
+ |> get(url)
+
+ assert json_response(conn, :forbidden)
+ end
+ end
+ end
+
+ describe "DELETE /api/pleroma/admin/users" do
+ test "single user", %{admin: admin, conn: conn} do
+ user = insert(:user)
+
+ with_mock Pleroma.Web.Federator,
+ publish: fn _ -> nil end do
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> delete("/api/pleroma/admin/users?nickname=#{user.nickname}")
+
+ ObanHelpers.perform_all()
+
+ assert User.get_by_nickname(user.nickname).deactivated
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} deleted users: @#{user.nickname}"
+
+ assert json_response(conn, 200) == [user.nickname]
+
+ assert called(Pleroma.Web.Federator.publish(:_))
+ end
+ end
+
+ test "multiple users", %{admin: admin, conn: conn} do
+ user_one = insert(:user)
+ user_two = insert(:user)
+
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> delete("/api/pleroma/admin/users", %{
+ nicknames: [user_one.nickname, user_two.nickname]
+ })
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} deleted users: @#{user_one.nickname}, @#{user_two.nickname}"
+
+ response = json_response(conn, 200)
+ assert response -- [user_one.nickname, user_two.nickname] == []
+ end
+ end
+
+ describe "/api/pleroma/admin/users" do
+ test "Create", %{conn: conn} do
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> post("/api/pleroma/admin/users", %{
+ "users" => [
+ %{
+ "nickname" => "lain",
+ "email" => "lain@example.org",
+ "password" => "test"
+ },
+ %{
+ "nickname" => "lain2",
+ "email" => "lain2@example.org",
+ "password" => "test"
+ }
+ ]
+ })
+
+ response = json_response(conn, 200) |> Enum.map(&Map.get(&1, "type"))
+ assert response == ["success", "success"]
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ["lain", "lain2"] -- Enum.map(log_entry.data["subjects"], & &1["nickname"]) == []
+ end
+
+ test "Cannot create user with existing email", %{conn: conn} do
+ user = insert(:user)
+
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> post("/api/pleroma/admin/users", %{
+ "users" => [
+ %{
+ "nickname" => "lain",
+ "email" => user.email,
+ "password" => "test"
+ }
+ ]
+ })
+
+ assert json_response(conn, 409) == [
+ %{
+ "code" => 409,
+ "data" => %{
+ "email" => user.email,
+ "nickname" => "lain"
+ },
+ "error" => "email has already been taken",
+ "type" => "error"
+ }
+ ]
+ end
+
+ test "Cannot create user with existing nickname", %{conn: conn} do
+ user = insert(:user)
+
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> post("/api/pleroma/admin/users", %{
+ "users" => [
+ %{
+ "nickname" => user.nickname,
+ "email" => "someuser@plerama.social",
+ "password" => "test"
+ }
+ ]
+ })
+
+ assert json_response(conn, 409) == [
+ %{
+ "code" => 409,
+ "data" => %{
+ "email" => "someuser@plerama.social",
+ "nickname" => user.nickname
+ },
+ "error" => "nickname has already been taken",
+ "type" => "error"
+ }
+ ]
+ end
+
+ test "Multiple user creation works in transaction", %{conn: conn} do
+ user = insert(:user)
+
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> post("/api/pleroma/admin/users", %{
+ "users" => [
+ %{
+ "nickname" => "newuser",
+ "email" => "newuser@pleroma.social",
+ "password" => "test"
+ },
+ %{
+ "nickname" => "lain",
+ "email" => user.email,
+ "password" => "test"
+ }
+ ]
+ })
+
+ assert json_response(conn, 409) == [
+ %{
+ "code" => 409,
+ "data" => %{
+ "email" => user.email,
+ "nickname" => "lain"
+ },
+ "error" => "email has already been taken",
+ "type" => "error"
+ },
+ %{
+ "code" => 409,
+ "data" => %{
+ "email" => "newuser@pleroma.social",
+ "nickname" => "newuser"
+ },
+ "error" => "",
+ "type" => "error"
+ }
+ ]
+
+ assert User.get_by_nickname("newuser") === nil
+ end
+ end
+
+ describe "/api/pleroma/admin/users/:nickname" do
+ test "Show", %{conn: conn} do
+ user = insert(:user)
+
+ conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}")
+
+ expected = %{
+ "deactivated" => false,
+ "id" => to_string(user.id),
+ "local" => true,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "tags" => [],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ }
+
+ assert expected == json_response(conn, 200)
+ end
+
+ test "when the user doesn't exist", %{conn: conn} do
+ user = build(:user)
+
+ conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}")
+
+ assert "Not found" == json_response(conn, 404)
+ end
+ end
+
+ describe "/api/pleroma/admin/users/follow" do
+ test "allows to force-follow another user", %{admin: admin, conn: conn} do
+ user = insert(:user)
+ follower = insert(:user)
+
+ conn
+ |> put_req_header("accept", "application/json")
+ |> post("/api/pleroma/admin/users/follow", %{
+ "follower" => follower.nickname,
+ "followed" => user.nickname
+ })
+
+ user = User.get_cached_by_id(user.id)
+ follower = User.get_cached_by_id(follower.id)
+
+ assert User.following?(follower, user)
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} made @#{follower.nickname} follow @#{user.nickname}"
+ end
+ end
+
+ describe "/api/pleroma/admin/users/unfollow" do
+ test "allows to force-unfollow another user", %{admin: admin, conn: conn} do
+ user = insert(:user)
+ follower = insert(:user)
+
+ User.follow(follower, user)
+
+ conn
+ |> put_req_header("accept", "application/json")
+ |> post("/api/pleroma/admin/users/unfollow", %{
+ "follower" => follower.nickname,
+ "followed" => user.nickname
+ })
+
+ user = User.get_cached_by_id(user.id)
+ follower = User.get_cached_by_id(follower.id)
+
+ refute User.following?(follower, user)
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} made @#{follower.nickname} unfollow @#{user.nickname}"
+ end
+ end
+
+ describe "PUT /api/pleroma/admin/users/tag" do
+ setup %{conn: conn} do
+ user1 = insert(:user, %{tags: ["x"]})
+ user2 = insert(:user, %{tags: ["y"]})
+ user3 = insert(:user, %{tags: ["unchanged"]})
+
+ conn =
+ conn
+ |> 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,
+ admin: admin,
+ user1: user1,
+ user2: user2
+ } do
+ assert json_response(conn, :no_content)
+ assert User.get_cached_by_id(user1.id).tags == ["x", "foo", "bar"]
+ assert User.get_cached_by_id(user2.id).tags == ["y", "foo", "bar"]
+
+ log_entry = Repo.one(ModerationLog)
+
+ users =
+ [user1.nickname, user2.nickname]
+ |> Enum.map(&"@#{&1}")
+ |> Enum.join(", ")
+
+ tags = ["foo", "bar"] |> Enum.join(", ")
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} added tags: #{tags} to users: #{users}"
+ end
+
+ test "it does not modify tags of not specified users", %{conn: conn, user3: user3} do
+ assert json_response(conn, :no_content)
+ assert User.get_cached_by_id(user3.id).tags == ["unchanged"]
+ end
+ end
+
+ describe "DELETE /api/pleroma/admin/users/tag" do
+ setup %{conn: conn} do
+ user1 = insert(:user, %{tags: ["x"]})
+ user2 = insert(:user, %{tags: ["y", "z"]})
+ user3 = insert(:user, %{tags: ["unchanged"]})
+
+ conn =
+ conn
+ |> 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,
+ admin: admin,
+ user1: user1,
+ user2: user2
+ } do
+ assert json_response(conn, :no_content)
+ assert User.get_cached_by_id(user1.id).tags == []
+ assert User.get_cached_by_id(user2.id).tags == ["y"]
+
+ log_entry = Repo.one(ModerationLog)
+
+ users =
+ [user1.nickname, user2.nickname]
+ |> Enum.map(&"@#{&1}")
+ |> Enum.join(", ")
+
+ tags = ["x", "z"] |> Enum.join(", ")
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} removed tags: #{tags} from users: #{users}"
+ end
+
+ test "it does not modify tags of not specified users", %{conn: conn, user3: user3} do
+ assert json_response(conn, :no_content)
+ assert User.get_cached_by_id(user3.id).tags == ["unchanged"]
+ end
+ end
+
+ describe "/api/pleroma/admin/users/:nickname/permission_group" do
+ test "GET is giving user_info", %{admin: admin, conn: conn} do
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> get("/api/pleroma/admin/users/#{admin.nickname}/permission_group/")
+
+ assert json_response(conn, 200) == %{
+ "is_admin" => true,
+ "is_moderator" => false
+ }
+ end
+
+ test "/:right POST, can add to a permission group", %{admin: admin, conn: conn} do
+ user = insert(:user)
+
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> post("/api/pleroma/admin/users/#{user.nickname}/permission_group/admin")
+
+ assert json_response(conn, 200) == %{
+ "is_admin" => true
+ }
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} made @#{user.nickname} admin"
+ end
+
+ test "/:right POST, can add to a permission group (multiple)", %{admin: admin, conn: conn} do
+ user_one = insert(:user)
+ user_two = insert(:user)
+
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> post("/api/pleroma/admin/users/permission_group/admin", %{
+ nicknames: [user_one.nickname, user_two.nickname]
+ })
+
+ assert json_response(conn, 200) == %{"is_admin" => true}
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} made @#{user_one.nickname}, @#{user_two.nickname} admin"
+ end
+
+ test "/:right DELETE, can remove from a permission group", %{admin: admin, conn: conn} do
+ user = insert(:user, is_admin: true)
+
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> delete("/api/pleroma/admin/users/#{user.nickname}/permission_group/admin")
+
+ assert json_response(conn, 200) == %{"is_admin" => false}
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} revoked admin role from @#{user.nickname}"
+ end
+
+ test "/:right DELETE, can remove from a permission group (multiple)", %{
+ admin: admin,
+ conn: conn
+ } do
+ user_one = insert(:user, is_admin: true)
+ user_two = insert(:user, is_admin: true)
+
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> delete("/api/pleroma/admin/users/permission_group/admin", %{
+ nicknames: [user_one.nickname, user_two.nickname]
+ })
+
+ assert json_response(conn, 200) == %{"is_admin" => false}
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} revoked admin role from @#{user_one.nickname}, @#{
+ user_two.nickname
+ }"
+ end
+ end
+
+ describe "POST /api/pleroma/admin/email_invite, with valid config" do
+ setup do: clear_config([:instance, :registrations_open], false)
+ setup do: clear_config([:instance, :invites_enabled], true)
+
+ test "sends invitation and returns 204", %{admin: admin, conn: conn} do
+ recipient_email = "foo@bar.com"
+ recipient_name = "J. D."
+
+ conn =
+ post(
+ conn,
+ "/api/pleroma/admin/users/email_invite?email=#{recipient_email}&name=#{recipient_name}"
+ )
+
+ assert json_response(conn, :no_content)
+
+ token_record = List.last(Repo.all(Pleroma.UserInviteToken))
+ assert token_record
+ refute token_record.used
+
+ notify_email = Config.get([:instance, :notify_email])
+ instance_name = Config.get([:instance, :name])
+
+ email =
+ Pleroma.Emails.UserEmail.user_invitation_email(
+ admin,
+ token_record,
+ recipient_email,
+ recipient_name
+ )
+
+ Swoosh.TestAssertions.assert_email_sent(
+ from: {instance_name, notify_email},
+ to: {recipient_name, recipient_email},
+ html_body: email.html_body
+ )
+ end
+
+ test "it returns 403 if requested by a non-admin" do
+ non_admin_user = insert(:user)
+ token = insert(:oauth_token, user: non_admin_user)
+
+ conn =
+ build_conn()
+ |> assign(:user, non_admin_user)
+ |> assign(:token, token)
+ |> post("/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
+
+ assert json_response(conn, :forbidden)
+ end
+
+ test "email with +", %{conn: conn, admin: admin} do
+ recipient_email = "foo+bar@baz.com"
+
+ conn
+ |> put_req_header("content-type", "application/json;charset=utf-8")
+ |> post("/api/pleroma/admin/users/email_invite", %{email: recipient_email})
+ |> json_response(:no_content)
+
+ token_record =
+ Pleroma.UserInviteToken
+ |> Repo.all()
+ |> List.last()
+
+ assert token_record
+ refute token_record.used
+
+ notify_email = Config.get([:instance, :notify_email])
+ instance_name = Config.get([:instance, :name])
+
+ email =
+ Pleroma.Emails.UserEmail.user_invitation_email(
+ admin,
+ token_record,
+ recipient_email
+ )
+
+ Swoosh.TestAssertions.assert_email_sent(
+ from: {instance_name, notify_email},
+ to: recipient_email,
+ html_body: email.html_body
+ )
+ end
+ end
+
+ describe "POST /api/pleroma/admin/users/email_invite, with invalid config" do
+ setup do: clear_config([:instance, :registrations_open])
+ setup do: clear_config([:instance, :invites_enabled])
+
+ test "it returns 500 if `invites_enabled` is not enabled", %{conn: conn} do
+ Config.put([:instance, :registrations_open], false)
+ Config.put([:instance, :invites_enabled], false)
+
+ conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
+
+ assert json_response(conn, :bad_request) ==
+ "To send invites you need to set the `invites_enabled` option to true."
+ end
+
+ test "it returns 500 if `registrations_open` is enabled", %{conn: conn} do
+ Config.put([:instance, :registrations_open], true)
+ Config.put([:instance, :invites_enabled], true)
+
+ conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
+
+ assert json_response(conn, :bad_request) ==
+ "To send invites you need to set the `registrations_open` option to false."
+ end
+ end
+
+ test "/api/pleroma/admin/users/:nickname/password_reset", %{conn: conn} do
+ user = insert(:user)
+
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> get("/api/pleroma/admin/users/#{user.nickname}/password_reset")
+
+ resp = json_response(conn, 200)
+
+ assert Regex.match?(~r/(http:\/\/|https:\/\/)/, resp["link"])
+ end
+
+ describe "GET /api/pleroma/admin/users" do
+ test "renders users array for the first page", %{conn: conn, admin: admin} do
+ user = insert(:user, local: false, tags: ["foo", "bar"])
+ conn = get(conn, "/api/pleroma/admin/users?page=1")
+
+ users =
+ [
+ %{
+ "deactivated" => admin.deactivated,
+ "id" => admin.id,
+ "nickname" => admin.nickname,
+ "roles" => %{"admin" => true, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(admin) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(admin.name || admin.nickname),
+ "confirmation_pending" => false
+ },
+ %{
+ "deactivated" => user.deactivated,
+ "id" => user.id,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => false,
+ "tags" => ["foo", "bar"],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ |> Enum.sort_by(& &1["nickname"])
+
+ assert json_response(conn, 200) == %{
+ "count" => 2,
+ "page_size" => 50,
+ "users" => users
+ }
+ end
+
+ test "pagination works correctly with service users", %{conn: conn} do
+ service1 = insert(:user, ap_id: Web.base_url() <> "/relay")
+ service2 = insert(:user, ap_id: Web.base_url() <> "/internal/fetch")
+ insert_list(25, :user)
+
+ assert %{"count" => 26, "page_size" => 10, "users" => users1} =
+ conn
+ |> get("/api/pleroma/admin/users?page=1&filters=", %{page_size: "10"})
+ |> json_response(200)
+
+ assert Enum.count(users1) == 10
+ assert service1 not in [users1]
+ assert service2 not in [users1]
+
+ assert %{"count" => 26, "page_size" => 10, "users" => users2} =
+ conn
+ |> get("/api/pleroma/admin/users?page=2&filters=", %{page_size: "10"})
+ |> json_response(200)
+
+ assert Enum.count(users2) == 10
+ assert service1 not in [users2]
+ assert service2 not in [users2]
+
+ assert %{"count" => 26, "page_size" => 10, "users" => users3} =
+ conn
+ |> get("/api/pleroma/admin/users?page=3&filters=", %{page_size: "10"})
+ |> json_response(200)
+
+ assert Enum.count(users3) == 6
+ assert service1 not in [users3]
+ assert service2 not in [users3]
+ end
+
+ test "renders empty array for the second page", %{conn: conn} do
+ insert(:user)
+
+ conn = get(conn, "/api/pleroma/admin/users?page=2")
+
+ assert json_response(conn, 200) == %{
+ "count" => 2,
+ "page_size" => 50,
+ "users" => []
+ }
+ end
+
+ test "regular search", %{conn: conn} do
+ user = insert(:user, nickname: "bob")
+
+ conn = get(conn, "/api/pleroma/admin/users?query=bo")
+
+ assert json_response(conn, 200) == %{
+ "count" => 1,
+ "page_size" => 50,
+ "users" => [
+ %{
+ "deactivated" => user.deactivated,
+ "id" => user.id,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ }
+ end
+
+ test "search by domain", %{conn: conn} do
+ user = insert(:user, nickname: "nickname@domain.com")
+ insert(:user)
+
+ conn = get(conn, "/api/pleroma/admin/users?query=domain.com")
+
+ assert json_response(conn, 200) == %{
+ "count" => 1,
+ "page_size" => 50,
+ "users" => [
+ %{
+ "deactivated" => user.deactivated,
+ "id" => user.id,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ }
+ end
+
+ test "search by full nickname", %{conn: conn} do
+ user = insert(:user, nickname: "nickname@domain.com")
+ insert(:user)
+
+ conn = get(conn, "/api/pleroma/admin/users?query=nickname@domain.com")
+
+ assert json_response(conn, 200) == %{
+ "count" => 1,
+ "page_size" => 50,
+ "users" => [
+ %{
+ "deactivated" => user.deactivated,
+ "id" => user.id,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ }
+ end
+
+ test "search by display name", %{conn: conn} do
+ user = insert(:user, name: "Display name")
+ insert(:user)
+
+ conn = get(conn, "/api/pleroma/admin/users?name=display")
+
+ assert json_response(conn, 200) == %{
+ "count" => 1,
+ "page_size" => 50,
+ "users" => [
+ %{
+ "deactivated" => user.deactivated,
+ "id" => user.id,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ }
+ end
+
+ test "search by email", %{conn: conn} do
+ user = insert(:user, email: "email@example.com")
+ insert(:user)
+
+ conn = get(conn, "/api/pleroma/admin/users?email=email@example.com")
+
+ assert json_response(conn, 200) == %{
+ "count" => 1,
+ "page_size" => 50,
+ "users" => [
+ %{
+ "deactivated" => user.deactivated,
+ "id" => user.id,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ }
+ end
+
+ test "regular search with page size", %{conn: conn} do
+ user = insert(:user, nickname: "aalice")
+ user2 = insert(:user, nickname: "alice")
+
+ conn1 = get(conn, "/api/pleroma/admin/users?query=a&page_size=1&page=1")
+
+ assert json_response(conn1, 200) == %{
+ "count" => 2,
+ "page_size" => 1,
+ "users" => [
+ %{
+ "deactivated" => user.deactivated,
+ "id" => user.id,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ }
+
+ conn2 = get(conn, "/api/pleroma/admin/users?query=a&page_size=1&page=2")
+
+ assert json_response(conn2, 200) == %{
+ "count" => 2,
+ "page_size" => 1,
+ "users" => [
+ %{
+ "deactivated" => user2.deactivated,
+ "id" => user2.id,
+ "nickname" => user2.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(user2) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user2.name || user2.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ }
+ end
+
+ test "only local users" do
+ admin = insert(:user, is_admin: true, nickname: "john")
+ token = insert(:oauth_admin_token, user: admin)
+ user = insert(:user, nickname: "bob")
+
+ insert(:user, nickname: "bobb", local: false)
+
+ conn =
+ build_conn()
+ |> assign(:user, admin)
+ |> assign(:token, token)
+ |> get("/api/pleroma/admin/users?query=bo&filters=local")
+
+ assert json_response(conn, 200) == %{
+ "count" => 1,
+ "page_size" => 50,
+ "users" => [
+ %{
+ "deactivated" => user.deactivated,
+ "id" => user.id,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ }
+ end
+
+ test "only local users with no query", %{conn: conn, admin: old_admin} do
+ admin = insert(:user, is_admin: true, nickname: "john")
+ user = insert(:user, nickname: "bob")
+
+ insert(:user, nickname: "bobb", local: false)
+
+ conn = get(conn, "/api/pleroma/admin/users?filters=local")
+
+ users =
+ [
+ %{
+ "deactivated" => user.deactivated,
+ "id" => user.id,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ },
+ %{
+ "deactivated" => admin.deactivated,
+ "id" => admin.id,
+ "nickname" => admin.nickname,
+ "roles" => %{"admin" => true, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(admin) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(admin.name || admin.nickname),
+ "confirmation_pending" => false
+ },
+ %{
+ "deactivated" => false,
+ "id" => old_admin.id,
+ "local" => true,
+ "nickname" => old_admin.nickname,
+ "roles" => %{"admin" => true, "moderator" => false},
+ "tags" => [],
+ "avatar" => User.avatar_url(old_admin) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(old_admin.name || old_admin.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ |> Enum.sort_by(& &1["nickname"])
+
+ assert json_response(conn, 200) == %{
+ "count" => 3,
+ "page_size" => 50,
+ "users" => users
+ }
+ end
+
+ test "load only admins", %{conn: conn, admin: admin} do
+ second_admin = insert(:user, is_admin: true)
+ insert(:user)
+ insert(:user)
+
+ conn = get(conn, "/api/pleroma/admin/users?filters=is_admin")
+
+ users =
+ [
+ %{
+ "deactivated" => false,
+ "id" => admin.id,
+ "nickname" => admin.nickname,
+ "roles" => %{"admin" => true, "moderator" => false},
+ "local" => admin.local,
+ "tags" => [],
+ "avatar" => User.avatar_url(admin) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(admin.name || admin.nickname),
+ "confirmation_pending" => false
+ },
+ %{
+ "deactivated" => false,
+ "id" => second_admin.id,
+ "nickname" => second_admin.nickname,
+ "roles" => %{"admin" => true, "moderator" => false},
+ "local" => second_admin.local,
+ "tags" => [],
+ "avatar" => User.avatar_url(second_admin) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(second_admin.name || second_admin.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ |> Enum.sort_by(& &1["nickname"])
+
+ assert json_response(conn, 200) == %{
+ "count" => 2,
+ "page_size" => 50,
+ "users" => users
+ }
+ end
+
+ test "load only moderators", %{conn: conn} do
+ moderator = insert(:user, is_moderator: true)
+ insert(:user)
+ insert(:user)
+
+ conn = get(conn, "/api/pleroma/admin/users?filters=is_moderator")
+
+ assert json_response(conn, 200) == %{
+ "count" => 1,
+ "page_size" => 50,
+ "users" => [
+ %{
+ "deactivated" => false,
+ "id" => moderator.id,
+ "nickname" => moderator.nickname,
+ "roles" => %{"admin" => false, "moderator" => true},
+ "local" => moderator.local,
+ "tags" => [],
+ "avatar" => User.avatar_url(moderator) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(moderator.name || moderator.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ }
+ end
+
+ test "load users with tags list", %{conn: conn} do
+ user1 = insert(:user, tags: ["first"])
+ user2 = insert(:user, tags: ["second"])
+ insert(:user)
+ insert(:user)
+
+ conn = get(conn, "/api/pleroma/admin/users?tags[]=first&tags[]=second")
+
+ users =
+ [
+ %{
+ "deactivated" => false,
+ "id" => user1.id,
+ "nickname" => user1.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => user1.local,
+ "tags" => ["first"],
+ "avatar" => User.avatar_url(user1) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user1.name || user1.nickname),
+ "confirmation_pending" => false
+ },
+ %{
+ "deactivated" => false,
+ "id" => user2.id,
+ "nickname" => user2.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => user2.local,
+ "tags" => ["second"],
+ "avatar" => User.avatar_url(user2) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user2.name || user2.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ |> Enum.sort_by(& &1["nickname"])
+
+ assert json_response(conn, 200) == %{
+ "count" => 2,
+ "page_size" => 50,
+ "users" => users
+ }
+ end
+
+ test "it works with multiple filters" do
+ admin = insert(:user, nickname: "john", is_admin: true)
+ token = insert(:oauth_admin_token, user: admin)
+ user = insert(:user, nickname: "bob", local: false, deactivated: true)
+
+ insert(:user, nickname: "ken", local: true, deactivated: true)
+ insert(:user, nickname: "bobb", local: false, deactivated: false)
+
+ conn =
+ build_conn()
+ |> assign(:user, admin)
+ |> assign(:token, token)
+ |> get("/api/pleroma/admin/users?filters=deactivated,external")
+
+ assert json_response(conn, 200) == %{
+ "count" => 1,
+ "page_size" => 50,
+ "users" => [
+ %{
+ "deactivated" => user.deactivated,
+ "id" => user.id,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => user.local,
+ "tags" => [],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ }
+ end
+
+ test "it omits relay user", %{admin: admin, conn: conn} do
+ assert %User{} = Relay.get_actor()
+
+ conn = get(conn, "/api/pleroma/admin/users")
+
+ assert json_response(conn, 200) == %{
+ "count" => 1,
+ "page_size" => 50,
+ "users" => [
+ %{
+ "deactivated" => admin.deactivated,
+ "id" => admin.id,
+ "nickname" => admin.nickname,
+ "roles" => %{"admin" => true, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(admin) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(admin.name || admin.nickname),
+ "confirmation_pending" => false
+ }
+ ]
+ }
+ end
+ end
+
+ test "PATCH /api/pleroma/admin/users/activate", %{admin: admin, conn: conn} do
+ user_one = insert(:user, deactivated: true)
+ user_two = insert(:user, deactivated: true)
+
+ conn =
+ patch(
+ conn,
+ "/api/pleroma/admin/users/activate",
+ %{nicknames: [user_one.nickname, user_two.nickname]}
+ )
+
+ response = json_response(conn, 200)
+ assert Enum.map(response["users"], & &1["deactivated"]) == [false, false]
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} activated users: @#{user_one.nickname}, @#{user_two.nickname}"
+ end
+
+ test "PATCH /api/pleroma/admin/users/deactivate", %{admin: admin, conn: conn} do
+ user_one = insert(:user, deactivated: false)
+ user_two = insert(:user, deactivated: false)
+
+ conn =
+ patch(
+ conn,
+ "/api/pleroma/admin/users/deactivate",
+ %{nicknames: [user_one.nickname, user_two.nickname]}
+ )
+
+ response = json_response(conn, 200)
+ assert Enum.map(response["users"], & &1["deactivated"]) == [true, true]
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} deactivated users: @#{user_one.nickname}, @#{user_two.nickname}"
+ end
+
+ test "PATCH /api/pleroma/admin/users/:nickname/toggle_activation", %{admin: admin, conn: conn} do
+ user = insert(:user)
+
+ conn = patch(conn, "/api/pleroma/admin/users/#{user.nickname}/toggle_activation")
+
+ assert json_response(conn, 200) ==
+ %{
+ "deactivated" => !user.deactivated,
+ "id" => user.id,
+ "nickname" => user.nickname,
+ "roles" => %{"admin" => false, "moderator" => false},
+ "local" => true,
+ "tags" => [],
+ "avatar" => User.avatar_url(user) |> MediaProxy.url(),
+ "display_name" => HTML.strip_tags(user.name || user.nickname),
+ "confirmation_pending" => false
+ }
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} deactivated users: @#{user.nickname}"
+ end
+
+ describe "PUT disable_mfa" do
+ test "returns 200 and disable 2fa", %{conn: conn} do
+ user =
+ insert(:user,
+ multi_factor_authentication_settings: %MFA.Settings{
+ enabled: true,
+ totp: %MFA.Settings.TOTP{secret: "otp_secret", confirmed: true}
+ }
+ )
+
+ response =
+ conn
+ |> put("/api/pleroma/admin/users/disable_mfa", %{nickname: user.nickname})
+ |> json_response(200)
+
+ assert response == user.nickname
+ mfa_settings = refresh_record(user).multi_factor_authentication_settings
+
+ refute mfa_settings.enabled
+ refute mfa_settings.totp.confirmed
+ end
+
+ test "returns 404 if user not found", %{conn: conn} do
+ response =
+ conn
+ |> put("/api/pleroma/admin/users/disable_mfa", %{nickname: "nickname"})
+ |> json_response(404)
+
+ assert response == "Not found"
+ end
+ end
+
+ describe "POST /api/pleroma/admin/users/invite_token" do
+ test "without options", %{conn: conn} do
+ conn = post(conn, "/api/pleroma/admin/users/invite_token")
+
+ invite_json = json_response(conn, 200)
+ invite = UserInviteToken.find_by_token!(invite_json["token"])
+ refute invite.used
+ refute invite.expires_at
+ refute invite.max_use
+ assert invite.invite_type == "one_time"
+ end
+
+ test "with expires_at", %{conn: conn} do
+ conn =
+ post(conn, "/api/pleroma/admin/users/invite_token", %{
+ "expires_at" => Date.to_string(Date.utc_today())
+ })
+
+ invite_json = json_response(conn, 200)
+ invite = UserInviteToken.find_by_token!(invite_json["token"])
+
+ refute invite.used
+ assert invite.expires_at == Date.utc_today()
+ refute invite.max_use
+ assert invite.invite_type == "date_limited"
+ end
+
+ test "with max_use", %{conn: conn} do
+ conn = post(conn, "/api/pleroma/admin/users/invite_token", %{"max_use" => 150})
+
+ invite_json = json_response(conn, 200)
+ invite = UserInviteToken.find_by_token!(invite_json["token"])
+ refute invite.used
+ refute invite.expires_at
+ assert invite.max_use == 150
+ assert invite.invite_type == "reusable"
+ end
+
+ test "with max use and expires_at", %{conn: conn} do
+ conn =
+ post(conn, "/api/pleroma/admin/users/invite_token", %{
+ "max_use" => 150,
+ "expires_at" => Date.to_string(Date.utc_today())
+ })
+
+ invite_json = json_response(conn, 200)
+ invite = UserInviteToken.find_by_token!(invite_json["token"])
+ refute invite.used
+ assert invite.expires_at == Date.utc_today()
+ assert invite.max_use == 150
+ assert invite.invite_type == "reusable_date_limited"
+ end
+ end
+
+ describe "GET /api/pleroma/admin/users/invites" do
+ test "no invites", %{conn: conn} do
+ conn = get(conn, "/api/pleroma/admin/users/invites")
+
+ assert json_response(conn, 200) == %{"invites" => []}
+ end
+
+ test "with invite", %{conn: conn} do
+ {:ok, invite} = UserInviteToken.create_invite()
+
+ conn = get(conn, "/api/pleroma/admin/users/invites")
+
+ assert json_response(conn, 200) == %{
+ "invites" => [
+ %{
+ "expires_at" => nil,
+ "id" => invite.id,
+ "invite_type" => "one_time",
+ "max_use" => nil,
+ "token" => invite.token,
+ "used" => false,
+ "uses" => 0
+ }
+ ]
+ }
+ end
+ end
+
+ describe "POST /api/pleroma/admin/users/revoke_invite" do
+ test "with token", %{conn: conn} do
+ {:ok, invite} = UserInviteToken.create_invite()
+
+ conn = post(conn, "/api/pleroma/admin/users/revoke_invite", %{"token" => invite.token})
+
+ assert json_response(conn, 200) == %{
+ "expires_at" => nil,
+ "id" => invite.id,
+ "invite_type" => "one_time",
+ "max_use" => nil,
+ "token" => invite.token,
+ "used" => true,
+ "uses" => 0
+ }
+ end
+
+ test "with invalid token", %{conn: conn} do
+ conn = post(conn, "/api/pleroma/admin/users/revoke_invite", %{"token" => "foo"})
+
+ assert json_response(conn, :not_found) == "Not found"
+ end
+ end
+
+ describe "GET /api/pleroma/admin/reports/:id" do
+ test "returns report by its id", %{conn: conn} do
+ [reporter, target_user] = insert_pair(:user)
+ activity = insert(:note_activity, user: target_user)
+
+ {:ok, %{id: report_id}} =
+ CommonAPI.report(reporter, %{
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
+ })
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/reports/#{report_id}")
+ |> json_response(:ok)
+
+ assert response["id"] == report_id
+ end
+
+ test "returns 404 when report id is invalid", %{conn: conn} do
+ conn = get(conn, "/api/pleroma/admin/reports/test")
+
+ assert json_response(conn, :not_found) == "Not found"
+ end
+ end
+
+ describe "PATCH /api/pleroma/admin/reports" do
+ setup do
+ [reporter, target_user] = insert_pair(:user)
+ activity = insert(:note_activity, user: target_user)
+
+ {:ok, %{id: report_id}} =
+ CommonAPI.report(reporter, %{
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
+ })
+
+ {:ok, %{id: second_report_id}} =
+ CommonAPI.report(reporter, %{
+ account_id: target_user.id,
+ comment: "I feel very offended",
+ status_ids: [activity.id]
+ })
+
+ %{
+ id: report_id,
+ second_report_id: second_report_id
+ }
+ end
+
+ test "requires admin:write:reports scope", %{conn: conn, id: id, admin: admin} do
+ read_token = insert(:oauth_token, user: admin, scopes: ["admin:read"])
+ write_token = insert(:oauth_token, user: admin, scopes: ["admin:write:reports"])
+
+ response =
+ conn
+ |> assign(:token, read_token)
+ |> patch("/api/pleroma/admin/reports", %{
+ "reports" => [%{"state" => "resolved", "id" => id}]
+ })
+ |> json_response(403)
+
+ assert response == %{
+ "error" => "Insufficient permissions: admin:write:reports."
+ }
+
+ conn
+ |> assign(:token, write_token)
+ |> patch("/api/pleroma/admin/reports", %{
+ "reports" => [%{"state" => "resolved", "id" => id}]
+ })
+ |> json_response(:no_content)
+ end
+
+ test "mark report as resolved", %{conn: conn, id: id, admin: admin} do
+ conn
+ |> patch("/api/pleroma/admin/reports", %{
+ "reports" => [
+ %{"state" => "resolved", "id" => id}
+ ]
+ })
+ |> json_response(:no_content)
+
+ activity = Activity.get_by_id(id)
+ assert activity.data["state"] == "resolved"
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} updated report ##{id} with 'resolved' state"
+ end
+
+ test "closes report", %{conn: conn, id: id, admin: admin} do
+ conn
+ |> patch("/api/pleroma/admin/reports", %{
+ "reports" => [
+ %{"state" => "closed", "id" => id}
+ ]
+ })
+ |> json_response(:no_content)
+
+ activity = Activity.get_by_id(id)
+ assert activity.data["state"] == "closed"
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} updated report ##{id} with 'closed' state"
+ end
+
+ test "returns 400 when state is unknown", %{conn: conn, id: id} do
+ conn =
+ conn
+ |> patch("/api/pleroma/admin/reports", %{
+ "reports" => [
+ %{"state" => "test", "id" => id}
+ ]
+ })
+
+ assert hd(json_response(conn, :bad_request))["error"] == "Unsupported state"
+ end
+
+ test "returns 404 when report is not exist", %{conn: conn} do
+ conn =
+ conn
+ |> patch("/api/pleroma/admin/reports", %{
+ "reports" => [
+ %{"state" => "closed", "id" => "test"}
+ ]
+ })
+
+ assert hd(json_response(conn, :bad_request))["error"] == "not_found"
+ end
+
+ test "updates state of multiple reports", %{
+ conn: conn,
+ id: id,
+ admin: admin,
+ second_report_id: second_report_id
+ } do
+ conn
+ |> patch("/api/pleroma/admin/reports", %{
+ "reports" => [
+ %{"state" => "resolved", "id" => id},
+ %{"state" => "closed", "id" => second_report_id}
+ ]
+ })
+ |> json_response(:no_content)
+
+ activity = Activity.get_by_id(id)
+ second_activity = Activity.get_by_id(second_report_id)
+ assert activity.data["state"] == "resolved"
+ assert second_activity.data["state"] == "closed"
+
+ [first_log_entry, second_log_entry] = Repo.all(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(first_log_entry) ==
+ "@#{admin.nickname} updated report ##{id} with 'resolved' state"
+
+ assert ModerationLog.get_log_entry_message(second_log_entry) ==
+ "@#{admin.nickname} updated report ##{second_report_id} with 'closed' state"
+ end
+ end
+
+ describe "GET /api/pleroma/admin/reports" do
+ test "returns empty response when no reports created", %{conn: conn} do
+ response =
+ conn
+ |> get("/api/pleroma/admin/reports")
+ |> json_response(:ok)
+
+ assert Enum.empty?(response["reports"])
+ assert response["total"] == 0
+ end
+
+ test "returns reports", %{conn: conn} do
+ [reporter, target_user] = insert_pair(:user)
+ activity = insert(:note_activity, user: target_user)
+
+ {:ok, %{id: report_id}} =
+ CommonAPI.report(reporter, %{
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
+ })
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/reports")
+ |> json_response(:ok)
+
+ [report] = response["reports"]
+
+ assert length(response["reports"]) == 1
+ assert report["id"] == report_id
+
+ assert response["total"] == 1
+ end
+
+ test "returns reports with specified state", %{conn: conn} do
+ [reporter, target_user] = insert_pair(:user)
+ activity = insert(:note_activity, user: target_user)
+
+ {:ok, %{id: first_report_id}} =
+ CommonAPI.report(reporter, %{
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
+ })
+
+ {:ok, %{id: second_report_id}} =
+ CommonAPI.report(reporter, %{
+ account_id: target_user.id,
+ comment: "I don't like this user"
+ })
+
+ CommonAPI.update_report_state(second_report_id, "closed")
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/reports", %{
+ "state" => "open"
+ })
+ |> json_response(:ok)
+
+ [open_report] = response["reports"]
+
+ assert length(response["reports"]) == 1
+ assert open_report["id"] == first_report_id
+
+ assert response["total"] == 1
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/reports", %{
+ "state" => "closed"
+ })
+ |> json_response(:ok)
+
+ [closed_report] = response["reports"]
+
+ assert length(response["reports"]) == 1
+ assert closed_report["id"] == second_report_id
+
+ assert response["total"] == 1
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/reports", %{
+ "state" => "resolved"
+ })
+ |> json_response(:ok)
+
+ assert Enum.empty?(response["reports"])
+ assert response["total"] == 0
+ end
+
+ test "returns 403 when requested by a non-admin" do
+ user = insert(:user)
+ token = insert(:oauth_token, user: user)
+
+ conn =
+ build_conn()
+ |> assign(:user, user)
+ |> assign(:token, token)
+ |> get("/api/pleroma/admin/reports")
+
+ assert json_response(conn, :forbidden) ==
+ %{"error" => "User is not an admin or OAuth admin scope is not granted."}
+ end
+
+ test "returns 403 when requested by anonymous" do
+ conn = get(build_conn(), "/api/pleroma/admin/reports")
+
+ assert json_response(conn, :forbidden) == %{"error" => "Invalid credentials."}
+ end
+ end
+
+ describe "GET /api/pleroma/admin/config" do
+ setup do: clear_config(:configurable_from_database, true)
+
+ test "when configuration from database is off", %{conn: conn} do
+ Config.put(:configurable_from_database, false)
+ conn = get(conn, "/api/pleroma/admin/config")
+
+ assert json_response(conn, 400) ==
+ "To use this endpoint you need to enable configuration from database."
+ end
+
+ test "with settings only in db", %{conn: conn} do
+ config1 = insert(:config)
+ config2 = insert(:config)
+
+ conn = get(conn, "/api/pleroma/admin/config", %{"only_db" => true})
+
+ %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => key1,
+ "value" => _
+ },
+ %{
+ "group" => ":pleroma",
+ "key" => key2,
+ "value" => _
+ }
+ ]
+ } = json_response(conn, 200)
+
+ assert key1 == config1.key
+ assert key2 == config2.key
+ end
+
+ test "db is added to settings that are in db", %{conn: conn} do
+ _config = insert(:config, key: ":instance", value: ConfigDB.to_binary(name: "Some name"))
+
+ %{"configs" => configs} =
+ conn
+ |> get("/api/pleroma/admin/config")
+ |> json_response(200)
+
+ [instance_config] =
+ Enum.filter(configs, fn %{"group" => group, "key" => key} ->
+ group == ":pleroma" and key == ":instance"
+ end)
+
+ assert instance_config["db"] == [":name"]
+ end
+
+ test "merged default setting with db settings", %{conn: conn} do
+ config1 = insert(:config)
+ config2 = insert(:config)
+
+ config3 =
+ insert(:config,
+ value: ConfigDB.to_binary(k1: :v1, k2: :v2)
+ )
+
+ %{"configs" => configs} =
+ conn
+ |> get("/api/pleroma/admin/config")
+ |> json_response(200)
+
+ assert length(configs) > 3
+
+ received_configs =
+ Enum.filter(configs, fn %{"group" => group, "key" => key} ->
+ group == ":pleroma" and key in [config1.key, config2.key, config3.key]
+ end)
+
+ assert length(received_configs) == 3
+
+ db_keys =
+ config3.value
+ |> ConfigDB.from_binary()
+ |> Keyword.keys()
+ |> ConfigDB.convert()
+
+ Enum.each(received_configs, fn %{"value" => value, "db" => db} ->
+ assert db in [[config1.key], [config2.key], db_keys]
+
+ assert value in [
+ ConfigDB.from_binary_with_convert(config1.value),
+ ConfigDB.from_binary_with_convert(config2.value),
+ ConfigDB.from_binary_with_convert(config3.value)
+ ]
+ end)
+ end
+
+ test "subkeys with full update right merge", %{conn: conn} do
+ config1 =
+ insert(:config,
+ key: ":emoji",
+ value: ConfigDB.to_binary(groups: [a: 1, b: 2], key: [a: 1])
+ )
+
+ config2 =
+ insert(:config,
+ key: ":assets",
+ value: ConfigDB.to_binary(mascots: [a: 1, b: 2], key: [a: 1])
+ )
+
+ %{"configs" => configs} =
+ conn
+ |> get("/api/pleroma/admin/config")
+ |> json_response(200)
+
+ vals =
+ Enum.filter(configs, fn %{"group" => group, "key" => key} ->
+ group == ":pleroma" and key in [config1.key, config2.key]
+ end)
+
+ emoji = Enum.find(vals, fn %{"key" => key} -> key == ":emoji" end)
+ assets = Enum.find(vals, fn %{"key" => key} -> key == ":assets" end)
+
+ emoji_val = ConfigDB.transform_with_out_binary(emoji["value"])
+ assets_val = ConfigDB.transform_with_out_binary(assets["value"])
+
+ assert emoji_val[:groups] == [a: 1, b: 2]
+ assert assets_val[:mascots] == [a: 1, b: 2]
+ end
+ end
+
+ test "POST /api/pleroma/admin/config error", %{conn: conn} do
+ conn = post(conn, "/api/pleroma/admin/config", %{"configs" => []})
+
+ assert json_response(conn, 400) ==
+ "To use this endpoint you need to enable configuration from database."
+ end
+
+ describe "POST /api/pleroma/admin/config" do
+ setup do
+ http = Application.get_env(:pleroma, :http)
+
+ on_exit(fn ->
+ Application.delete_env(:pleroma, :key1)
+ Application.delete_env(:pleroma, :key2)
+ Application.delete_env(:pleroma, :key3)
+ Application.delete_env(:pleroma, :key4)
+ Application.delete_env(:pleroma, :keyaa1)
+ Application.delete_env(:pleroma, :keyaa2)
+ Application.delete_env(:pleroma, Pleroma.Web.Endpoint.NotReal)
+ Application.delete_env(:pleroma, Pleroma.Captcha.NotReal)
+ Application.put_env(:pleroma, :http, http)
+ Application.put_env(:tesla, :adapter, Tesla.Mock)
+ Restarter.Pleroma.refresh()
+ end)
+ end
+
+ setup do: clear_config(:configurable_from_database, true)
+
+ @tag capture_log: true
+ test "create new config setting in db", %{conn: conn} do
+ ueberauth = Application.get_env(:ueberauth, Ueberauth)
+ on_exit(fn -> Application.put_env(:ueberauth, Ueberauth, ueberauth) end)
+
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{group: ":pleroma", key: ":key1", value: "value1"},
+ %{
+ group: ":ueberauth",
+ key: "Ueberauth",
+ value: [%{"tuple" => [":consumer_secret", "aaaa"]}]
+ },
+ %{
+ group: ":pleroma",
+ key: ":key2",
+ value: %{
+ ":nested_1" => "nested_value1",
+ ":nested_2" => [
+ %{":nested_22" => "nested_value222"},
+ %{":nested_33" => %{":nested_44" => "nested_444"}}
+ ]
+ }
+ },
+ %{
+ group: ":pleroma",
+ key: ":key3",
+ value: [
+ %{"nested_3" => ":nested_3", "nested_33" => "nested_33"},
+ %{"nested_4" => true}
+ ]
+ },
+ %{
+ group: ":pleroma",
+ key: ":key4",
+ value: %{":nested_5" => ":upload", "endpoint" => "https://example.com"}
+ },
+ %{
+ group: ":idna",
+ key: ":key5",
+ value: %{"tuple" => ["string", "Pleroma.Captcha.NotReal", []]}
+ }
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":key1",
+ "value" => "value1",
+ "db" => [":key1"]
+ },
+ %{
+ "group" => ":ueberauth",
+ "key" => "Ueberauth",
+ "value" => [%{"tuple" => [":consumer_secret", "aaaa"]}],
+ "db" => [":consumer_secret"]
+ },
+ %{
+ "group" => ":pleroma",
+ "key" => ":key2",
+ "value" => %{
+ ":nested_1" => "nested_value1",
+ ":nested_2" => [
+ %{":nested_22" => "nested_value222"},
+ %{":nested_33" => %{":nested_44" => "nested_444"}}
+ ]
+ },
+ "db" => [":key2"]
+ },
+ %{
+ "group" => ":pleroma",
+ "key" => ":key3",
+ "value" => [
+ %{"nested_3" => ":nested_3", "nested_33" => "nested_33"},
+ %{"nested_4" => true}
+ ],
+ "db" => [":key3"]
+ },
+ %{
+ "group" => ":pleroma",
+ "key" => ":key4",
+ "value" => %{"endpoint" => "https://example.com", ":nested_5" => ":upload"},
+ "db" => [":key4"]
+ },
+ %{
+ "group" => ":idna",
+ "key" => ":key5",
+ "value" => %{"tuple" => ["string", "Pleroma.Captcha.NotReal", []]},
+ "db" => [":key5"]
+ }
+ ]
+ }
+
+ assert Application.get_env(:pleroma, :key1) == "value1"
+
+ assert Application.get_env(:pleroma, :key2) == %{
+ nested_1: "nested_value1",
+ nested_2: [
+ %{nested_22: "nested_value222"},
+ %{nested_33: %{nested_44: "nested_444"}}
+ ]
+ }
+
+ assert Application.get_env(:pleroma, :key3) == [
+ %{"nested_3" => :nested_3, "nested_33" => "nested_33"},
+ %{"nested_4" => true}
+ ]
+
+ assert Application.get_env(:pleroma, :key4) == %{
+ "endpoint" => "https://example.com",
+ nested_5: :upload
+ }
+
+ assert Application.get_env(:idna, :key5) == {"string", Pleroma.Captcha.NotReal, []}
+ end
+
+ test "save configs setting without explicit key", %{conn: conn} do
+ level = Application.get_env(:quack, :level)
+ meta = Application.get_env(:quack, :meta)
+ webhook_url = Application.get_env(:quack, :webhook_url)
+
+ on_exit(fn ->
+ Application.put_env(:quack, :level, level)
+ Application.put_env(:quack, :meta, meta)
+ Application.put_env(:quack, :webhook_url, webhook_url)
+ end)
+
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ group: ":quack",
+ key: ":level",
+ value: ":info"
+ },
+ %{
+ group: ":quack",
+ key: ":meta",
+ value: [":none"]
+ },
+ %{
+ group: ":quack",
+ key: ":webhook_url",
+ value: "https://hooks.slack.com/services/KEY"
+ }
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":quack",
+ "key" => ":level",
+ "value" => ":info",
+ "db" => [":level"]
+ },
+ %{
+ "group" => ":quack",
+ "key" => ":meta",
+ "value" => [":none"],
+ "db" => [":meta"]
+ },
+ %{
+ "group" => ":quack",
+ "key" => ":webhook_url",
+ "value" => "https://hooks.slack.com/services/KEY",
+ "db" => [":webhook_url"]
+ }
+ ]
+ }
+
+ assert Application.get_env(:quack, :level) == :info
+ assert Application.get_env(:quack, :meta) == [:none]
+ assert Application.get_env(:quack, :webhook_url) == "https://hooks.slack.com/services/KEY"
+ end
+
+ test "saving config with partial update", %{conn: conn} do
+ config = insert(:config, key: ":key1", value: :erlang.term_to_binary(key1: 1, key2: 2))
+
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{group: config.group, key: config.key, value: [%{"tuple" => [":key3", 3]}]}
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":key1",
+ "value" => [
+ %{"tuple" => [":key1", 1]},
+ %{"tuple" => [":key2", 2]},
+ %{"tuple" => [":key3", 3]}
+ ],
+ "db" => [":key1", ":key2", ":key3"]
+ }
+ ]
+ }
+ end
+
+ test "saving config which need pleroma reboot", %{conn: conn} do
+ chat = Config.get(:chat)
+ on_exit(fn -> Config.put(:chat, chat) end)
+
+ assert post(
+ conn,
+ "/api/pleroma/admin/config",
+ %{
+ configs: [
+ %{group: ":pleroma", key: ":chat", value: [%{"tuple" => [":enabled", true]}]}
+ ]
+ }
+ )
+ |> json_response(200) == %{
+ "configs" => [
+ %{
+ "db" => [":enabled"],
+ "group" => ":pleroma",
+ "key" => ":chat",
+ "value" => [%{"tuple" => [":enabled", true]}]
+ }
+ ],
+ "need_reboot" => true
+ }
+
+ configs =
+ conn
+ |> get("/api/pleroma/admin/config")
+ |> json_response(200)
+
+ assert configs["need_reboot"]
+
+ capture_log(fn ->
+ assert conn |> get("/api/pleroma/admin/restart") |> json_response(200) == %{}
+ end) =~ "pleroma restarted"
+
+ configs =
+ conn
+ |> get("/api/pleroma/admin/config")
+ |> json_response(200)
+
+ assert configs["need_reboot"] == false
+ end
+
+ test "update setting which need reboot, don't change reboot flag until reboot", %{conn: conn} do
+ chat = Config.get(:chat)
+ on_exit(fn -> Config.put(:chat, chat) end)
+
+ assert post(
+ conn,
+ "/api/pleroma/admin/config",
+ %{
+ configs: [
+ %{group: ":pleroma", key: ":chat", value: [%{"tuple" => [":enabled", true]}]}
+ ]
+ }
+ )
+ |> json_response(200) == %{
+ "configs" => [
+ %{
+ "db" => [":enabled"],
+ "group" => ":pleroma",
+ "key" => ":chat",
+ "value" => [%{"tuple" => [":enabled", true]}]
+ }
+ ],
+ "need_reboot" => true
+ }
+
+ assert post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{group: ":pleroma", key: ":key1", value: [%{"tuple" => [":key3", 3]}]}
+ ]
+ })
+ |> json_response(200) == %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":key1",
+ "value" => [
+ %{"tuple" => [":key3", 3]}
+ ],
+ "db" => [":key3"]
+ }
+ ],
+ "need_reboot" => true
+ }
+
+ capture_log(fn ->
+ assert conn |> get("/api/pleroma/admin/restart") |> json_response(200) == %{}
+ end) =~ "pleroma restarted"
+
+ configs =
+ conn
+ |> get("/api/pleroma/admin/config")
+ |> json_response(200)
+
+ assert configs["need_reboot"] == false
+ end
+
+ test "saving config with nested merge", %{conn: conn} do
+ config =
+ insert(:config, key: ":key1", value: :erlang.term_to_binary(key1: 1, key2: [k1: 1, k2: 2]))
+
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ group: config.group,
+ key: config.key,
+ value: [
+ %{"tuple" => [":key3", 3]},
+ %{
+ "tuple" => [
+ ":key2",
+ [
+ %{"tuple" => [":k2", 1]},
+ %{"tuple" => [":k3", 3]}
+ ]
+ ]
+ }
+ ]
+ }
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":key1",
+ "value" => [
+ %{"tuple" => [":key1", 1]},
+ %{"tuple" => [":key3", 3]},
+ %{
+ "tuple" => [
+ ":key2",
+ [
+ %{"tuple" => [":k1", 1]},
+ %{"tuple" => [":k2", 1]},
+ %{"tuple" => [":k3", 3]}
+ ]
+ ]
+ }
+ ],
+ "db" => [":key1", ":key3", ":key2"]
+ }
+ ]
+ }
+ end
+
+ test "saving special atoms", %{conn: conn} do
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":key1",
+ "value" => [
+ %{
+ "tuple" => [
+ ":ssl_options",
+ [%{"tuple" => [":versions", [":tlsv1", ":tlsv1.1", ":tlsv1.2"]]}]
+ ]
+ }
+ ]
+ }
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":key1",
+ "value" => [
+ %{
+ "tuple" => [
+ ":ssl_options",
+ [%{"tuple" => [":versions", [":tlsv1", ":tlsv1.1", ":tlsv1.2"]]}]
+ ]
+ }
+ ],
+ "db" => [":ssl_options"]
+ }
+ ]
+ }
+
+ assert Application.get_env(:pleroma, :key1) == [
+ ssl_options: [versions: [:tlsv1, :"tlsv1.1", :"tlsv1.2"]]
+ ]
+ end
+
+ test "saving full setting if value is in full_key_update list", %{conn: conn} do
+ backends = Application.get_env(:logger, :backends)
+ on_exit(fn -> Application.put_env(:logger, :backends, backends) end)
+
+ config =
+ insert(:config,
+ group: ":logger",
+ key: ":backends",
+ value: :erlang.term_to_binary([])
+ )
+
+ Pleroma.Config.TransferTask.load_and_update_env([], false)
+
+ assert Application.get_env(:logger, :backends) == []
+
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ group: config.group,
+ key: config.key,
+ value: [":console"]
+ }
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":logger",
+ "key" => ":backends",
+ "value" => [
+ ":console"
+ ],
+ "db" => [":backends"]
+ }
+ ]
+ }
+
+ assert Application.get_env(:logger, :backends) == [
+ :console
+ ]
+ end
+
+ test "saving full setting if value is not keyword", %{conn: conn} do
+ config =
+ insert(:config,
+ group: ":tesla",
+ key: ":adapter",
+ value: :erlang.term_to_binary(Tesla.Adapter.Hackey)
+ )
+
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{group: config.group, key: config.key, value: "Tesla.Adapter.Httpc"}
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":tesla",
+ "key" => ":adapter",
+ "value" => "Tesla.Adapter.Httpc",
+ "db" => [":adapter"]
+ }
+ ]
+ }
+ end
+
+ test "update config setting & delete with fallback to default value", %{
+ conn: conn,
+ admin: admin,
+ token: token
+ } do
+ ueberauth = Application.get_env(:ueberauth, Ueberauth)
+ config1 = insert(:config, key: ":keyaa1")
+ config2 = insert(:config, key: ":keyaa2")
+
+ config3 =
+ insert(:config,
+ group: ":ueberauth",
+ key: "Ueberauth"
+ )
+
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{group: config1.group, key: config1.key, value: "another_value"},
+ %{group: config2.group, key: config2.key, value: "another_value"}
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => config1.key,
+ "value" => "another_value",
+ "db" => [":keyaa1"]
+ },
+ %{
+ "group" => ":pleroma",
+ "key" => config2.key,
+ "value" => "another_value",
+ "db" => [":keyaa2"]
+ }
+ ]
+ }
+
+ assert Application.get_env(:pleroma, :keyaa1) == "another_value"
+ assert Application.get_env(:pleroma, :keyaa2) == "another_value"
+ assert Application.get_env(:ueberauth, Ueberauth) == ConfigDB.from_binary(config3.value)
+
+ conn =
+ build_conn()
+ |> assign(:user, admin)
+ |> assign(:token, token)
+ |> post("/api/pleroma/admin/config", %{
+ configs: [
+ %{group: config2.group, key: config2.key, delete: true},
+ %{
+ group: ":ueberauth",
+ key: "Ueberauth",
+ delete: true
+ }
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => []
+ }
+
+ assert Application.get_env(:ueberauth, Ueberauth) == ueberauth
+ refute Keyword.has_key?(Application.get_all_env(:pleroma), :keyaa2)
+ end
+
+ test "common config example", %{conn: conn} do
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ "group" => ":pleroma",
+ "key" => "Pleroma.Captcha.NotReal",
+ "value" => [
+ %{"tuple" => [":enabled", false]},
+ %{"tuple" => [":method", "Pleroma.Captcha.Kocaptcha"]},
+ %{"tuple" => [":seconds_valid", 60]},
+ %{"tuple" => [":path", ""]},
+ %{"tuple" => [":key1", nil]},
+ %{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]},
+ %{"tuple" => [":regex1", "~r/https:\/\/example.com/"]},
+ %{"tuple" => [":regex2", "~r/https:\/\/example.com/u"]},
+ %{"tuple" => [":regex3", "~r/https:\/\/example.com/i"]},
+ %{"tuple" => [":regex4", "~r/https:\/\/example.com/s"]},
+ %{"tuple" => [":name", "Pleroma"]}
+ ]
+ }
+ ]
+ })
+
+ assert Config.get([Pleroma.Captcha.NotReal, :name]) == "Pleroma"
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => "Pleroma.Captcha.NotReal",
+ "value" => [
+ %{"tuple" => [":enabled", false]},
+ %{"tuple" => [":method", "Pleroma.Captcha.Kocaptcha"]},
+ %{"tuple" => [":seconds_valid", 60]},
+ %{"tuple" => [":path", ""]},
+ %{"tuple" => [":key1", nil]},
+ %{"tuple" => [":partial_chain", "&:hackney_connect.partial_chain/1"]},
+ %{"tuple" => [":regex1", "~r/https:\\/\\/example.com/"]},
+ %{"tuple" => [":regex2", "~r/https:\\/\\/example.com/u"]},
+ %{"tuple" => [":regex3", "~r/https:\\/\\/example.com/i"]},
+ %{"tuple" => [":regex4", "~r/https:\\/\\/example.com/s"]},
+ %{"tuple" => [":name", "Pleroma"]}
+ ],
+ "db" => [
+ ":enabled",
+ ":method",
+ ":seconds_valid",
+ ":path",
+ ":key1",
+ ":partial_chain",
+ ":regex1",
+ ":regex2",
+ ":regex3",
+ ":regex4",
+ ":name"
+ ]
+ }
+ ]
+ }
+ end
+
+ test "tuples with more than two values", %{conn: conn} do
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ "group" => ":pleroma",
+ "key" => "Pleroma.Web.Endpoint.NotReal",
+ "value" => [
+ %{
+ "tuple" => [
+ ":http",
+ [
+ %{
+ "tuple" => [
+ ":key2",
+ [
+ %{
+ "tuple" => [
+ ":_",
+ [
+ %{
+ "tuple" => [
+ "/api/v1/streaming",
+ "Pleroma.Web.MastodonAPI.WebsocketHandler",
+ []
+ ]
+ },
+ %{
+ "tuple" => [
+ "/websocket",
+ "Phoenix.Endpoint.CowboyWebSocket",
+ %{
+ "tuple" => [
+ "Phoenix.Transports.WebSocket",
+ %{
+ "tuple" => [
+ "Pleroma.Web.Endpoint",
+ "Pleroma.Web.UserSocket",
+ []
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ %{
+ "tuple" => [
+ ":_",
+ "Phoenix.Endpoint.Cowboy2Handler",
+ %{"tuple" => ["Pleroma.Web.Endpoint", []]}
+ ]
+ }
+ ]
+ ]
+ }
+ ]
+ ]
+ }
+ ]
+ ]
+ }
+ ]
+ }
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => "Pleroma.Web.Endpoint.NotReal",
+ "value" => [
+ %{
+ "tuple" => [
+ ":http",
+ [
+ %{
+ "tuple" => [
+ ":key2",
+ [
+ %{
+ "tuple" => [
+ ":_",
+ [
+ %{
+ "tuple" => [
+ "/api/v1/streaming",
+ "Pleroma.Web.MastodonAPI.WebsocketHandler",
+ []
+ ]
+ },
+ %{
+ "tuple" => [
+ "/websocket",
+ "Phoenix.Endpoint.CowboyWebSocket",
+ %{
+ "tuple" => [
+ "Phoenix.Transports.WebSocket",
+ %{
+ "tuple" => [
+ "Pleroma.Web.Endpoint",
+ "Pleroma.Web.UserSocket",
+ []
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ %{
+ "tuple" => [
+ ":_",
+ "Phoenix.Endpoint.Cowboy2Handler",
+ %{"tuple" => ["Pleroma.Web.Endpoint", []]}
+ ]
+ }
+ ]
+ ]
+ }
+ ]
+ ]
+ }
+ ]
+ ]
+ }
+ ],
+ "db" => [":http"]
+ }
+ ]
+ }
+ end
+
+ test "settings with nesting map", %{conn: conn} do
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ "group" => ":pleroma",
+ "key" => ":key1",
+ "value" => [
+ %{"tuple" => [":key2", "some_val"]},
+ %{
+ "tuple" => [
+ ":key3",
+ %{
+ ":max_options" => 20,
+ ":max_option_chars" => 200,
+ ":min_expiration" => 0,
+ ":max_expiration" => 31_536_000,
+ "nested" => %{
+ ":max_options" => 20,
+ ":max_option_chars" => 200,
+ ":min_expiration" => 0,
+ ":max_expiration" => 31_536_000
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ })
+
+ assert json_response(conn, 200) ==
+ %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":key1",
+ "value" => [
+ %{"tuple" => [":key2", "some_val"]},
+ %{
+ "tuple" => [
+ ":key3",
+ %{
+ ":max_expiration" => 31_536_000,
+ ":max_option_chars" => 200,
+ ":max_options" => 20,
+ ":min_expiration" => 0,
+ "nested" => %{
+ ":max_expiration" => 31_536_000,
+ ":max_option_chars" => 200,
+ ":max_options" => 20,
+ ":min_expiration" => 0
+ }
+ }
+ ]
+ }
+ ],
+ "db" => [":key2", ":key3"]
+ }
+ ]
+ }
+ end
+
+ test "value as map", %{conn: conn} do
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ "group" => ":pleroma",
+ "key" => ":key1",
+ "value" => %{"key" => "some_val"}
+ }
+ ]
+ })
+
+ assert json_response(conn, 200) ==
+ %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":key1",
+ "value" => %{"key" => "some_val"},
+ "db" => [":key1"]
+ }
+ ]
+ }
+ end
+
+ test "queues key as atom", %{conn: conn} do
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ "group" => ":oban",
+ "key" => ":queues",
+ "value" => [
+ %{"tuple" => [":federator_incoming", 50]},
+ %{"tuple" => [":federator_outgoing", 50]},
+ %{"tuple" => [":web_push", 50]},
+ %{"tuple" => [":mailer", 10]},
+ %{"tuple" => [":transmogrifier", 20]},
+ %{"tuple" => [":scheduled_activities", 10]},
+ %{"tuple" => [":background", 5]}
+ ]
+ }
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":oban",
+ "key" => ":queues",
+ "value" => [
+ %{"tuple" => [":federator_incoming", 50]},
+ %{"tuple" => [":federator_outgoing", 50]},
+ %{"tuple" => [":web_push", 50]},
+ %{"tuple" => [":mailer", 10]},
+ %{"tuple" => [":transmogrifier", 20]},
+ %{"tuple" => [":scheduled_activities", 10]},
+ %{"tuple" => [":background", 5]}
+ ],
+ "db" => [
+ ":federator_incoming",
+ ":federator_outgoing",
+ ":web_push",
+ ":mailer",
+ ":transmogrifier",
+ ":scheduled_activities",
+ ":background"
+ ]
+ }
+ ]
+ }
+ end
+
+ test "delete part of settings by atom subkeys", %{conn: conn} do
+ config =
+ insert(:config,
+ key: ":keyaa1",
+ value: :erlang.term_to_binary(subkey1: "val1", subkey2: "val2", subkey3: "val3")
+ )
+
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ group: config.group,
+ key: config.key,
+ subkeys: [":subkey1", ":subkey3"],
+ delete: true
+ }
+ ]
+ })
+
+ assert json_response(conn, 200) == %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":keyaa1",
+ "value" => [%{"tuple" => [":subkey2", "val2"]}],
+ "db" => [":subkey2"]
+ }
+ ]
+ }
+ end
+
+ test "proxy tuple localhost", %{conn: conn} do
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ group: ":pleroma",
+ key: ":http",
+ value: [
+ %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "localhost", 1234]}]}
+ ]
+ }
+ ]
+ })
+
+ assert %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":http",
+ "value" => value,
+ "db" => db
+ }
+ ]
+ } = json_response(conn, 200)
+
+ assert %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "localhost", 1234]}]} in value
+ assert ":proxy_url" in db
+ end
+
+ test "proxy tuple domain", %{conn: conn} do
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ group: ":pleroma",
+ key: ":http",
+ value: [
+ %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "domain.com", 1234]}]}
+ ]
+ }
+ ]
+ })
+
+ assert %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":http",
+ "value" => value,
+ "db" => db
+ }
+ ]
+ } = json_response(conn, 200)
+
+ assert %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "domain.com", 1234]}]} in value
+ assert ":proxy_url" in db
+ end
+
+ test "proxy tuple ip", %{conn: conn} do
+ conn =
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{
+ group: ":pleroma",
+ key: ":http",
+ value: [
+ %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "127.0.0.1", 1234]}]}
+ ]
+ }
+ ]
+ })
+
+ assert %{
+ "configs" => [
+ %{
+ "group" => ":pleroma",
+ "key" => ":http",
+ "value" => value,
+ "db" => db
+ }
+ ]
+ } = json_response(conn, 200)
+
+ assert %{"tuple" => [":proxy_url", %{"tuple" => [":socks5", "127.0.0.1", 1234]}]} in value
+ assert ":proxy_url" in db
+ end
+
+ test "doesn't set keys not in the whitelist", %{conn: conn} do
+ clear_config(:database_config_whitelist, [
+ {:pleroma, :key1},
+ {:pleroma, :key2},
+ {:pleroma, Pleroma.Captcha.NotReal},
+ {:not_real}
+ ])
+
+ post(conn, "/api/pleroma/admin/config", %{
+ configs: [
+ %{group: ":pleroma", key: ":key1", value: "value1"},
+ %{group: ":pleroma", key: ":key2", value: "value2"},
+ %{group: ":pleroma", key: ":key3", value: "value3"},
+ %{group: ":pleroma", key: "Pleroma.Web.Endpoint.NotReal", value: "value4"},
+ %{group: ":pleroma", key: "Pleroma.Captcha.NotReal", value: "value5"},
+ %{group: ":not_real", key: ":anything", value: "value6"}
+ ]
+ })
+
+ assert Application.get_env(:pleroma, :key1) == "value1"
+ assert Application.get_env(:pleroma, :key2) == "value2"
+ assert Application.get_env(:pleroma, :key3) == nil
+ assert Application.get_env(:pleroma, Pleroma.Web.Endpoint.NotReal) == nil
+ assert Application.get_env(:pleroma, Pleroma.Captcha.NotReal) == "value5"
+ assert Application.get_env(:not_real, :anything) == "value6"
+ end
+ end
+
+ describe "GET /api/pleroma/admin/restart" do
+ setup do: clear_config(:configurable_from_database, true)
+
+ test "pleroma restarts", %{conn: conn} do
+ capture_log(fn ->
+ assert conn |> get("/api/pleroma/admin/restart") |> json_response(200) == %{}
+ end) =~ "pleroma restarted"
+
+ refute Restarter.Pleroma.need_reboot?()
+ end
+ end
+
+ test "need_reboot flag", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/admin/need_reboot")
+ |> json_response(200) == %{"need_reboot" => false}
+
+ Restarter.Pleroma.need_reboot()
+
+ assert conn
+ |> get("/api/pleroma/admin/need_reboot")
+ |> json_response(200) == %{"need_reboot" => true}
+
+ on_exit(fn -> Restarter.Pleroma.refresh() end)
+ end
+
+ describe "GET /api/pleroma/admin/users/:nickname/statuses" do
+ setup do
+ user = insert(:user)
+
+ date1 = (DateTime.to_unix(DateTime.utc_now()) + 2000) |> DateTime.from_unix!()
+ date2 = (DateTime.to_unix(DateTime.utc_now()) + 1000) |> DateTime.from_unix!()
+ date3 = (DateTime.to_unix(DateTime.utc_now()) + 3000) |> DateTime.from_unix!()
+
+ insert(:note_activity, user: user, published: date1)
+ insert(:note_activity, user: user, published: date2)
+ insert(:note_activity, user: user, published: date3)
+
+ %{user: user}
+ end
+
+ test "renders user's statuses", %{conn: conn, user: user} do
+ conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses")
+
+ assert json_response(conn, 200) |> length() == 3
+ end
+
+ test "renders user's statuses with a limit", %{conn: conn, user: user} do
+ conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses?page_size=2")
+
+ assert json_response(conn, 200) |> length() == 2
+ end
+
+ test "doesn't return private statuses by default", %{conn: conn, user: user} do
+ {:ok, _private_status} = CommonAPI.post(user, %{status: "private", visibility: "private"})
+
+ {:ok, _public_status} = CommonAPI.post(user, %{status: "public", visibility: "public"})
+
+ conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses")
+
+ assert json_response(conn, 200) |> length() == 4
+ end
+
+ test "returns private statuses with godmode on", %{conn: conn, user: user} do
+ {:ok, _private_status} = CommonAPI.post(user, %{status: "private", visibility: "private"})
+
+ {:ok, _public_status} = CommonAPI.post(user, %{status: "public", visibility: "public"})
+
+ conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses?godmode=true")
+
+ assert json_response(conn, 200) |> length() == 5
+ end
+
+ test "excludes reblogs by default", %{conn: conn, user: user} do
+ other_user = insert(:user)
+ {:ok, activity} = CommonAPI.post(user, %{status: "."})
+ {:ok, %Activity{}, _} = CommonAPI.repeat(activity.id, other_user)
+
+ conn_res = get(conn, "/api/pleroma/admin/users/#{other_user.nickname}/statuses")
+ assert json_response(conn_res, 200) |> length() == 0
+
+ conn_res =
+ get(conn, "/api/pleroma/admin/users/#{other_user.nickname}/statuses?with_reblogs=true")
+
+ assert json_response(conn_res, 200) |> length() == 1
+ end
+ end
+
+ describe "GET /api/pleroma/admin/moderation_log" do
+ setup do
+ moderator = insert(:user, is_moderator: true)
+
+ %{moderator: moderator}
+ end
+
+ test "returns the log", %{conn: conn, admin: admin} do
+ Repo.insert(%ModerationLog{
+ data: %{
+ actor: %{
+ "id" => admin.id,
+ "nickname" => admin.nickname,
+ "type" => "user"
+ },
+ action: "relay_follow",
+ target: "https://example.org/relay"
+ },
+ inserted_at: NaiveDateTime.truncate(~N[2017-08-15 15:47:06.597036], :second)
+ })
+
+ Repo.insert(%ModerationLog{
+ data: %{
+ actor: %{
+ "id" => admin.id,
+ "nickname" => admin.nickname,
+ "type" => "user"
+ },
+ action: "relay_unfollow",
+ target: "https://example.org/relay"
+ },
+ inserted_at: NaiveDateTime.truncate(~N[2017-08-16 15:47:06.597036], :second)
+ })
+
+ conn = get(conn, "/api/pleroma/admin/moderation_log")
+
+ response = json_response(conn, 200)
+ [first_entry, second_entry] = response["items"]
+
+ assert response["total"] == 2
+ assert first_entry["data"]["action"] == "relay_unfollow"
+
+ assert first_entry["message"] ==
+ "@#{admin.nickname} unfollowed relay: https://example.org/relay"
+
+ assert second_entry["data"]["action"] == "relay_follow"
+
+ assert second_entry["message"] ==
+ "@#{admin.nickname} followed relay: https://example.org/relay"
+ end
+
+ test "returns the log with pagination", %{conn: conn, admin: admin} do
+ Repo.insert(%ModerationLog{
+ data: %{
+ actor: %{
+ "id" => admin.id,
+ "nickname" => admin.nickname,
+ "type" => "user"
+ },
+ action: "relay_follow",
+ target: "https://example.org/relay"
+ },
+ inserted_at: NaiveDateTime.truncate(~N[2017-08-15 15:47:06.597036], :second)
+ })
+
+ Repo.insert(%ModerationLog{
+ data: %{
+ actor: %{
+ "id" => admin.id,
+ "nickname" => admin.nickname,
+ "type" => "user"
+ },
+ action: "relay_unfollow",
+ target: "https://example.org/relay"
+ },
+ inserted_at: NaiveDateTime.truncate(~N[2017-08-16 15:47:06.597036], :second)
+ })
+
+ conn1 = get(conn, "/api/pleroma/admin/moderation_log?page_size=1&page=1")
+
+ response1 = json_response(conn1, 200)
+ [first_entry] = response1["items"]
+
+ assert response1["total"] == 2
+ assert response1["items"] |> length() == 1
+ assert first_entry["data"]["action"] == "relay_unfollow"
+
+ assert first_entry["message"] ==
+ "@#{admin.nickname} unfollowed relay: https://example.org/relay"
+
+ conn2 = get(conn, "/api/pleroma/admin/moderation_log?page_size=1&page=2")
+
+ response2 = json_response(conn2, 200)
+ [second_entry] = response2["items"]
+
+ assert response2["total"] == 2
+ assert response2["items"] |> length() == 1
+ assert second_entry["data"]["action"] == "relay_follow"
+
+ assert second_entry["message"] ==
+ "@#{admin.nickname} followed relay: https://example.org/relay"
+ end
+
+ test "filters log by date", %{conn: conn, admin: admin} do
+ first_date = "2017-08-15T15:47:06Z"
+ second_date = "2017-08-20T15:47:06Z"
+
+ Repo.insert(%ModerationLog{
+ data: %{
+ actor: %{
+ "id" => admin.id,
+ "nickname" => admin.nickname,
+ "type" => "user"
+ },
+ action: "relay_follow",
+ target: "https://example.org/relay"
+ },
+ inserted_at: NaiveDateTime.from_iso8601!(first_date)
+ })
+
+ Repo.insert(%ModerationLog{
+ data: %{
+ actor: %{
+ "id" => admin.id,
+ "nickname" => admin.nickname,
+ "type" => "user"
+ },
+ action: "relay_unfollow",
+ target: "https://example.org/relay"
+ },
+ inserted_at: NaiveDateTime.from_iso8601!(second_date)
+ })
+
+ conn1 =
+ get(
+ conn,
+ "/api/pleroma/admin/moderation_log?start_date=#{second_date}"
+ )
+
+ response1 = json_response(conn1, 200)
+ [first_entry] = response1["items"]
+
+ assert response1["total"] == 1
+ assert first_entry["data"]["action"] == "relay_unfollow"
+
+ assert first_entry["message"] ==
+ "@#{admin.nickname} unfollowed relay: https://example.org/relay"
+ end
+
+ test "returns log filtered by user", %{conn: conn, admin: admin, moderator: moderator} do
+ Repo.insert(%ModerationLog{
+ data: %{
+ actor: %{
+ "id" => admin.id,
+ "nickname" => admin.nickname,
+ "type" => "user"
+ },
+ action: "relay_follow",
+ target: "https://example.org/relay"
+ }
+ })
+
+ Repo.insert(%ModerationLog{
+ data: %{
+ actor: %{
+ "id" => moderator.id,
+ "nickname" => moderator.nickname,
+ "type" => "user"
+ },
+ action: "relay_unfollow",
+ target: "https://example.org/relay"
+ }
+ })
+
+ conn1 = get(conn, "/api/pleroma/admin/moderation_log?user_id=#{moderator.id}")
+
+ response1 = json_response(conn1, 200)
+ [first_entry] = response1["items"]
+
+ assert response1["total"] == 1
+ assert get_in(first_entry, ["data", "actor", "id"]) == moderator.id
+ end
+
+ test "returns log filtered by search", %{conn: conn, moderator: moderator} do
+ ModerationLog.insert_log(%{
+ actor: moderator,
+ action: "relay_follow",
+ target: "https://example.org/relay"
+ })
+
+ ModerationLog.insert_log(%{
+ actor: moderator,
+ action: "relay_unfollow",
+ target: "https://example.org/relay"
+ })
+
+ conn1 = get(conn, "/api/pleroma/admin/moderation_log?search=unfo")
+
+ response1 = json_response(conn1, 200)
+ [first_entry] = response1["items"]
+
+ assert response1["total"] == 1
+
+ assert get_in(first_entry, ["data", "message"]) ==
+ "@#{moderator.nickname} unfollowed relay: https://example.org/relay"
+ end
+ end
+
+ describe "GET /users/:nickname/credentials" do
+ test "gets the user credentials", %{conn: conn} do
+ user = insert(:user)
+ conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/credentials")
+
+ response = assert json_response(conn, 200)
+ assert response["email"] == user.email
+ end
+
+ test "returns 403 if requested by a non-admin" do
+ user = insert(:user)
+
+ conn =
+ build_conn()
+ |> assign(:user, user)
+ |> get("/api/pleroma/admin/users/#{user.nickname}/credentials")
+
+ assert json_response(conn, :forbidden)
+ end
+ end
+
+ describe "PATCH /users/:nickname/credentials" do
+ test "changes password and email", %{conn: conn, admin: admin} do
+ user = insert(:user)
+ assert user.password_reset_pending == false
+
+ conn =
+ patch(conn, "/api/pleroma/admin/users/#{user.nickname}/credentials", %{
+ "password" => "new_password",
+ "email" => "new_email@example.com",
+ "name" => "new_name"
+ })
+
+ assert json_response(conn, 200) == %{"status" => "success"}
+
+ ObanHelpers.perform_all()
+
+ updated_user = User.get_by_id(user.id)
+
+ assert updated_user.email == "new_email@example.com"
+ assert updated_user.name == "new_name"
+ assert updated_user.password_hash != user.password_hash
+ assert updated_user.password_reset_pending == true
+
+ [log_entry2, log_entry1] = ModerationLog |> Repo.all() |> Enum.sort()
+
+ assert ModerationLog.get_log_entry_message(log_entry1) ==
+ "@#{admin.nickname} updated users: @#{user.nickname}"
+
+ assert ModerationLog.get_log_entry_message(log_entry2) ==
+ "@#{admin.nickname} forced password reset for users: @#{user.nickname}"
+ end
+
+ test "returns 403 if requested by a non-admin" do
+ user = insert(:user)
+
+ conn =
+ build_conn()
+ |> assign(:user, user)
+ |> patch("/api/pleroma/admin/users/#{user.nickname}/credentials", %{
+ "password" => "new_password",
+ "email" => "new_email@example.com",
+ "name" => "new_name"
+ })
+
+ assert json_response(conn, :forbidden)
+ end
+ end
+
+ describe "PATCH /users/:nickname/force_password_reset" do
+ test "sets password_reset_pending to true", %{conn: conn} do
+ user = insert(:user)
+ assert user.password_reset_pending == false
+
+ conn =
+ patch(conn, "/api/pleroma/admin/users/force_password_reset", %{nicknames: [user.nickname]})
+
+ assert json_response(conn, 204) == ""
+
+ ObanHelpers.perform_all()
+
+ assert User.get_by_id(user.id).password_reset_pending == true
+ end
+ end
+
+ describe "relays" do
+ test "POST /relay", %{conn: conn, admin: admin} do
+ conn =
+ post(conn, "/api/pleroma/admin/relay", %{
+ relay_url: "http://mastodon.example.org/users/admin"
+ })
+
+ assert json_response(conn, 200) == "http://mastodon.example.org/users/admin"
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} followed relay: http://mastodon.example.org/users/admin"
+ end
+
+ test "GET /relay", %{conn: conn} do
+ relay_user = Pleroma.Web.ActivityPub.Relay.get_actor()
+
+ ["http://mastodon.example.org/users/admin", "https://mstdn.io/users/mayuutann"]
+ |> Enum.each(fn ap_id ->
+ {:ok, user} = User.get_or_fetch_by_ap_id(ap_id)
+ User.follow(relay_user, user)
+ end)
+
+ conn = get(conn, "/api/pleroma/admin/relay")
+
+ assert json_response(conn, 200)["relays"] -- ["mastodon.example.org", "mstdn.io"] == []
+ end
+
+ test "DELETE /relay", %{conn: conn, admin: admin} do
+ post(conn, "/api/pleroma/admin/relay", %{
+ relay_url: "http://mastodon.example.org/users/admin"
+ })
+
+ conn =
+ delete(conn, "/api/pleroma/admin/relay", %{
+ relay_url: "http://mastodon.example.org/users/admin"
+ })
+
+ assert json_response(conn, 200) == "http://mastodon.example.org/users/admin"
+
+ [log_entry_one, log_entry_two] = Repo.all(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry_one) ==
+ "@#{admin.nickname} followed relay: http://mastodon.example.org/users/admin"
+
+ assert ModerationLog.get_log_entry_message(log_entry_two) ==
+ "@#{admin.nickname} unfollowed relay: http://mastodon.example.org/users/admin"
+ end
+ end
+
+ describe "instances" do
+ test "GET /instances/:instance/statuses", %{conn: conn} do
+ user = insert(:user, local: false, nickname: "archaeme@archae.me")
+ user2 = insert(:user, local: false, nickname: "test@test.com")
+ insert_pair(:note_activity, user: user)
+ activity = insert(:note_activity, user: user2)
+
+ ret_conn = get(conn, "/api/pleroma/admin/instances/archae.me/statuses")
+
+ response = json_response(ret_conn, 200)
+
+ assert length(response) == 2
+
+ ret_conn = get(conn, "/api/pleroma/admin/instances/test.com/statuses")
+
+ response = json_response(ret_conn, 200)
+
+ assert length(response) == 1
+
+ ret_conn = get(conn, "/api/pleroma/admin/instances/nonexistent.com/statuses")
+
+ response = json_response(ret_conn, 200)
+
+ assert Enum.empty?(response)
+
+ CommonAPI.repeat(activity.id, user)
+
+ ret_conn = get(conn, "/api/pleroma/admin/instances/archae.me/statuses")
+ response = json_response(ret_conn, 200)
+ assert length(response) == 2
+
+ ret_conn = get(conn, "/api/pleroma/admin/instances/archae.me/statuses?with_reblogs=true")
+ response = json_response(ret_conn, 200)
+ assert length(response) == 3
+ end
+ end
+
+ describe "PATCH /confirm_email" do
+ test "it confirms emails of two users", %{conn: conn, admin: admin} do
+ [first_user, second_user] = insert_pair(:user, confirmation_pending: true)
+
+ assert first_user.confirmation_pending == true
+ assert second_user.confirmation_pending == true
+
+ ret_conn =
+ patch(conn, "/api/pleroma/admin/users/confirm_email", %{
+ nicknames: [
+ first_user.nickname,
+ second_user.nickname
+ ]
+ })
+
+ assert ret_conn.status == 200
+
+ assert first_user.confirmation_pending == true
+ assert second_user.confirmation_pending == true
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} confirmed email for users: @#{first_user.nickname}, @#{
+ second_user.nickname
+ }"
+ end
+ end
+
+ describe "PATCH /resend_confirmation_email" do
+ test "it resend emails for two users", %{conn: conn, admin: admin} do
+ [first_user, second_user] = insert_pair(:user, confirmation_pending: true)
+
+ ret_conn =
+ patch(conn, "/api/pleroma/admin/users/resend_confirmation_email", %{
+ nicknames: [
+ first_user.nickname,
+ second_user.nickname
+ ]
+ })
+
+ assert ret_conn.status == 200
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} re-sent confirmation email for users: @#{first_user.nickname}, @#{
+ second_user.nickname
+ }"
+ end
+ end
+
+ describe "POST /reports/:id/notes" do
+ setup %{conn: conn, admin: admin} do
+ [reporter, target_user] = insert_pair(:user)
+ activity = insert(:note_activity, user: target_user)
+
+ {:ok, %{id: report_id}} =
+ CommonAPI.report(reporter, %{
+ account_id: target_user.id,
+ comment: "I feel offended",
+ status_ids: [activity.id]
+ })
+
+ post(conn, "/api/pleroma/admin/reports/#{report_id}/notes", %{
+ content: "this is disgusting!"
+ })
+
+ post(conn, "/api/pleroma/admin/reports/#{report_id}/notes", %{
+ content: "this is disgusting2!"
+ })
+
+ %{
+ admin_id: admin.id,
+ report_id: report_id
+ }
+ end
+
+ test "it creates report note", %{admin_id: admin_id, report_id: report_id} do
+ [note, _] = Repo.all(ReportNote)
+
+ assert %{
+ activity_id: ^report_id,
+ content: "this is disgusting!",
+ user_id: ^admin_id
+ } = note
+ end
+
+ test "it returns reports with notes", %{conn: conn, admin: admin} do
+ conn = get(conn, "/api/pleroma/admin/reports")
+
+ response = json_response(conn, 200)
+ notes = hd(response["reports"])["notes"]
+ [note, _] = notes
+
+ assert note["user"]["nickname"] == admin.nickname
+ assert note["content"] == "this is disgusting!"
+ assert note["created_at"]
+ assert response["total"] == 1
+ end
+
+ test "it deletes the note", %{conn: conn, report_id: report_id} do
+ assert ReportNote |> Repo.all() |> length() == 2
+
+ [note, _] = Repo.all(ReportNote)
+
+ delete(conn, "/api/pleroma/admin/reports/#{report_id}/notes/#{note.id}")
+
+ assert ReportNote |> Repo.all() |> length() == 1
+ end
+ end
+
+ describe "GET /api/pleroma/admin/config/descriptions" do
+ test "structure", %{conn: conn} do
+ admin = insert(:user, is_admin: true)
+
+ conn =
+ assign(conn, :user, admin)
+ |> get("/api/pleroma/admin/config/descriptions")
+
+ assert [child | _others] = json_response(conn, 200)
+
+ assert child["children"]
+ assert child["key"]
+ assert String.starts_with?(child["group"], ":")
+ assert child["description"]
+ end
+
+ test "filters by database configuration whitelist", %{conn: conn} do
+ clear_config(:database_config_whitelist, [
+ {:pleroma, :instance},
+ {:pleroma, :activitypub},
+ {:pleroma, Pleroma.Upload},
+ {:esshd}
+ ])
+
+ admin = insert(:user, is_admin: true)
+
+ conn =
+ assign(conn, :user, admin)
+ |> get("/api/pleroma/admin/config/descriptions")
+
+ children = json_response(conn, 200)
+
+ assert length(children) == 4
+
+ assert Enum.count(children, fn c -> c["group"] == ":pleroma" end) == 3
+
+ instance = Enum.find(children, fn c -> c["key"] == ":instance" end)
+ assert instance["children"]
+
+ activitypub = Enum.find(children, fn c -> c["key"] == ":activitypub" end)
+ assert activitypub["children"]
+
+ web_endpoint = Enum.find(children, fn c -> c["key"] == "Pleroma.Upload" end)
+ assert web_endpoint["children"]
+
+ esshd = Enum.find(children, fn c -> c["group"] == ":esshd" end)
+ assert esshd["children"]
+ end
+ end
+
+ describe "/api/pleroma/admin/stats" do
+ test "status visibility count", %{conn: conn} do
+ admin = insert(:user, is_admin: true)
+ user = insert(:user)
+ CommonAPI.post(user, %{visibility: "public", status: "hey"})
+ CommonAPI.post(user, %{visibility: "unlisted", status: "hey"})
+ CommonAPI.post(user, %{visibility: "unlisted", status: "hey"})
+
+ response =
+ conn
+ |> assign(:user, admin)
+ |> get("/api/pleroma/admin/stats")
+ |> json_response(200)
+
+ assert %{"direct" => 0, "private" => 0, "public" => 1, "unlisted" => 2} =
+ response["status_visibility"]
+ end
+ end
+
+ describe "POST /api/pleroma/admin/oauth_app" do
+ test "errors", %{conn: conn} do
+ response = conn |> post("/api/pleroma/admin/oauth_app", %{}) |> json_response(200)
+
+ assert response == %{"name" => "can't be blank", "redirect_uris" => "can't be blank"}
+ end
+
+ test "success", %{conn: conn} do
+ base_url = Web.base_url()
+ app_name = "Trusted app"
+
+ response =
+ conn
+ |> post("/api/pleroma/admin/oauth_app", %{
+ name: app_name,
+ redirect_uris: base_url
+ })
+ |> json_response(200)
+
+ assert %{
+ "client_id" => _,
+ "client_secret" => _,
+ "name" => ^app_name,
+ "redirect_uri" => ^base_url,
+ "trusted" => false
+ } = response
+ end
+
+ test "with trusted", %{conn: conn} do
+ base_url = Web.base_url()
+ app_name = "Trusted app"
+
+ response =
+ conn
+ |> post("/api/pleroma/admin/oauth_app", %{
+ name: app_name,
+ redirect_uris: base_url,
+ trusted: true
+ })
+ |> json_response(200)
+
+ assert %{
+ "client_id" => _,
+ "client_secret" => _,
+ "name" => ^app_name,
+ "redirect_uri" => ^base_url,
+ "trusted" => true
+ } = response
+ end
+ end
+
+ describe "GET /api/pleroma/admin/oauth_app" do
+ setup do
+ app = insert(:oauth_app)
+ {:ok, app: app}
+ end
+
+ test "list", %{conn: conn} do
+ response =
+ conn
+ |> get("/api/pleroma/admin/oauth_app")
+ |> json_response(200)
+
+ assert %{"apps" => apps, "count" => count, "page_size" => _} = response
+
+ assert length(apps) == count
+ end
+
+ test "with page size", %{conn: conn} do
+ insert(:oauth_app)
+ page_size = 1
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/oauth_app", %{page_size: to_string(page_size)})
+ |> json_response(200)
+
+ assert %{"apps" => apps, "count" => _, "page_size" => ^page_size} = response
+
+ assert length(apps) == page_size
+ end
+
+ test "search by client name", %{conn: conn, app: app} do
+ response =
+ conn
+ |> get("/api/pleroma/admin/oauth_app", %{name: app.client_name})
+ |> json_response(200)
+
+ assert %{"apps" => [returned], "count" => _, "page_size" => _} = response
+
+ assert returned["client_id"] == app.client_id
+ assert returned["name"] == app.client_name
+ end
+
+ test "search by client id", %{conn: conn, app: app} do
+ response =
+ conn
+ |> get("/api/pleroma/admin/oauth_app", %{client_id: app.client_id})
+ |> json_response(200)
+
+ assert %{"apps" => [returned], "count" => _, "page_size" => _} = response
+
+ assert returned["client_id"] == app.client_id
+ assert returned["name"] == app.client_name
+ end
+
+ test "only trusted", %{conn: conn} do
+ app = insert(:oauth_app, trusted: true)
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/oauth_app", %{trusted: true})
+ |> json_response(200)
+
+ assert %{"apps" => [returned], "count" => _, "page_size" => _} = response
+
+ assert returned["client_id"] == app.client_id
+ assert returned["name"] == app.client_name
+ end
+ end
+
+ describe "DELETE /api/pleroma/admin/oauth_app/:id" do
+ test "with id", %{conn: conn} do
+ app = insert(:oauth_app)
+
+ response =
+ conn
+ |> delete("/api/pleroma/admin/oauth_app/" <> to_string(app.id))
+ |> json_response(:no_content)
+
+ assert response == ""
+ end
+
+ test "with non existance id", %{conn: conn} do
+ response =
+ conn
+ |> delete("/api/pleroma/admin/oauth_app/0")
+ |> json_response(:bad_request)
+
+ assert response == ""
+ end
+ end
+
+ describe "PATCH /api/pleroma/admin/oauth_app/:id" do
+ test "with id", %{conn: conn} do
+ app = insert(:oauth_app)
+
+ name = "another name"
+ url = "https://example.com"
+ scopes = ["admin"]
+ id = app.id
+ website = "http://website.com"
+
+ response =
+ conn
+ |> patch("/api/pleroma/admin/oauth_app/" <> to_string(app.id), %{
+ name: name,
+ trusted: true,
+ redirect_uris: url,
+ scopes: scopes,
+ website: website
+ })
+ |> json_response(200)
+
+ assert %{
+ "client_id" => _,
+ "client_secret" => _,
+ "id" => ^id,
+ "name" => ^name,
+ "redirect_uri" => ^url,
+ "trusted" => true,
+ "website" => ^website
+ } = response
+ end
+
+ test "without id", %{conn: conn} do
+ response =
+ conn
+ |> patch("/api/pleroma/admin/oauth_app/0")
+ |> json_response(:bad_request)
+
+ assert response == ""
+ end
+ end
+end
+
+# Needed for testing
+defmodule Pleroma.Web.Endpoint.NotReal do
+end
+
+defmodule Pleroma.Captcha.NotReal do
+end
diff --git a/test/web/admin_api/controllers/status_controller_test.exs b/test/web/admin_api/controllers/status_controller_test.exs
new file mode 100644
index 000000000..8ecc78491
--- /dev/null
+++ b/test/web/admin_api/controllers/status_controller_test.exs
@@ -0,0 +1,185 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
+ use Pleroma.Web.ConnCase
+
+ import Pleroma.Factory
+
+ alias Pleroma.Activity
+ alias Pleroma.Config
+ alias Pleroma.ModerationLog
+ alias Pleroma.Repo
+ alias Pleroma.User
+ alias Pleroma.Web.CommonAPI
+
+ setup do
+ admin = insert(:user, is_admin: true)
+ token = insert(:oauth_admin_token, user: admin)
+
+ conn =
+ build_conn()
+ |> assign(:user, admin)
+ |> assign(:token, token)
+
+ {:ok, %{admin: admin, token: token, conn: conn}}
+ end
+
+ describe "GET /api/pleroma/admin/statuses/:id" do
+ test "not found", %{conn: conn} do
+ assert conn
+ |> get("/api/pleroma/admin/statuses/not_found")
+ |> json_response(:not_found)
+ end
+
+ test "shows activity", %{conn: conn} do
+ activity = insert(:note_activity)
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/statuses/#{activity.id}")
+ |> json_response(200)
+
+ assert response["id"] == activity.id
+ end
+ end
+
+ describe "PUT /api/pleroma/admin/statuses/:id" do
+ setup do
+ activity = insert(:note_activity)
+
+ %{id: activity.id}
+ end
+
+ test "toggle sensitive flag", %{conn: conn, id: id, admin: admin} do
+ response =
+ conn
+ |> put("/api/pleroma/admin/statuses/#{id}", %{"sensitive" => "true"})
+ |> json_response(:ok)
+
+ assert response["sensitive"]
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} updated status ##{id}, set sensitive: 'true'"
+
+ response =
+ conn
+ |> put("/api/pleroma/admin/statuses/#{id}", %{"sensitive" => "false"})
+ |> json_response(:ok)
+
+ refute response["sensitive"]
+ end
+
+ test "change visibility flag", %{conn: conn, id: id, admin: admin} do
+ response =
+ conn
+ |> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "public"})
+ |> json_response(:ok)
+
+ assert response["visibility"] == "public"
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} updated status ##{id}, set visibility: 'public'"
+
+ response =
+ conn
+ |> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "private"})
+ |> json_response(:ok)
+
+ assert response["visibility"] == "private"
+
+ response =
+ conn
+ |> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "unlisted"})
+ |> json_response(:ok)
+
+ assert response["visibility"] == "unlisted"
+ end
+
+ test "returns 400 when visibility is unknown", %{conn: conn, id: id} do
+ conn = put(conn, "/api/pleroma/admin/statuses/#{id}", %{visibility: "test"})
+
+ assert json_response(conn, :bad_request) == "Unsupported visibility"
+ end
+ end
+
+ describe "DELETE /api/pleroma/admin/statuses/:id" do
+ setup do
+ activity = insert(:note_activity)
+
+ %{id: activity.id}
+ end
+
+ test "deletes status", %{conn: conn, id: id, admin: admin} do
+ conn
+ |> delete("/api/pleroma/admin/statuses/#{id}")
+ |> json_response(:ok)
+
+ refute Activity.get_by_id(id)
+
+ log_entry = Repo.one(ModerationLog)
+
+ assert ModerationLog.get_log_entry_message(log_entry) ==
+ "@#{admin.nickname} deleted status ##{id}"
+ end
+
+ test "returns 404 when the status does not exist", %{conn: conn} do
+ conn = delete(conn, "/api/pleroma/admin/statuses/test")
+
+ assert json_response(conn, :not_found) == "Not found"
+ end
+ end
+
+ describe "GET /api/pleroma/admin/statuses" do
+ test "returns all public and unlisted statuses", %{conn: conn, admin: admin} do
+ blocked = insert(:user)
+ user = insert(:user)
+ User.block(admin, blocked)
+
+ {:ok, _} = CommonAPI.post(user, %{status: "@#{admin.nickname}", visibility: "direct"})
+
+ {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "unlisted"})
+ {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "private"})
+ {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "public"})
+ {:ok, _} = CommonAPI.post(blocked, %{status: ".", visibility: "public"})
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/statuses")
+ |> json_response(200)
+
+ refute "private" in Enum.map(response, & &1["visibility"])
+ assert length(response) == 3
+ end
+
+ test "returns only local statuses with local_only on", %{conn: conn} do
+ user = insert(:user)
+ remote_user = insert(:user, local: false, nickname: "archaeme@archae.me")
+ insert(:note_activity, user: user, local: true)
+ insert(:note_activity, user: remote_user, local: false)
+
+ response =
+ conn
+ |> get("/api/pleroma/admin/statuses?local_only=true")
+ |> json_response(200)
+
+ assert length(response) == 1
+ end
+
+ test "returns private and direct statuses with godmode on", %{conn: conn, admin: admin} do
+ user = insert(:user)
+
+ {:ok, _} = CommonAPI.post(user, %{status: "@#{admin.nickname}", visibility: "direct"})
+
+ {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "private"})
+ {:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "public"})
+ conn = get(conn, "/api/pleroma/admin/statuses?godmode=true")
+ assert json_response(conn, 200) |> length() == 3
+ end
+ end
+end
--
cgit v1.2.3
From d9d425708e094a428fb05127b97480a122c1c616 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 21 May 2020 12:43:09 +0200
Subject: SideEffects: Builed out Announce effects.
---
test/web/activity_pub/side_effects_test.exs | 48 ++++++++++++++++++++++++++---
1 file changed, 44 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index 5dede3957..db8bf2b05 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -172,7 +172,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
{:ok, post} = CommonAPI.post(poster, %{status: "hey"})
{:ok, like} = CommonAPI.favorite(user, post.id)
{:ok, reaction} = CommonAPI.react_with_emoji(post.id, user, "👍")
- {:ok, announce, _} = CommonAPI.repeat(post.id, user)
+ {:ok, announce} = CommonAPI.repeat(post.id, user)
{:ok, block} = ActivityPub.block(user, poster)
User.block(user, poster)
@@ -295,23 +295,63 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
poster = insert(:user)
user = insert(:user)
{:ok, post} = CommonAPI.post(poster, %{status: "hey"})
+ {:ok, private_post} = CommonAPI.post(poster, %{status: "hey", visibility: "private"})
+
+ {:ok, announce_data, _meta} = Builder.announce(user, post.object, public: true)
+
+ {:ok, private_announce_data, _meta} =
+ Builder.announce(user, private_post.object, public: false)
+
+ {:ok, relay_announce_data, _meta} =
+ Builder.announce(Pleroma.Web.ActivityPub.Relay.get_actor(), post.object, public: true)
- {:ok, announce_data, _meta} = Builder.announce(user, post.object)
{:ok, announce, _meta} = ActivityPub.persist(announce_data, local: true)
+ {:ok, private_announce, _meta} = ActivityPub.persist(private_announce_data, local: true)
+ {:ok, relay_announce, _meta} = ActivityPub.persist(relay_announce_data, local: true)
- %{announce: announce, user: user, poster: poster}
+ %{
+ announce: announce,
+ user: user,
+ poster: poster,
+ private_announce: private_announce,
+ relay_announce: relay_announce
+ }
end
- test "add the announce to the original object", %{announce: announce, user: user} do
+ test "adds the announce to the original object", %{announce: announce, user: user} do
{:ok, announce, _} = SideEffects.handle(announce)
object = Object.get_by_ap_id(announce.data["object"])
assert object.data["announcement_count"] == 1
assert user.ap_id in object.data["announcements"]
end
+ test "does not add the announce to the original object if the announce is private", %{
+ private_announce: announce
+ } do
+ {:ok, announce, _} = SideEffects.handle(announce)
+ object = Object.get_by_ap_id(announce.data["object"])
+ assert object.data["announcement_count"] == nil
+ end
+
+ test "does not add the announce to the original object if the actor is a service actor", %{
+ relay_announce: announce
+ } do
+ {:ok, announce, _} = SideEffects.handle(announce)
+ object = Object.get_by_ap_id(announce.data["object"])
+ assert object.data["announcement_count"] == nil
+ end
+
test "creates a notification", %{announce: announce, poster: poster} do
{:ok, announce, _} = SideEffects.handle(announce)
assert Repo.get_by(Notification, user_id: poster.id, activity_id: announce.id)
end
+
+ test "it streams out the announce", %{announce: announce} do
+ with_mock Pleroma.Web.ActivityPub.ActivityPub, [:passthrough], stream_out: fn _ -> nil end do
+ {:ok, announce, _} = SideEffects.handle(announce)
+
+ assert called(Pleroma.Web.ActivityPub.ActivityPub.stream_out(announce))
+ end
+ end
end
end
--
cgit v1.2.3
From 23e248694df988d50e8a07b704a7ac56b8e9b19c Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 21 May 2020 13:16:21 +0200
Subject: Announcements: Fix all tests.
---
test/notification_test.exs | 6 +-
test/tasks/user_test.exs | 5 +-
test/user_test.exs | 4 +-
test/web/activity_pub/activity_pub_test.exs | 85 ++--------------------
test/web/activity_pub/relay_test.exs | 15 ++--
test/web/activity_pub/side_effects_test.exs | 8 --
test/web/activity_pub/transmogrifier_test.exs | 2 +-
test/web/activity_pub/utils_test.exs | 2 +-
test/web/activity_pub/views/object_view_test.exs | 2 +-
test/web/admin_api/admin_api_controller_test.exs | 4 +-
test/web/common_api/common_api_test.exs | 5 ++
.../controllers/account_controller_test.exs | 6 +-
.../controllers/notification_controller_test.exs | 8 +-
.../controllers/status_controller_test.exs | 18 ++---
.../mastodon_api/views/notification_view_test.exs | 2 +-
test/web/mastodon_api/views/status_view_test.exs | 4 +-
test/web/push/impl_test.exs | 2 +-
test/web/streamer/streamer_test.exs | 6 +-
18 files changed, 57 insertions(+), 127 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 111ff09f4..3a96721fa 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -648,7 +648,7 @@ defmodule Pleroma.NotificationTest do
status: "hey @#{other_user.nickname}!"
})
- {:ok, activity_two, _} = CommonAPI.repeat(activity_one.id, third_user)
+ {:ok, activity_two} = CommonAPI.repeat(activity_one.id, third_user)
{enabled_receivers, _disabled_receivers} =
Notification.get_notified_from_activity(activity_two)
@@ -778,7 +778,7 @@ defmodule Pleroma.NotificationTest do
assert Enum.empty?(Notification.for_user(user))
- {:ok, _, _} = CommonAPI.repeat(activity.id, other_user)
+ {:ok, _} = CommonAPI.repeat(activity.id, other_user)
assert length(Notification.for_user(user)) == 1
@@ -795,7 +795,7 @@ defmodule Pleroma.NotificationTest do
assert Enum.empty?(Notification.for_user(user))
- {:ok, _, _} = CommonAPI.repeat(activity.id, other_user)
+ {:ok, _} = CommonAPI.repeat(activity.id, other_user)
assert length(Notification.for_user(user)) == 1
diff --git a/test/tasks/user_test.exs b/test/tasks/user_test.exs
index 4aa873f0b..7db48439f 100644
--- a/test/tasks/user_test.exs
+++ b/test/tasks/user_test.exs
@@ -91,6 +91,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do
describe "running rm" do
test "user is deleted" do
+ clear_config([:instance, :federating], true)
user = insert(:user)
with_mock Pleroma.Web.Federator,
@@ -108,8 +109,10 @@ defmodule Mix.Tasks.Pleroma.UserTest do
test "a remote user's create activity is deleted when the object has been pruned" do
user = insert(:user)
-
{:ok, post} = CommonAPI.post(user, %{status: "uguu"})
+
+ clear_config([:instance, :federating], true)
+
object = Object.normalize(post)
Object.prune(object)
diff --git a/test/user_test.exs b/test/user_test.exs
index 863e0106c..be58c70e1 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -992,7 +992,7 @@ defmodule Pleroma.UserTest do
user = insert(:user, local: true)
{:ok, activity} = CommonAPI.post(actor, %{status: "hello"})
- {:ok, announce, _} = CommonAPI.repeat(activity.id, user)
+ {:ok, announce} = CommonAPI.repeat(activity.id, user)
recipients = User.get_recipients_from_activity(announce)
@@ -1147,7 +1147,7 @@ defmodule Pleroma.UserTest do
{:ok, like} = CommonAPI.favorite(user, activity_two.id)
{:ok, like_two} = CommonAPI.favorite(follower, activity.id)
- {:ok, repeat, _} = CommonAPI.repeat(activity_two.id, user)
+ {:ok, repeat} = CommonAPI.repeat(activity_two.id, user)
{:ok, job} = User.delete(user)
{:ok, _user} = ObanHelpers.perform(job)
diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs
index 77bd07edf..3dcb62873 100644
--- a/test/web/activity_pub/activity_pub_test.exs
+++ b/test/web/activity_pub/activity_pub_test.exs
@@ -537,7 +537,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
assert Enum.member?(activities, activity_one)
{:ok, _user_relationship} = User.block(user, %{ap_id: activity_three.data["actor"]})
- {:ok, _announce, %{data: %{"id" => id}}} = CommonAPI.repeat(activity_three.id, booster)
+ {:ok, %{data: %{"object" => id}}} = CommonAPI.repeat(activity_three.id, booster)
%Activity{} = boost_activity = Activity.get_create_by_object_ap_id(id)
activity_three = Activity.get_by_id(activity_three.id)
@@ -592,7 +592,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, activity_two} = CommonAPI.post(blockee, %{status: "hey! @#{friend.nickname}"})
- {:ok, activity_three, _} = CommonAPI.repeat(activity_two.id, friend)
+ {:ok, activity_three} = CommonAPI.repeat(activity_two.id, friend)
activities =
ActivityPub.fetch_activities([], %{"blocking_user" => blocker})
@@ -618,7 +618,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
followed_user = insert(:user)
ActivityPub.follow(user, followed_user)
- {:ok, repeat_activity, _} = CommonAPI.repeat(activity.id, followed_user)
+ {:ok, repeat_activity} = CommonAPI.repeat(activity.id, followed_user)
activities =
ActivityPub.fetch_activities([], %{"blocking_user" => user, "skip_preload" => true})
@@ -651,7 +651,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
another_user = insert(:user, %{ap_id: "https://#{domain}/@meanie2"})
bad_note = insert(:note, %{data: %{"actor" => another_user.ap_id}})
bad_activity = insert(:note_activity, %{note: bad_note})
- {:ok, repeat_activity, _} = CommonAPI.repeat(bad_activity.id, domain_user)
+ {:ok, repeat_activity} = CommonAPI.repeat(bad_activity.id, domain_user)
activities =
ActivityPub.fetch_activities([], %{"blocking_user" => blocker, "skip_preload" => true})
@@ -699,7 +699,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
activity_three_actor = User.get_by_ap_id(activity_three.data["actor"])
{:ok, _user_relationships} = User.mute(user, activity_three_actor)
- {:ok, _announce, %{data: %{"id" => id}}} = CommonAPI.repeat(activity_three.id, booster)
+ {:ok, %{data: %{"object" => id}}} = CommonAPI.repeat(activity_three.id, booster)
%Activity{} = boost_activity = Activity.get_create_by_object_ap_id(id)
activity_three = Activity.get_by_id(activity_three.id)
@@ -749,7 +749,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, user} = User.follow(user, booster)
- {:ok, announce, _object} = CommonAPI.repeat(activity_three.id, booster)
+ {:ok, announce} = CommonAPI.repeat(activity_three.id, booster)
[announce_activity] = ActivityPub.fetch_activities([user.ap_id | User.following(user)])
@@ -846,7 +846,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
booster = insert(:user)
{:ok, _reblog_mute} = CommonAPI.hide_reblogs(user, booster)
- {:ok, activity, _} = CommonAPI.repeat(activity.id, booster)
+ {:ok, activity} = CommonAPI.repeat(activity.id, booster)
activities = ActivityPub.fetch_activities([], %{"muting_user" => user})
@@ -860,7 +860,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
{:ok, _reblog_mute} = CommonAPI.hide_reblogs(user, booster)
{:ok, _reblog_mute} = CommonAPI.show_reblogs(user, booster)
- {:ok, activity, _} = CommonAPI.repeat(activity.id, booster)
+ {:ok, activity} = CommonAPI.repeat(activity.id, booster)
activities = ActivityPub.fetch_activities([], %{"muting_user" => user})
@@ -868,75 +868,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do
end
end
- describe "announcing an object" do
- test "adds an announce activity to the db" do
- note_activity = insert(:note_activity)
- object = Object.normalize(note_activity)
- user = insert(:user)
-
- {:ok, announce_activity, object} = ActivityPub.announce(user, object)
- assert object.data["announcement_count"] == 1
- assert object.data["announcements"] == [user.ap_id]
-
- assert announce_activity.data["to"] == [
- User.ap_followers(user),
- note_activity.data["actor"]
- ]
-
- assert announce_activity.data["object"] == object.data["id"]
- assert announce_activity.data["actor"] == user.ap_id
- assert announce_activity.data["context"] == object.data["context"]
- end
-
- test "reverts annouce from object on error" do
- note_activity = insert(:note_activity)
- object = Object.normalize(note_activity)
- user = insert(:user)
-
- with_mock(Utils, [:passthrough], maybe_federate: fn _ -> {:error, :reverted} end) do
- assert {:error, :reverted} = ActivityPub.announce(user, object)
- end
-
- reloaded_object = Object.get_by_ap_id(object.data["id"])
- assert reloaded_object == object
- refute reloaded_object.data["announcement_count"]
- refute reloaded_object.data["announcements"]
- end
- end
-
- describe "announcing a private object" do
- test "adds an announce activity to the db if the audience is not widened" do
- user = insert(:user)
- {:ok, note_activity} = CommonAPI.post(user, %{status: ".", visibility: "private"})
- object = Object.normalize(note_activity)
-
- {:ok, announce_activity, object} = ActivityPub.announce(user, object, nil, true, false)
-
- assert announce_activity.data["to"] == [User.ap_followers(user)]
-
- assert announce_activity.data["object"] == object.data["id"]
- assert announce_activity.data["actor"] == user.ap_id
- assert announce_activity.data["context"] == object.data["context"]
- end
-
- test "does not add an announce activity to the db if the audience is widened" do
- user = insert(:user)
- {:ok, note_activity} = CommonAPI.post(user, %{status: ".", visibility: "private"})
- object = Object.normalize(note_activity)
-
- assert {:error, _} = ActivityPub.announce(user, object, nil, true, true)
- end
-
- test "does not add an announce activity to the db if the announcer is not the author" do
- user = insert(:user)
- announcer = insert(:user)
- {:ok, note_activity} = CommonAPI.post(user, %{status: ".", visibility: "private"})
- object = Object.normalize(note_activity)
-
- assert {:error, _} = ActivityPub.announce(announcer, object, nil, true, false)
- end
- end
-
describe "uploading files" do
test "copies the file to the configured folder" do
file = %Plug.Upload{
diff --git a/test/web/activity_pub/relay_test.exs b/test/web/activity_pub/relay_test.exs
index 9e16e39c4..dbee8a0f4 100644
--- a/test/web/activity_pub/relay_test.exs
+++ b/test/web/activity_pub/relay_test.exs
@@ -6,7 +6,6 @@ defmodule Pleroma.Web.ActivityPub.RelayTest do
use Pleroma.DataCase
alias Pleroma.Activity
- alias Pleroma.Object
alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.Relay
@@ -95,21 +94,20 @@ defmodule Pleroma.Web.ActivityPub.RelayTest do
end)
assert capture_log(fn ->
- assert Relay.publish(activity) == {:error, nil}
- end) =~ "[error] error: nil"
+ assert Relay.publish(activity) == {:error, false}
+ end) =~ "[error] error: false"
end
test_with_mock "returns announce activity and publish to federate",
Pleroma.Web.Federator,
[:passthrough],
[] do
- Pleroma.Config.put([:instance, :federating], true)
+ clear_config([:instance, :federating], true)
service_actor = Relay.get_actor()
note = insert(:note_activity)
- assert {:ok, %Activity{} = activity, %Object{} = obj} = Relay.publish(note)
+ assert {:ok, %Activity{} = activity} = Relay.publish(note)
assert activity.data["type"] == "Announce"
assert activity.data["actor"] == service_actor.ap_id
- assert activity.data["object"] == obj.data["id"]
assert called(Pleroma.Web.Federator.publish(activity))
end
@@ -117,13 +115,12 @@ defmodule Pleroma.Web.ActivityPub.RelayTest do
Pleroma.Web.Federator,
[:passthrough],
[] do
- Pleroma.Config.put([:instance, :federating], false)
+ clear_config([:instance, :federating], false)
service_actor = Relay.get_actor()
note = insert(:note_activity)
- assert {:ok, %Activity{} = activity, %Object{} = obj} = Relay.publish(note)
+ assert {:ok, %Activity{} = activity} = Relay.publish(note)
assert activity.data["type"] == "Announce"
assert activity.data["actor"] == service_actor.ap_id
- assert activity.data["object"] == obj.data["id"]
refute called(Pleroma.Web.Federator.publish(activity))
end
end
diff --git a/test/web/activity_pub/side_effects_test.exs b/test/web/activity_pub/side_effects_test.exs
index db8bf2b05..a80104ea7 100644
--- a/test/web/activity_pub/side_effects_test.exs
+++ b/test/web/activity_pub/side_effects_test.exs
@@ -325,14 +325,6 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do
assert user.ap_id in object.data["announcements"]
end
- test "does not add the announce to the original object if the announce is private", %{
- private_announce: announce
- } do
- {:ok, announce, _} = SideEffects.handle(announce)
- object = Object.get_by_ap_id(announce.data["object"])
- assert object.data["announcement_count"] == nil
- end
-
test "does not add the announce to the original object if the actor is a service actor", %{
relay_announce: announce
} do
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 81f966ad9..356004d48 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -1079,7 +1079,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
{:ok, activity} = CommonAPI.post(user, %{status: "hey", visibility: "private"})
- {:ok, announce_activity, _} = CommonAPI.repeat(activity.id, user)
+ {:ok, announce_activity} = CommonAPI.repeat(activity.id, user)
{:ok, modified} = Transmogrifier.prepare_outgoing(announce_activity.data)
diff --git a/test/web/activity_pub/utils_test.exs b/test/web/activity_pub/utils_test.exs
index 9e0a0f1c4..15f03f193 100644
--- a/test/web/activity_pub/utils_test.exs
+++ b/test/web/activity_pub/utils_test.exs
@@ -334,7 +334,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do
assert object = Object.normalize(note_activity)
actor = insert(:user)
- {:ok, announce, _object} = ActivityPub.announce(actor, object)
+ {:ok, announce} = CommonAPI.repeat(note_activity.id, actor)
assert Utils.get_existing_announce(actor.ap_id, object) == announce
end
end
diff --git a/test/web/activity_pub/views/object_view_test.exs b/test/web/activity_pub/views/object_view_test.exs
index 43f0617f0..f0389845d 100644
--- a/test/web/activity_pub/views/object_view_test.exs
+++ b/test/web/activity_pub/views/object_view_test.exs
@@ -73,7 +73,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectViewTest do
object = Object.normalize(note)
user = insert(:user)
- {:ok, announce_activity, _} = CommonAPI.repeat(note.id, user)
+ {:ok, announce_activity} = CommonAPI.repeat(note.id, user)
result = ObjectView.render("object.json", %{object: announce_activity})
diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs
index 370d876d0..12cb1afd9 100644
--- a/test/web/admin_api/admin_api_controller_test.exs
+++ b/test/web/admin_api/admin_api_controller_test.exs
@@ -148,6 +148,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
describe "DELETE /api/pleroma/admin/users" do
test "single user", %{admin: admin, conn: conn} do
user = insert(:user)
+ clear_config([:instance, :federating], true)
with_mock Pleroma.Web.Federator,
publish: fn _ -> nil end do
@@ -2944,6 +2945,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
assert ":proxy_url" in db
end
+ @tag capture_log: true
test "doesn't set keys not in the whitelist", %{conn: conn} do
clear_config(:database_config_whitelist, [
{:pleroma, :key1},
@@ -3096,7 +3098,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
test "excludes reblogs by default", %{conn: conn, user: user} do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(user, %{status: "."})
- {:ok, %Activity{}, _} = CommonAPI.repeat(activity.id, other_user)
+ {:ok, %Activity{}} = CommonAPI.repeat(activity.id, other_user)
conn_res = get(conn, "/api/pleroma/admin/users/#{other_user.nickname}/statuses")
assert json_response(conn_res, 200) |> length() == 0
diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs
index e68a6a7d2..d849fd8f0 100644
--- a/test/web/common_api/common_api_test.exs
+++ b/test/web/common_api/common_api_test.exs
@@ -41,6 +41,8 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, post} = CommonAPI.post(user, %{status: "namu amida butsu"})
+ clear_config([:instance, :federating], true)
+
Object.normalize(post, false)
|> Object.prune()
@@ -59,6 +61,8 @@ defmodule Pleroma.Web.CommonAPITest do
{:ok, post} = CommonAPI.post(user, %{status: "namu amida butsu"})
+ clear_config([:instance, :federating], true)
+
with_mock Pleroma.Web.Federator,
publish: fn _ -> nil end do
assert {:ok, delete} = CommonAPI.delete(post.id, user)
@@ -440,6 +444,7 @@ defmodule Pleroma.Web.CommonAPITest do
CommonAPI.repeat(activity.id, user, %{visibility: "private"})
assert Visibility.is_private?(announce_activity)
+ refute Visibility.visible_for_user?(announce_activity, nil)
end
test "favoriting a status" do
diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs
index 280bd6aca..1ce97378d 100644
--- a/test/web/mastodon_api/controllers/account_controller_test.exs
+++ b/test/web/mastodon_api/controllers/account_controller_test.exs
@@ -256,7 +256,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
User.block(user_one, user_two)
{:ok, activity} = CommonAPI.post(user_two, %{status: "User one sux0rz"})
- {:ok, repeat, _} = CommonAPI.repeat(activity.id, user_three)
+ {:ok, repeat} = CommonAPI.repeat(activity.id, user_three)
assert resp =
conn
@@ -375,7 +375,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
test "gets a user's statuses without reblogs", %{user: user, conn: conn} do
{:ok, %{id: post_id}} = CommonAPI.post(user, %{status: "HI!!!"})
- {:ok, _, _} = CommonAPI.repeat(post_id, user)
+ {:ok, _} = CommonAPI.repeat(post_id, user)
conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?exclude_reblogs=true")
assert [%{"id" => ^post_id}] = json_response_and_validate_schema(conn, 200)
@@ -678,7 +678,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do
assert %{"showing_reblogs" => false} = json_response_and_validate_schema(ret_conn, 200)
{:ok, activity} = CommonAPI.post(other_user, %{status: "hey"})
- {:ok, %{id: reblog_id}, _} = CommonAPI.repeat(activity.id, followed)
+ {:ok, %{id: reblog_id}} = CommonAPI.repeat(activity.id, followed)
assert [] ==
conn
diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs
index 562fc4d8e..e278d61f5 100644
--- a/test/web/mastodon_api/controllers/notification_controller_test.exs
+++ b/test/web/mastodon_api/controllers/notification_controller_test.exs
@@ -280,8 +280,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
{:ok, unlisted_activity} =
CommonAPI.post(other_user, %{status: ".", visibility: "unlisted"})
- {:ok, _, _} = CommonAPI.repeat(public_activity.id, user)
- {:ok, _, _} = CommonAPI.repeat(unlisted_activity.id, user)
+ {:ok, _} = CommonAPI.repeat(public_activity.id, user)
+ {:ok, _} = CommonAPI.repeat(unlisted_activity.id, user)
activity_ids =
conn
@@ -301,7 +301,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
{:ok, mention_activity} = CommonAPI.post(other_user, %{status: "hey @#{user.nickname}"})
{:ok, create_activity} = CommonAPI.post(user, %{status: "hey"})
{:ok, favorite_activity} = CommonAPI.favorite(other_user, create_activity.id)
- {:ok, reblog_activity, _} = CommonAPI.repeat(create_activity.id, other_user)
+ {:ok, reblog_activity} = CommonAPI.repeat(create_activity.id, other_user)
{:ok, _, _, follow_activity} = CommonAPI.follow(other_user, user)
mention_notification_id = get_notification_id_by_activity(mention_activity)
@@ -339,7 +339,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
{:ok, mention_activity} = CommonAPI.post(other_user, %{status: "hey @#{user.nickname}"})
{:ok, create_activity} = CommonAPI.post(user, %{status: "hey"})
{:ok, favorite_activity} = CommonAPI.favorite(other_user, create_activity.id)
- {:ok, reblog_activity, _} = CommonAPI.repeat(create_activity.id, other_user)
+ {:ok, reblog_activity} = CommonAPI.repeat(create_activity.id, other_user)
{:ok, _, _, follow_activity} = CommonAPI.follow(other_user, user)
mention_notification_id = get_notification_id_by_activity(mention_activity)
diff --git a/test/web/mastodon_api/controllers/status_controller_test.exs b/test/web/mastodon_api/controllers/status_controller_test.exs
index 962e64b03..700c82e4f 100644
--- a/test/web/mastodon_api/controllers/status_controller_test.exs
+++ b/test/web/mastodon_api/controllers/status_controller_test.exs
@@ -878,8 +878,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
user3 = insert(:user)
{:ok, _} = CommonAPI.favorite(user2, activity.id)
{:ok, _bookmark} = Pleroma.Bookmark.create(user2.id, activity.id)
- {:ok, reblog_activity1, _object} = CommonAPI.repeat(activity.id, user1)
- {:ok, _, _object} = CommonAPI.repeat(activity.id, user2)
+ {:ok, reblog_activity1} = CommonAPI.repeat(activity.id, user1)
+ {:ok, _} = CommonAPI.repeat(activity.id, user2)
conn_res =
build_conn()
@@ -917,7 +917,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "unreblogs and returns the unreblogged status", %{user: user, conn: conn} do
activity = insert(:note_activity)
- {:ok, _, _} = CommonAPI.repeat(activity.id, user)
+ {:ok, _} = CommonAPI.repeat(activity.id, user)
conn =
conn
@@ -1427,7 +1427,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "returns users who have reblogged the status", %{conn: conn, activity: activity} do
other_user = insert(:user)
- {:ok, _, _} = CommonAPI.repeat(activity.id, other_user)
+ {:ok, _} = CommonAPI.repeat(activity.id, other_user)
response =
conn
@@ -1458,7 +1458,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
other_user = insert(:user)
{:ok, _user_relationship} = User.block(user, other_user)
- {:ok, _, _} = CommonAPI.repeat(activity.id, other_user)
+ {:ok, _} = CommonAPI.repeat(activity.id, other_user)
response =
conn
@@ -1469,12 +1469,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
end
test "does not return users who have reblogged the status privately", %{
- conn: conn,
- activity: activity
+ conn: conn
} do
other_user = insert(:user)
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "my secret post"})
- {:ok, _, _} = CommonAPI.repeat(activity.id, other_user, %{visibility: "private"})
+ {:ok, _} = CommonAPI.repeat(activity.id, other_user, %{visibility: "private"})
response =
conn
@@ -1486,7 +1486,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
test "does not fail on an unauthenticated request", %{activity: activity} do
other_user = insert(:user)
- {:ok, _, _} = CommonAPI.repeat(activity.id, other_user)
+ {:ok, _} = CommonAPI.repeat(activity.id, other_user)
response =
build_conn()
diff --git a/test/web/mastodon_api/views/notification_view_test.exs b/test/web/mastodon_api/views/notification_view_test.exs
index 9839e48fc..f15be1df1 100644
--- a/test/web/mastodon_api/views/notification_view_test.exs
+++ b/test/web/mastodon_api/views/notification_view_test.exs
@@ -78,7 +78,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do
user = insert(:user)
another_user = insert(:user)
{:ok, create_activity} = CommonAPI.post(user, %{status: "hey"})
- {:ok, reblog_activity, _object} = CommonAPI.repeat(create_activity.id, another_user)
+ {:ok, reblog_activity} = CommonAPI.repeat(create_activity.id, another_user)
{:ok, [notification]} = Notification.create_notifications(reblog_activity)
reblog_activity = Activity.get_by_id(create_activity.id)
diff --git a/test/web/mastodon_api/views/status_view_test.exs b/test/web/mastodon_api/views/status_view_test.exs
index 43e3bdca1..5cbadf0fc 100644
--- a/test/web/mastodon_api/views/status_view_test.exs
+++ b/test/web/mastodon_api/views/status_view_test.exs
@@ -442,7 +442,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
user = insert(:user)
activity = insert(:note_activity)
- {:ok, reblog, _} = CommonAPI.repeat(activity.id, user)
+ {:ok, reblog} = CommonAPI.repeat(activity.id, user)
represented = StatusView.render("show.json", %{for: user, activity: reblog})
@@ -600,7 +600,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do
status: "˙˙ɐʎns"
})
- {:ok, activity, _object} = CommonAPI.repeat(activity.id, other_user)
+ {:ok, activity} = CommonAPI.repeat(activity.id, other_user)
result = StatusView.render("show.json", %{activity: activity, for: user})
diff --git a/test/web/push/impl_test.exs b/test/web/push/impl_test.exs
index 2acd0939f..a826b24c9 100644
--- a/test/web/push/impl_test.exs
+++ b/test/web/push/impl_test.exs
@@ -151,7 +151,7 @@ defmodule Pleroma.Web.Push.ImplTest do
"Lorem ipsum dolor sit amet, consectetur :firefox: adipiscing elit. Fusce sagittis finibus turpis."
})
- {:ok, announce_activity, _} = CommonAPI.repeat(activity.id, user)
+ {:ok, announce_activity} = CommonAPI.repeat(activity.id, user)
object = Object.normalize(activity)
assert Impl.format_body(%{activity: announce_activity}, user, object) ==
diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs
index 95b7d1420..cb4595bb6 100644
--- a/test/web/streamer/streamer_test.exs
+++ b/test/web/streamer/streamer_test.exs
@@ -106,7 +106,7 @@ defmodule Pleroma.Web.StreamerTest do
other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{status: "hey"})
- {:ok, announce, _} = CommonAPI.repeat(activity.id, user)
+ {:ok, announce} = CommonAPI.repeat(activity.id, user)
assert_receive {:render_with_user, Pleroma.Web.StreamerView, "update.json", ^announce}
refute Streamer.filtered_by_user?(user, announce)
@@ -427,7 +427,7 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, create_activity} = CommonAPI.post(user3, %{status: "I'm kawen"})
Streamer.get_topic_and_add_socket("user", user1)
- {:ok, announce_activity, _} = CommonAPI.repeat(create_activity.id, user2)
+ {:ok, announce_activity} = CommonAPI.repeat(create_activity.id, user2)
assert_receive {:render_with_user, _, _, ^announce_activity}
assert Streamer.filtered_by_user?(user1, announce_activity)
end
@@ -440,7 +440,7 @@ defmodule Pleroma.Web.StreamerTest do
{:ok, create_activity} = CommonAPI.post(user1, %{status: "I'm kawen"})
Streamer.get_topic_and_add_socket("user", user1)
- {:ok, _favorite_activity, _} = CommonAPI.repeat(create_activity.id, user2)
+ {:ok, _announce_activity} = CommonAPI.repeat(create_activity.id, user2)
assert_receive {:render_with_user, _, "notification.json", notif}
assert Streamer.filtered_by_user?(user1, notif)
--
cgit v1.2.3
From c76267afb9ba6fa79d949c51d8ff72c75989a4f5 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 21 May 2020 13:31:52 +0200
Subject: Credo fixes.
---
test/web/activity_pub/transmogrifier/announce_handling_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier/announce_handling_test.exs b/test/web/activity_pub/transmogrifier/announce_handling_test.exs
index 50bcb307f..e895636b5 100644
--- a/test/web/activity_pub/transmogrifier/announce_handling_test.exs
+++ b/test/web/activity_pub/transmogrifier/announce_handling_test.exs
@@ -7,8 +7,8 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnnounceHandlingTest do
alias Pleroma.Activity
alias Pleroma.Object
- alias Pleroma.Web.CommonAPI
alias Pleroma.Web.ActivityPub.Transmogrifier
+ alias Pleroma.Web.CommonAPI
import Pleroma.Factory
--
cgit v1.2.3
From cdc6ba8d7bca3660c5c431979eae43231f339d6a Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 21 May 2020 13:58:18 +0200
Subject: AnnounceValidator: Check for announcability
---
test/web/activity_pub/object_validator_test.exs | 29 +++++++++++++++++++++++++
1 file changed, 29 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index e24e0f913..84e5edd05 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -342,5 +342,34 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
assert {:actor, {"already announced this object", []}} in cng.errors
assert {:object, {"already announced by this actor", []}} in cng.errors
end
+
+ test "returns an error if the actor can't announce the object", %{
+ announcer: announcer,
+ user: user
+ } do
+ {:ok, post_activity} =
+ CommonAPI.post(user, %{status: "a secret post", visibility: "private"})
+
+ object = Object.normalize(post_activity, false)
+
+ # Another user can't announce it
+ {:ok, announce, []} = Builder.announce(announcer, object, public: false)
+
+ {:error, cng} = ObjectValidator.validate(announce, [])
+
+ assert {:actor, {"can not announce this object", []}} in cng.errors
+
+ # The actor of the object can announce it
+ {:ok, announce, []} = Builder.announce(user, object, public: false)
+
+ assert {:ok, _, _} = ObjectValidator.validate(announce, [])
+
+ # The actor of the object can not announce it publicly
+ {:ok, announce, []} = Builder.announce(user, object, public: true)
+
+ {:error, cng} = ObjectValidator.validate(announce, [])
+
+ assert {:actor, {"can not announce this object publicly", []}} in cng.errors
+ end
end
end
--
cgit v1.2.3
From bf1b221f94a53c90cda832e9bfb6c5fa0e6524f2 Mon Sep 17 00:00:00 2001
From: lain
Date: Thu, 21 May 2020 14:12:32 +0200
Subject: Credo fixes for the credo god.
---
test/web/activity_pub/object_validator_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/object_validator_test.exs b/test/web/activity_pub/object_validator_test.exs
index 84e5edd05..7953eecf2 100644
--- a/test/web/activity_pub/object_validator_test.exs
+++ b/test/web/activity_pub/object_validator_test.exs
@@ -364,7 +364,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidatorTest do
assert {:ok, _, _} = ObjectValidator.validate(announce, [])
- # The actor of the object can not announce it publicly
+ # The actor of the object can not announce it publicly
{:ok, announce, []} = Builder.announce(user, object, public: true)
{:error, cng} = ObjectValidator.validate(announce, [])
--
cgit v1.2.3
From 45d2c4157fc264dacdca0f17268d3a33f364801f Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Thu, 21 May 2020 14:03:38 +0400
Subject: Add OpenAPI spec for AdminAPI.StatusController
---
.../controllers/admin_api_controller_test.exs | 24 +++++++++-----
.../controllers/status_controller_test.exs | 37 ++++++++++++++--------
2 files changed, 39 insertions(+), 22 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/controllers/admin_api_controller_test.exs b/test/web/admin_api/controllers/admin_api_controller_test.exs
index 2c317e0fe..a0c11a354 100644
--- a/test/web/admin_api/controllers/admin_api_controller_test.exs
+++ b/test/web/admin_api/controllers/admin_api_controller_test.exs
@@ -350,7 +350,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}")
- assert "Not found" == json_response(conn, 404)
+ assert %{"error" => "Not found"} == json_response(conn, 404)
end
end
@@ -683,7 +683,10 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
assert json_response(conn, :bad_request) ==
- "To send invites you need to set the `invites_enabled` option to true."
+ %{
+ "error" =>
+ "To send invites you need to set the `invites_enabled` option to true."
+ }
end
test "it returns 500 if `registrations_open` is enabled", %{conn: conn} do
@@ -693,7 +696,10 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
conn = post(conn, "/api/pleroma/admin/users/email_invite?email=foo@bar.com&name=JD")
assert json_response(conn, :bad_request) ==
- "To send invites you need to set the `registrations_open` option to false."
+ %{
+ "error" =>
+ "To send invites you need to set the `registrations_open` option to false."
+ }
end
end
@@ -1307,7 +1313,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
|> put("/api/pleroma/admin/users/disable_mfa", %{nickname: "nickname"})
|> json_response(404)
- assert response == "Not found"
+ assert response == %{"error" => "Not found"}
end
end
@@ -1413,7 +1419,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
test "with invalid token", %{conn: conn} do
conn = post(conn, "/api/pleroma/admin/users/revoke_invite", %{"token" => "foo"})
- assert json_response(conn, :not_found) == "Not found"
+ assert json_response(conn, :not_found) == %{"error" => "Not found"}
end
end
@@ -1440,7 +1446,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
test "returns 404 when report id is invalid", %{conn: conn} do
conn = get(conn, "/api/pleroma/admin/reports/test")
- assert json_response(conn, :not_found) == "Not found"
+ assert json_response(conn, :not_found) == %{"error" => "Not found"}
end
end
@@ -1705,7 +1711,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
conn = get(conn, "/api/pleroma/admin/config")
assert json_response(conn, 400) ==
- "To use this endpoint you need to enable configuration from database."
+ %{
+ "error" => "To use this endpoint you need to enable configuration from database."
+ }
end
test "with settings only in db", %{conn: conn} do
@@ -1827,7 +1835,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
conn = post(conn, "/api/pleroma/admin/config", %{"configs" => []})
assert json_response(conn, 400) ==
- "To use this endpoint you need to enable configuration from database."
+ %{"error" => "To use this endpoint you need to enable configuration from database."}
end
describe "POST /api/pleroma/admin/config" do
diff --git a/test/web/admin_api/controllers/status_controller_test.exs b/test/web/admin_api/controllers/status_controller_test.exs
index 8ecc78491..124d8dc2e 100644
--- a/test/web/admin_api/controllers/status_controller_test.exs
+++ b/test/web/admin_api/controllers/status_controller_test.exs
@@ -30,7 +30,7 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
test "not found", %{conn: conn} do
assert conn
|> get("/api/pleroma/admin/statuses/not_found")
- |> json_response(:not_found)
+ |> json_response_and_validate_schema(:not_found)
end
test "shows activity", %{conn: conn} do
@@ -39,7 +39,7 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
response =
conn
|> get("/api/pleroma/admin/statuses/#{activity.id}")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert response["id"] == activity.id
end
@@ -55,8 +55,9 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
test "toggle sensitive flag", %{conn: conn, id: id, admin: admin} do
response =
conn
+ |> put_req_header("content-type", "application/json")
|> put("/api/pleroma/admin/statuses/#{id}", %{"sensitive" => "true"})
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert response["sensitive"]
@@ -67,8 +68,9 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
response =
conn
+ |> put_req_header("content-type", "application/json")
|> put("/api/pleroma/admin/statuses/#{id}", %{"sensitive" => "false"})
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
refute response["sensitive"]
end
@@ -76,8 +78,9 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
test "change visibility flag", %{conn: conn, id: id, admin: admin} do
response =
conn
+ |> put_req_header("content-type", "application/json")
|> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "public"})
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert response["visibility"] == "public"
@@ -88,23 +91,29 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
response =
conn
+ |> put_req_header("content-type", "application/json")
|> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "private"})
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert response["visibility"] == "private"
response =
conn
+ |> put_req_header("content-type", "application/json")
|> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "unlisted"})
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
assert response["visibility"] == "unlisted"
end
test "returns 400 when visibility is unknown", %{conn: conn, id: id} do
- conn = put(conn, "/api/pleroma/admin/statuses/#{id}", %{visibility: "test"})
+ conn =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> put("/api/pleroma/admin/statuses/#{id}", %{visibility: "test"})
- assert json_response(conn, :bad_request) == "Unsupported visibility"
+ assert %{"error" => "test - Invalid value for enum."} =
+ json_response_and_validate_schema(conn, :bad_request)
end
end
@@ -118,7 +127,7 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
test "deletes status", %{conn: conn, id: id, admin: admin} do
conn
|> delete("/api/pleroma/admin/statuses/#{id}")
- |> json_response(:ok)
+ |> json_response_and_validate_schema(:ok)
refute Activity.get_by_id(id)
@@ -131,7 +140,7 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
test "returns 404 when the status does not exist", %{conn: conn} do
conn = delete(conn, "/api/pleroma/admin/statuses/test")
- assert json_response(conn, :not_found) == "Not found"
+ assert json_response_and_validate_schema(conn, :not_found) == %{"error" => "Not found"}
end
end
@@ -151,7 +160,7 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
response =
conn
|> get("/api/pleroma/admin/statuses")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
refute "private" in Enum.map(response, & &1["visibility"])
assert length(response) == 3
@@ -166,7 +175,7 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
response =
conn
|> get("/api/pleroma/admin/statuses?local_only=true")
- |> json_response(200)
+ |> json_response_and_validate_schema(200)
assert length(response) == 1
end
@@ -179,7 +188,7 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do
{:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "private"})
{:ok, _} = CommonAPI.post(user, %{status: ".", visibility: "public"})
conn = get(conn, "/api/pleroma/admin/statuses?godmode=true")
- assert json_response(conn, 200) |> length() == 3
+ assert json_response_and_validate_schema(conn, 200) |> length() == 3
end
end
end
--
cgit v1.2.3
From bcb549531ff5f90253adc1b8cc2900c348f20175 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 22 May 2020 14:38:28 +0200
Subject: EmojiReactionController: Return more appropriate error.
---
.../web/pleroma_api/controllers/emoji_reaction_controller_test.exs | 7 +++++++
1 file changed, 7 insertions(+)
(limited to 'test')
diff --git a/test/web/pleroma_api/controllers/emoji_reaction_controller_test.exs b/test/web/pleroma_api/controllers/emoji_reaction_controller_test.exs
index ee66ebf87..e1bb5ebfe 100644
--- a/test/web/pleroma_api/controllers/emoji_reaction_controller_test.exs
+++ b/test/web/pleroma_api/controllers/emoji_reaction_controller_test.exs
@@ -33,6 +33,13 @@ defmodule Pleroma.Web.PleromaAPI.EmojiReactionControllerTest do
assert result["pleroma"]["emoji_reactions"] == [
%{"name" => "☕", "count" => 1, "me" => true}
]
+
+ # Reacting with a non-emoji
+ assert conn
+ |> assign(:user, other_user)
+ |> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"]))
+ |> put("/api/v1/pleroma/statuses/#{activity.id}/reactions/x")
+ |> json_response_and_validate_schema(400)
end
test "DELETE /api/v1/pleroma/statuses/:id/reactions/:emoji", %{conn: conn} do
--
cgit v1.2.3
From ca755f9a73649375096850ce7849688f45162de8 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 22 May 2020 16:15:29 +0200
Subject: ActivityPubController: Add Mastodon compatibility route.
---
.../activity_pub/activity_pub_controller_test.exs | 29 +++++++++++++++++++++-
1 file changed, 28 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs
index c432c90e3..b247163ec 100644
--- a/test/web/activity_pub/activity_pub_controller_test.exs
+++ b/test/web/activity_pub/activity_pub_controller_test.exs
@@ -6,7 +6,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
use Pleroma.Web.ConnCase
use Oban.Testing, repo: Pleroma.Repo
- import Pleroma.Factory
alias Pleroma.Activity
alias Pleroma.Config
alias Pleroma.Delivery
@@ -19,8 +18,13 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
alias Pleroma.Web.ActivityPub.UserView
alias Pleroma.Web.ActivityPub.Utils
alias Pleroma.Web.CommonAPI
+ alias Pleroma.Web.Endpoint
alias Pleroma.Workers.ReceiverWorker
+ import Pleroma.Factory
+
+ require Pleroma.Constants
+
setup_all do
Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
:ok
@@ -168,6 +172,29 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
end
end
+ describe "mastodon compatibility routes" do
+ test "it returns a json representation of the object with accept application/json", %{
+ conn: conn
+ } do
+ {:ok, object} =
+ %{
+ "type" => "Note",
+ "content" => "hey",
+ "id" => Endpoint.url() <> "/users/raymoo/statuses/999999999",
+ "actor" => Endpoint.url() <> "/users/raymoo",
+ "to" => [Pleroma.Constants.as_public()]
+ }
+ |> Object.create()
+
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> get("/users/raymoo/statuses/999999999")
+
+ assert json_response(conn, 200) == ObjectView.render("object.json", %{object: object})
+ end
+ end
+
describe "/objects/:uuid" do
test "it returns a json representation of the object with accept application/json", %{
conn: conn
--
cgit v1.2.3
From ba106aa9c8d4854c2fe0f6bb02091bb3bd6719d7 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Fri, 22 May 2020 18:15:36 +0400
Subject: Fix notifications mark as read API
---
.../pleroma_api/controllers/notification_controller_test.exs | 11 ++++++++---
1 file changed, 8 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/pleroma_api/controllers/notification_controller_test.exs b/test/web/pleroma_api/controllers/notification_controller_test.exs
index 7c5ace804..bb4fe6c49 100644
--- a/test/web/pleroma_api/controllers/notification_controller_test.exs
+++ b/test/web/pleroma_api/controllers/notification_controller_test.exs
@@ -23,7 +23,8 @@ defmodule Pleroma.Web.PleromaAPI.NotificationControllerTest do
response =
conn
- |> post("/api/v1/pleroma/notifications/read?id=#{notification1.id}")
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/pleroma/notifications/read", %{id: notification1.id})
|> json_response_and_validate_schema(:ok)
assert %{"pleroma" => %{"is_seen" => true}} = response
@@ -41,7 +42,8 @@ defmodule Pleroma.Web.PleromaAPI.NotificationControllerTest do
[response1, response2] =
conn
- |> post("/api/v1/pleroma/notifications/read?max_id=#{notification2.id}")
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/pleroma/notifications/read", %{max_id: notification2.id})
|> json_response_and_validate_schema(:ok)
assert %{"pleroma" => %{"is_seen" => true}} = response1
@@ -54,7 +56,10 @@ defmodule Pleroma.Web.PleromaAPI.NotificationControllerTest do
test "it returns error when notification not found", %{conn: conn} do
response =
conn
- |> post("/api/v1/pleroma/notifications/read?id=22222222222222")
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/pleroma/notifications/read", %{
+ id: 22_222_222_222_222
+ })
|> json_response_and_validate_schema(:bad_request)
assert response == %{"error" => "Cannot get notification"}
--
cgit v1.2.3
From 8a4bd9e5d17bd1acb5c5a61b85ac125202a4aaa4 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 22 May 2020 16:47:22 +0200
Subject: OStatusController: Add Mastodon compatibility route for objects.
---
test/web/ostatus/ostatus_controller_test.exs | 35 ++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
(limited to 'test')
diff --git a/test/web/ostatus/ostatus_controller_test.exs b/test/web/ostatus/ostatus_controller_test.exs
index bb349cb19..266fe2f45 100644
--- a/test/web/ostatus/ostatus_controller_test.exs
+++ b/test/web/ostatus/ostatus_controller_test.exs
@@ -10,7 +10,11 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do
alias Pleroma.Config
alias Pleroma.Object
alias Pleroma.User
+ alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.CommonAPI
+ alias Pleroma.Web.Endpoint
+
+ require Pleroma.Constants
setup_all do
Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
@@ -19,6 +23,37 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do
setup do: clear_config([:instance, :federating], true)
+ describe "Mastodon compatibility routes" do
+ setup %{conn: conn} do
+ conn = put_req_header(conn, "accept", "text/html")
+ %{conn: conn}
+ end
+
+ test "redirects to /notice/:id for html format", %{conn: conn} do
+ {:ok, object} =
+ %{
+ "type" => "Note",
+ "content" => "hey",
+ "id" => Endpoint.url() <> "/users/raymoo/statuses/999999999",
+ "actor" => Endpoint.url() <> "/users/raymoo",
+ "to" => [Pleroma.Constants.as_public()]
+ }
+ |> Object.create()
+
+ {:ok, activity, _} =
+ %{
+ "type" => "Create",
+ "object" => object.data["id"],
+ "actor" => object.data["actor"],
+ "to" => object.data["to"]
+ }
+ |> ActivityPub.persist(local: true)
+
+ conn = get(conn, "/users/raymoo/statuses/999999999")
+ assert redirected_to(conn) == "/notice/#{activity.id}"
+ end
+ end
+
# Note: see ActivityPubControllerTest for JSON format tests
describe "GET /objects/:uuid (text/html)" do
setup %{conn: conn} do
--
cgit v1.2.3
From 355aa3bdc78465a42a9e0b20baaefd4fba04f596 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 22 May 2020 17:06:12 +0200
Subject: ActivityPubController: Add Mastodon activity compat route.
---
.../activity_pub/activity_pub_controller_test.exs | 32 ++++++++++++++++++++++
test/web/ostatus/ostatus_controller_test.exs | 1 +
2 files changed, 33 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs
index b247163ec..dd2a48a61 100644
--- a/test/web/activity_pub/activity_pub_controller_test.exs
+++ b/test/web/activity_pub/activity_pub_controller_test.exs
@@ -13,6 +13,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
alias Pleroma.Object
alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
+ alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.ObjectView
alias Pleroma.Web.ActivityPub.Relay
alias Pleroma.Web.ActivityPub.UserView
@@ -193,6 +194,37 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
assert json_response(conn, 200) == ObjectView.render("object.json", %{object: object})
end
+
+ test "it returns a json representation of the activity with accept application/json", %{
+ conn: conn
+ } do
+ {:ok, object} =
+ %{
+ "type" => "Note",
+ "content" => "hey",
+ "id" => Endpoint.url() <> "/users/raymoo/statuses/999999999",
+ "actor" => Endpoint.url() <> "/users/raymoo",
+ "to" => [Pleroma.Constants.as_public()]
+ }
+ |> Object.create()
+
+ {:ok, activity, _} =
+ %{
+ "id" => object.data["id"] <> "/activity",
+ "type" => "Create",
+ "object" => object.data["id"],
+ "actor" => object.data["actor"],
+ "to" => object.data["to"]
+ }
+ |> ActivityPub.persist(local: true)
+
+ conn =
+ conn
+ |> put_req_header("accept", "application/json")
+ |> get("/users/raymoo/statuses/999999999/activity")
+
+ assert json_response(conn, 200) == ObjectView.render("object.json", %{object: activity})
+ end
end
describe "/objects/:uuid" do
diff --git a/test/web/ostatus/ostatus_controller_test.exs b/test/web/ostatus/ostatus_controller_test.exs
index 266fe2f45..0f973d5b6 100644
--- a/test/web/ostatus/ostatus_controller_test.exs
+++ b/test/web/ostatus/ostatus_controller_test.exs
@@ -42,6 +42,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do
{:ok, activity, _} =
%{
+ "id" => object.data["id"] <> "/activity",
"type" => "Create",
"object" => object.data["id"],
"actor" => object.data["actor"],
--
cgit v1.2.3
From 91c8467582d1b4b5ad12256292e86dc1c54f0234 Mon Sep 17 00:00:00 2001
From: lain
Date: Fri, 22 May 2020 17:11:59 +0200
Subject: OStatusController: Add Mastodon activity compat route.
---
test/web/ostatus/ostatus_controller_test.exs | 15 ++++++++++++---
1 file changed, 12 insertions(+), 3 deletions(-)
(limited to 'test')
diff --git a/test/web/ostatus/ostatus_controller_test.exs b/test/web/ostatus/ostatus_controller_test.exs
index 0f973d5b6..ee498f4b5 100644
--- a/test/web/ostatus/ostatus_controller_test.exs
+++ b/test/web/ostatus/ostatus_controller_test.exs
@@ -26,10 +26,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do
describe "Mastodon compatibility routes" do
setup %{conn: conn} do
conn = put_req_header(conn, "accept", "text/html")
- %{conn: conn}
- end
- test "redirects to /notice/:id for html format", %{conn: conn} do
{:ok, object} =
%{
"type" => "Note",
@@ -50,9 +47,21 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do
}
|> ActivityPub.persist(local: true)
+ %{conn: conn, activity: activity}
+ end
+
+ test "redirects to /notice/:id for html format", %{conn: conn, activity: activity} do
conn = get(conn, "/users/raymoo/statuses/999999999")
assert redirected_to(conn) == "/notice/#{activity.id}"
end
+
+ test "redirects to /notice/:id for html format for activity", %{
+ conn: conn,
+ activity: activity
+ } do
+ conn = get(conn, "/users/raymoo/statuses/999999999/activity")
+ assert redirected_to(conn) == "/notice/#{activity.id}"
+ end
end
# Note: see ActivityPubControllerTest for JSON format tests
--
cgit v1.2.3
From cc82229ba70e054acfdea07a195c1b11961ea1bc Mon Sep 17 00:00:00 2001
From: Roman Chvanikov
Date: Fri, 22 May 2020 18:19:25 +0300
Subject: Add filename_display_max_length config
---
test/web/common_api/common_api_utils_test.exs | 41 +++++++++++++++++++++------
1 file changed, 32 insertions(+), 9 deletions(-)
(limited to 'test')
diff --git a/test/web/common_api/common_api_utils_test.exs b/test/web/common_api/common_api_utils_test.exs
index d7d2d10d5..e67c10b93 100644
--- a/test/web/common_api/common_api_utils_test.exs
+++ b/test/web/common_api/common_api_utils_test.exs
@@ -14,18 +14,41 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do
@public_address "https://www.w3.org/ns/activitystreams#Public"
- test "it adds attachment links to a given text and attachment set" do
- name =
- "Sakura%20Mana%20%E2%80%93%20Turned%20on%20by%20a%20Senior%20OL%20with%20a%20Temptating%20Tight%20Skirt-s%20Full%20Hipline%20and%20Panty%20Shot-%20Beautiful%20Thick%20Thighs-%20and%20Erotic%20Ass-%20-2015-%20--%20Oppaitime%208-28-2017%206-50-33%20PM.png"
+ describe "add_attachments/2" do
+ setup do
+ name =
+ "Sakura Mana – Turned on by a Senior OL with a Temptating Tight Skirt-s Full Hipline and Panty Shot- Beautiful Thick Thighs- and Erotic Ass- -2015- -- Oppaitime 8-28-2017 6-50-33 PM.png"
- attachment = %{
- "url" => [%{"href" => name}]
- }
+ attachment = %{
+ "url" => [%{"href" => URI.encode(name)}]
+ }
- res = Utils.add_attachments("", [attachment])
+ %{name: name, attachment: attachment}
+ end
+
+ test "it adds attachment links to a given text and attachment set", %{
+ name: name,
+ attachment: attachment
+ } do
+ len = 10
+ clear_config([Pleroma.Upload, :filename_display_max_length], len)
- assert res ==
- "
Sakura Mana – Turned on by a Se…"
+ expected =
+ "
#{String.slice(name, 0..len)}…"
+
+ assert Utils.add_attachments("", [attachment]) == expected
+ end
+
+ test "doesn't truncate file name if config for truncate is set to 0", %{
+ name: name,
+ attachment: attachment
+ } do
+ clear_config([Pleroma.Upload, :filename_display_max_length], 0)
+
+ expected = "
#{name}"
+
+ assert Utils.add_attachments("", [attachment]) == expected
+ end
end
describe "it confirms the password given is the current users password" do
--
cgit v1.2.3
From d0c26956da160b2fbfd4855ca7fe31eeebe6528d Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 25 May 2020 12:46:14 +0200
Subject: User: Don't error out if we want to refresh a user but can't
---
.../activity_pub/activity_pub_controller_test.exs | 30 ++++++++++++++++++++++
1 file changed, 30 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs
index dd2a48a61..24edab41a 100644
--- a/test/web/activity_pub/activity_pub_controller_test.exs
+++ b/test/web/activity_pub/activity_pub_controller_test.exs
@@ -451,6 +451,36 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do
assert Activity.get_by_ap_id(data["id"])
end
+ @tag capture_log: true
+ test "it inserts an incoming activity into the database" <>
+ "even if we can't fetch the user but have it in our db",
+ %{conn: conn} do
+ user =
+ insert(:user,
+ ap_id: "https://mastodon.example.org/users/raymoo",
+ ap_enabled: true,
+ local: false,
+ last_refreshed_at: nil
+ )
+
+ data =
+ File.read!("test/fixtures/mastodon-post-activity.json")
+ |> Poison.decode!()
+ |> Map.put("actor", user.ap_id)
+ |> put_in(["object", "attridbutedTo"], user.ap_id)
+
+ conn =
+ conn
+ |> assign(:valid_signature, true)
+ |> put_req_header("content-type", "application/activity+json")
+ |> post("/inbox", data)
+
+ assert "ok" == json_response(conn, 200)
+
+ ObanHelpers.perform(all_enqueued(worker: ReceiverWorker))
+ assert Activity.get_by_ap_id(data["id"])
+ end
+
test "it clears `unreachable` federation status of the sender", %{conn: conn} do
data = File.read!("test/fixtures/mastodon-post-activity.json") |> Poison.decode!()
--
cgit v1.2.3
From 0c970a9d44fc0ceddbb52483f6f2fab11243e0ca Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 25 May 2020 12:49:38 +0200
Subject: UserTest: Add test for user refreshing.
---
test/user_test.exs | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
(limited to 'test')
diff --git a/test/user_test.exs b/test/user_test.exs
index 45125f704..3556ef1b4 100644
--- a/test/user_test.exs
+++ b/test/user_test.exs
@@ -586,6 +586,26 @@ defmodule Pleroma.UserTest do
refute user.last_refreshed_at == orig_user.last_refreshed_at
end
+
+ @tag capture_log: true
+ test "it returns the old user if stale, but unfetchable" do
+ a_week_ago = NaiveDateTime.add(NaiveDateTime.utc_now(), -604_800)
+
+ orig_user =
+ insert(
+ :user,
+ local: false,
+ nickname: "admin@mastodon.example.org",
+ ap_id: "http://mastodon.example.org/users/raymoo",
+ last_refreshed_at: a_week_ago
+ )
+
+ assert orig_user.last_refreshed_at == a_week_ago
+
+ {:ok, user} = User.get_or_fetch_by_ap_id("http://mastodon.example.org/users/raymoo")
+
+ assert user.last_refreshed_at == orig_user.last_refreshed_at
+ end
end
test "returns an ap_id for a user" do
--
cgit v1.2.3
From 3bec0d2e50a0c468508ae884a3e5dc371106501e Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 25 May 2020 12:59:42 +0200
Subject: Factory: Set users to be ap_enabled by default.
---
test/support/factory.ex | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/support/factory.ex b/test/support/factory.ex
index d4284831c..6e3676aca 100644
--- a/test/support/factory.ex
+++ b/test/support/factory.ex
@@ -34,7 +34,8 @@ defmodule Pleroma.Factory do
last_digest_emailed_at: NaiveDateTime.utc_now(),
last_refreshed_at: NaiveDateTime.utc_now(),
notification_settings: %Pleroma.User.NotificationSetting{},
- multi_factor_authentication_settings: %Pleroma.MFA.Settings{}
+ multi_factor_authentication_settings: %Pleroma.MFA.Settings{},
+ ap_enabled: true
}
%{
--
cgit v1.2.3
From aeb0875025cf37ad8cefe43c637f56a5a16f8628 Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 25 May 2020 13:48:47 +0200
Subject: StealEmojiPolicyTest: Fix flaky test.
---
test/web/activity_pub/mrf/steal_emoji_policy_test.exs | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/mrf/steal_emoji_policy_test.exs b/test/web/activity_pub/mrf/steal_emoji_policy_test.exs
index 8882c8c13..0e7e57c77 100644
--- a/test/web/activity_pub/mrf/steal_emoji_policy_test.exs
+++ b/test/web/activity_pub/mrf/steal_emoji_policy_test.exs
@@ -14,8 +14,6 @@ defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicyTest do
end
setup do
- clear_config(:mrf_steal_emoji)
-
emoji_path = Path.join(Config.get([:instance, :static_dir]), "emoji/stolen")
File.rm_rf!(emoji_path)
File.mkdir!(emoji_path)
@@ -53,8 +51,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicyTest do
}
}
- Config.put([:mrf_steal_emoji, :hosts], ["example.org"])
- Config.put([:mrf_steal_emoji, :size_limit], 284_468)
+ clear_config([:mrf_steal_emoji, :hosts], ["example.org"])
+ clear_config([:mrf_steal_emoji, :size_limit], 284_468)
assert {:ok, message} == StealEmojiPolicy.filter(message)
--
cgit v1.2.3
From 2dff37604192b086ede4a00d68b886dbec93f3c9 Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 25 May 2020 13:48:47 +0200
Subject: StealEmojiPolicyTest: Fix flaky test.
---
test/web/activity_pub/mrf/steal_emoji_policy_test.exs | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/mrf/steal_emoji_policy_test.exs b/test/web/activity_pub/mrf/steal_emoji_policy_test.exs
index 8882c8c13..0e7e57c77 100644
--- a/test/web/activity_pub/mrf/steal_emoji_policy_test.exs
+++ b/test/web/activity_pub/mrf/steal_emoji_policy_test.exs
@@ -14,8 +14,6 @@ defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicyTest do
end
setup do
- clear_config(:mrf_steal_emoji)
-
emoji_path = Path.join(Config.get([:instance, :static_dir]), "emoji/stolen")
File.rm_rf!(emoji_path)
File.mkdir!(emoji_path)
@@ -53,8 +51,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicyTest do
}
}
- Config.put([:mrf_steal_emoji, :hosts], ["example.org"])
- Config.put([:mrf_steal_emoji, :size_limit], 284_468)
+ clear_config([:mrf_steal_emoji, :hosts], ["example.org"])
+ clear_config([:mrf_steal_emoji, :size_limit], 284_468)
assert {:ok, message} == StealEmojiPolicy.filter(message)
--
cgit v1.2.3
From 5d5db7e5b7f722f7735798f9b9ed8069091726de Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 25 May 2020 14:00:18 +0200
Subject: StealEmojiPolicyTest: Clean up.
---
test/web/activity_pub/mrf/steal_emoji_policy_test.exs | 6 ++++++
1 file changed, 6 insertions(+)
(limited to 'test')
diff --git a/test/web/activity_pub/mrf/steal_emoji_policy_test.exs b/test/web/activity_pub/mrf/steal_emoji_policy_test.exs
index 0e7e57c77..3f8222736 100644
--- a/test/web/activity_pub/mrf/steal_emoji_policy_test.exs
+++ b/test/web/activity_pub/mrf/steal_emoji_policy_test.exs
@@ -19,6 +19,12 @@ defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicyTest do
File.mkdir!(emoji_path)
Pleroma.Emoji.reload()
+
+ on_exit(fn ->
+ File.rm_rf!(emoji_path)
+ end)
+
+ :ok
end
test "does nothing by default" do
--
cgit v1.2.3
From 6bd7070b00a8d0ac64292f4c7152b71bee5f6b69 Mon Sep 17 00:00:00 2001
From: lain
Date: Mon, 25 May 2020 15:08:43 +0200
Subject: Transmogrifier: Use a simpler way to get mentions.
---
test/web/activity_pub/transmogrifier_test.exs | 33 +++++++++++++++------------
1 file changed, 19 insertions(+), 14 deletions(-)
(limited to 'test')
diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs
index 356004d48..94d8552e8 100644
--- a/test/web/activity_pub/transmogrifier_test.exs
+++ b/test/web/activity_pub/transmogrifier_test.exs
@@ -1094,23 +1094,28 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
{:ok, activity} =
CommonAPI.post(user, %{status: "hey, @#{other_user.nickname}, how are ya? #2hu"})
- {:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
- object = modified["object"]
+ with_mock Pleroma.Notification,
+ get_notified_from_activity: fn _, _ -> [] end do
+ {:ok, modified} = Transmogrifier.prepare_outgoing(activity.data)
- expected_mention = %{
- "href" => other_user.ap_id,
- "name" => "@#{other_user.nickname}",
- "type" => "Mention"
- }
+ object = modified["object"]
- expected_tag = %{
- "href" => Pleroma.Web.Endpoint.url() <> "/tags/2hu",
- "type" => "Hashtag",
- "name" => "#2hu"
- }
+ expected_mention = %{
+ "href" => other_user.ap_id,
+ "name" => "@#{other_user.nickname}",
+ "type" => "Mention"
+ }
- assert Enum.member?(object["tag"], expected_tag)
- assert Enum.member?(object["tag"], expected_mention)
+ expected_tag = %{
+ "href" => Pleroma.Web.Endpoint.url() <> "/tags/2hu",
+ "type" => "Hashtag",
+ "name" => "#2hu"
+ }
+
+ refute called(Pleroma.Notification.get_notified_from_activity(:_, :_))
+ assert Enum.member?(object["tag"], expected_tag)
+ assert Enum.member?(object["tag"], expected_mention)
+ end
end
test "it adds the sensitive property" do
--
cgit v1.2.3
From e32b7ae044be284c4b0d596d2effd1c7801873b3 Mon Sep 17 00:00:00 2001
From: Egor Kislitsyn
Date: Mon, 25 May 2020 23:01:37 +0400
Subject: Skip failing `:crypt` test on mac
---
test/plugs/authentication_plug_test.exs | 1 +
1 file changed, 1 insertion(+)
(limited to 'test')
diff --git a/test/plugs/authentication_plug_test.exs b/test/plugs/authentication_plug_test.exs
index 3c70c1747..777ae15ae 100644
--- a/test/plugs/authentication_plug_test.exs
+++ b/test/plugs/authentication_plug_test.exs
@@ -68,6 +68,7 @@ defmodule Pleroma.Plugs.AuthenticationPlugTest do
assert "$pbkdf2" <> _ = user.password_hash
end
+ @tag :skip_on_mac
test "with a crypt hash, it updates to a pkbdf2 hash", %{conn: conn} do
user =
insert(:user,
--
cgit v1.2.3
From d7a57004ef975e2cf02facb9d80cff287a5d6d3b Mon Sep 17 00:00:00 2001
From: Ivan Tashkinov
Date: Mon, 25 May 2020 23:27:47 +0300
Subject: [#1501] Made user feed contain public and unlisted activities.
---
test/web/feed/user_controller_test.exs | 26 +++++++++++++++++++++++++-
1 file changed, 25 insertions(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/feed/user_controller_test.exs b/test/web/feed/user_controller_test.exs
index 05ad427c2..fa2ed1ea5 100644
--- a/test/web/feed/user_controller_test.exs
+++ b/test/web/feed/user_controller_test.exs
@@ -11,13 +11,14 @@ defmodule Pleroma.Web.Feed.UserControllerTest do
alias Pleroma.Config
alias Pleroma.Object
alias Pleroma.User
+ alias Pleroma.Web.CommonAPI
setup do: clear_config([:instance, :federating], true)
describe "feed" do
setup do: clear_config([:feed])
- test "gets a feed", %{conn: conn} do
+ test "gets an atom feed", %{conn: conn} do
Config.put(
[:feed, :post_title],
%{max_length: 10, omission: "..."}
@@ -157,6 +158,29 @@ defmodule Pleroma.Web.Feed.UserControllerTest do
assert response(conn, 404)
end
+
+ test "returns feed with public and unlisted activities", %{conn: conn} do
+ user = insert(:user)
+
+ {:ok, _} = CommonAPI.post(user, %{status: "public", visibility: "public"})
+ {:ok, _} = CommonAPI.post(user, %{status: "direct", visibility: "direct"})
+ {:ok, _} = CommonAPI.post(user, %{status: "unlisted", visibility: "unlisted"})
+ {:ok, _} = CommonAPI.post(user, %{status: "private", visibility: "private"})
+
+ resp =
+ conn
+ |> put_req_header("accept", "application/atom+xml")
+ |> get(user_feed_path(conn, :feed, user.nickname))
+ |> response(200)
+
+ activity_titles =
+ resp
+ |> SweetXml.parse()
+ |> SweetXml.xpath(~x"//entry/title/text()"l)
+ |> Enum.sort()
+
+ assert activity_titles == ['public', 'unlisted']
+ end
end
# Note: see ActivityPubControllerTest for JSON format tests
--
cgit v1.2.3
From 3249141588c8f73f1958f782041798fbde05e69f Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Wed, 27 May 2020 09:42:28 +0300
Subject: validate actor type
---
.../controllers/admin_api_controller_test.exs | 35 +++++++++++++++++++---
1 file changed, 31 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/admin_api/controllers/admin_api_controller_test.exs b/test/web/admin_api/controllers/admin_api_controller_test.exs
index 321840a8c..ead840186 100644
--- a/test/web/admin_api/controllers/admin_api_controller_test.exs
+++ b/test/web/admin_api/controllers/admin_api_controller_test.exs
@@ -3191,8 +3191,12 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
end
describe "PATCH /users/:nickname/credentials" do
- test "changes password and email", %{conn: conn, admin: admin} do
+ setup do
user = insert(:user)
+ [user: user]
+ end
+
+ test "changes password and email", %{conn: conn, admin: admin, user: user} do
assert user.password_reset_pending == false
conn =
@@ -3222,9 +3226,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
"@#{admin.nickname} forced password reset for users: @#{user.nickname}"
end
- test "returns 403 if requested by a non-admin" do
- user = insert(:user)
-
+ test "returns 403 if requested by a non-admin", %{user: user} do
conn =
build_conn()
|> assign(:user, user)
@@ -3236,6 +3238,31 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
assert json_response(conn, :forbidden)
end
+
+ test "changes actor type from permitted list", %{conn: conn, user: user} do
+ assert user.actor_type == "Person"
+
+ assert patch(conn, "/api/pleroma/admin/users/#{user.nickname}/credentials", %{
+ "actor_type" => "Service"
+ })
+ |> json_response(200) == %{"status" => "success"}
+
+ updated_user = User.get_by_id(user.id)
+
+ assert updated_user.actor_type == "Service"
+
+ assert patch(conn, "/api/pleroma/admin/users/#{user.nickname}/credentials", %{
+ "actor_type" => "Application"
+ })
+ |> json_response(200) == %{"errors" => %{"actor_type" => "is invalid"}}
+ end
+
+ test "update non existing user", %{conn: conn} do
+ assert patch(conn, "/api/pleroma/admin/users/non-existing/credentials", %{
+ "password" => "new_password"
+ })
+ |> json_response(200) == %{"error" => "Unable to update user."}
+ end
end
describe "PATCH /users/:nickname/force_password_reset" do
--
cgit v1.2.3
From b8e029b5ea33c9267ac26ab7ba598f1cd7be46c2 Mon Sep 17 00:00:00 2001
From: lain
Date: Wed, 27 May 2020 12:41:06 +0200
Subject: Notification: Actually preload objects.
---
test/notification_test.exs | 11 +++++++----
1 file changed, 7 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/notification_test.exs b/test/notification_test.exs
index 3a96721fa..37c255fee 100644
--- a/test/notification_test.exs
+++ b/test/notification_test.exs
@@ -454,8 +454,7 @@ defmodule Pleroma.NotificationTest do
status: "hey again @#{other_user.nickname}!"
})
- [n2, n1] = notifs = Notification.for_user(other_user)
- assert length(notifs) == 2
+ [n2, n1] = Notification.for_user(other_user)
assert n2.id > n1.id
@@ -464,7 +463,9 @@ defmodule Pleroma.NotificationTest do
status: "hey yet again @#{other_user.nickname}!"
})
- Notification.set_read_up_to(other_user, n2.id)
+ [_, read_notification] = Notification.set_read_up_to(other_user, n2.id)
+
+ assert read_notification.activity.object
[n3, n2, n1] = Notification.for_user(other_user)
@@ -972,7 +973,9 @@ defmodule Pleroma.NotificationTest do
{:ok, _activity} = CommonAPI.post(muted, %{status: "hey @#{user.nickname}"})
- assert length(Notification.for_user(user)) == 1
+ [notification] = Notification.for_user(user)
+
+ assert notification.activity.object
end
test "it doesn't return notifications for muted user with notifications" do
--
cgit v1.2.3
From 48fd9be65ae2c25e170e494720a07c126e80e2f6 Mon Sep 17 00:00:00 2001
From: kPherox
Date: Tue, 26 May 2020 09:47:03 +0000
Subject: Exclude post actor from to of relay announce
---
test/web/activity_pub/relay_test.exs | 1 +
1 file changed, 1 insertion(+)
(limited to 'test')
diff --git a/test/web/activity_pub/relay_test.exs b/test/web/activity_pub/relay_test.exs
index dbee8a0f4..b3b573c9b 100644
--- a/test/web/activity_pub/relay_test.exs
+++ b/test/web/activity_pub/relay_test.exs
@@ -108,6 +108,7 @@ defmodule Pleroma.Web.ActivityPub.RelayTest do
assert {:ok, %Activity{} = activity} = Relay.publish(note)
assert activity.data["type"] == "Announce"
assert activity.data["actor"] == service_actor.ap_id
+ assert activity.data["to"] == [service_actor.follower_address]
assert called(Pleroma.Web.Federator.publish(activity))
end
--
cgit v1.2.3
From 78c46fb7ba2aa9e9842d3c7d8331488fd10a3b9d Mon Sep 17 00:00:00 2001
From: rinpatch
Date: Wed, 27 May 2020 19:34:56 +0300
Subject: MediaProxy test: use config macros instead of directly putting values
They were not properly cleaned later and caused trouble for another tests
---
test/web/media_proxy/media_proxy_test.exs | 14 +++-----------
1 file changed, 3 insertions(+), 11 deletions(-)
(limited to 'test')
diff --git a/test/web/media_proxy/media_proxy_test.exs b/test/web/media_proxy/media_proxy_test.exs
index 69c2d5dae..69d2a71a6 100644
--- a/test/web/media_proxy/media_proxy_test.exs
+++ b/test/web/media_proxy/media_proxy_test.exs
@@ -124,15 +124,7 @@ defmodule Pleroma.Web.MediaProxyTest do
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")
+ clear_config([:media_proxy, :base_url], "https://cache.pleroma.social")
url = "https://pleroma.soykaf.com/static/logo.png"
encoded = url(url)
@@ -213,8 +205,8 @@ defmodule Pleroma.Web.MediaProxyTest do
end
test "does not change whitelisted urls" do
- Pleroma.Config.put([:media_proxy, :whitelist], ["mycdn.akamai.com"])
- Pleroma.Config.put([:media_proxy, :base_url], "https://cache.pleroma.social")
+ clear_config([:media_proxy, :whitelist], ["mycdn.akamai.com"])
+ clear_config([:media_proxy, :base_url], "https://cache.pleroma.social")
media_url = "https://mycdn.akamai.com"
--
cgit v1.2.3
From 8f6d428880721d4b0151991e7943706b70ab8005 Mon Sep 17 00:00:00 2001
From: rinpatch
Date: Wed, 27 May 2020 19:35:35 +0300
Subject: AccountView: Use mediaproxy URLs for emojis
Also use atom keys in emoji maps instead of binaries
Closes #1810
---
test/web/mastodon_api/views/account_view_test.exs | 35 ++++++++++++++++++++---
1 file changed, 31 insertions(+), 4 deletions(-)
(limited to 'test')
diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs
index 487ec26c2..f91333e5c 100644
--- a/test/web/mastodon_api/views/account_view_test.exs
+++ b/test/web/mastodon_api/views/account_view_test.exs
@@ -54,10 +54,10 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
header_static: "http://localhost:4001/images/banner.png",
emojis: [
%{
- "static_url" => "/file.png",
- "url" => "/file.png",
- "shortcode" => "karjalanpiirakka",
- "visible_in_picker" => false
+ static_url: "/file.png",
+ url: "/file.png",
+ shortcode: "karjalanpiirakka",
+ visible_in_picker: false
}
],
fields: [],
@@ -491,4 +491,31 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do
AccountView.render("show.json", %{user: user, for: user})
end
end
+
+ test "uses mediaproxy urls when it's enabled" do
+ clear_config([:media_proxy, :enabled], true)
+
+ user =
+ insert(:user,
+ avatar: %{"url" => [%{"href" => "https://evil.website/avatar.png"}]},
+ banner: %{"url" => [%{"href" => "https://evil.website/banner.png"}]},
+ emoji: %{"joker_smile" => "https://evil.website/society.png"}
+ )
+
+ AccountView.render("show.json", %{user: user})
+ |> Enum.all?(fn
+ {key, url} when key in [:avatar, :avatar_static, :header, :header_static] ->
+ String.starts_with?(url, Pleroma.Web.base_url())
+
+ {:emojis, emojis} ->
+ Enum.all?(emojis, fn %{url: url, static_url: static_url} ->
+ String.starts_with?(url, Pleroma.Web.base_url()) &&
+ String.starts_with?(static_url, Pleroma.Web.base_url())
+ end)
+
+ _ ->
+ true
+ end)
+ |> assert()
+ end
end
--
cgit v1.2.3
From 455a402c8a967b3a234c836b0574c4f011860d43 Mon Sep 17 00:00:00 2001
From: rinpatch
Date: Wed, 27 May 2020 20:27:30 +0300
Subject: HTTP Security plug: rewrite &csp_string/0
- Directives are now separated with ";" instead of " ;",
according to https://www.w3.org/TR/CSP2/#policy-parsing
the space is optional
- Use an IO list, which at the end gets converted to a binary as
opposed to ++ing a bunch of arrays with binaries together and joining
them to a string. I doubt it gives any significant real world advantage,
but the code is cleaner and now I can sleep at night.
- The static part of csp is pre-joined to a single binary at compile time.
Same reasoning as the last point.
---
test/plugs/http_security_plug_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/plugs/http_security_plug_test.exs b/test/plugs/http_security_plug_test.exs
index 84e4c274f..63b4d3f31 100644
--- a/test/plugs/http_security_plug_test.exs
+++ b/test/plugs/http_security_plug_test.exs
@@ -67,7 +67,7 @@ defmodule Pleroma.Web.Plugs.HTTPSecurityPlugTest do
[csp] = Conn.get_resp_header(conn, "content-security-policy")
- assert csp =~ ~r|report-uri https://endpoint.com; report-to csp-endpoint;|
+ assert csp =~ ~r|report-uri https://endpoint.com;report-to csp-endpoint;|
[reply_to] = Conn.get_resp_header(conn, "reply-to")
--
cgit v1.2.3
From ae05792d2a825dbb7d53a7f5a079548ae8310c63 Mon Sep 17 00:00:00 2001
From: Alexander Strizhakov
Date: Thu, 28 May 2020 19:41:34 +0300
Subject: get-packs for local generated pack
---
test/instance_static/local_pack/files.json | 3 +++
test/instance_static/local_pack/manifest.json | 10 ++++++++++
test/tasks/emoji_test.exs | 13 +++++++++++++
3 files changed, 26 insertions(+)
create mode 100644 test/instance_static/local_pack/files.json
create mode 100644 test/instance_static/local_pack/manifest.json
(limited to 'test')
diff --git a/test/instance_static/local_pack/files.json b/test/instance_static/local_pack/files.json
new file mode 100644
index 000000000..279770998
--- /dev/null
+++ b/test/instance_static/local_pack/files.json
@@ -0,0 +1,3 @@
+{
+ "blank": "blank.png"
+}
\ No newline at end of file
diff --git a/test/instance_static/local_pack/manifest.json b/test/instance_static/local_pack/manifest.json
new file mode 100644
index 000000000..01067042f
--- /dev/null
+++ b/test/instance_static/local_pack/manifest.json
@@ -0,0 +1,10 @@
+{
+ "local": {
+ "src_sha256": "384025A1AC6314473863A11AC7AB38A12C01B851A3F82359B89B4D4211D3291D",
+ "src": "test/fixtures/emoji/packs/blank.png.zip",
+ "license": "Apache 2.0",
+ "homepage": "https://example.com",
+ "files": "files.json",
+ "description": "Some local pack"
+ }
+}
\ No newline at end of file
diff --git a/test/tasks/emoji_test.exs b/test/tasks/emoji_test.exs
index f5de3ef0e..499f098c2 100644
--- a/test/tasks/emoji_test.exs
+++ b/test/tasks/emoji_test.exs
@@ -73,6 +73,19 @@ defmodule Mix.Tasks.Pleroma.EmojiTest do
on_exit(fn -> File.rm_rf!("test/instance_static/emoji/finmoji") end)
end
+ test "install local emoji pack" do
+ assert capture_io(fn ->
+ Emoji.run([
+ "get-packs",
+ "local",
+ "--manifest",
+ "test/instance_static/local_pack/manifest.json"
+ ])
+ end) =~ "Writing pack.json for"
+
+ on_exit(fn -> File.rm_rf!("test/instance_static/emoji/local") end)
+ end
+
test "pack not found" do
mock(fn
%{
--
cgit v1.2.3
From 9ca978494fee4be96ec9b6b93e74afe08dd05fcc Mon Sep 17 00:00:00 2001
From: kPherox
Date: Fri, 29 May 2020 21:08:09 +0900
Subject: Add test for stream boosts of mastodon user
---
test/web/streamer/streamer_test.exs | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
(limited to 'test')
diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs
index cb4595bb6..4cf640ce8 100644
--- a/test/web/streamer/streamer_test.exs
+++ b/test/web/streamer/streamer_test.exs
@@ -112,6 +112,25 @@ defmodule Pleroma.Web.StreamerTest do
refute Streamer.filtered_by_user?(user, announce)
end
+ test "it streams boosts of mastodon user in the 'user' stream", %{user: user} do
+ Streamer.get_topic_and_add_socket("user", user)
+
+ other_user = insert(:user)
+ {:ok, activity} = CommonAPI.post(other_user, %{status: "hey"})
+
+ data =
+ File.read!("test/fixtures/mastodon-announce.json")
+ |> Poison.decode!()
+ |> Map.put("object", activity.data["object"])
+ |> Map.put("actor", user.ap_id)
+
+ {:ok, %Pleroma.Activity{data: data, local: false} = announce} =
+ Pleroma.Web.ActivityPub.Transmogrifier.handle_incoming(data)
+
+ assert_receive {:render_with_user, Pleroma.Web.StreamerView, "update.json", ^announce}
+ refute Streamer.filtered_by_user?(user, announce)
+ end
+
test "it sends notify to in the 'user' stream", %{user: user, notify: notify} do
Streamer.get_topic_and_add_socket("user", user)
Streamer.stream("user", notify)
--
cgit v1.2.3
From 0a83af330b7f33601848bca79bd1651b45eaea87 Mon Sep 17 00:00:00 2001
From: Roman Chvanikov
Date: Fri, 29 May 2020 23:05:03 +0300
Subject: fix unused var warning
---
test/web/streamer/streamer_test.exs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'test')
diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs
index 4cf640ce8..3f012259a 100644
--- a/test/web/streamer/streamer_test.exs
+++ b/test/web/streamer/streamer_test.exs
@@ -124,7 +124,7 @@ defmodule Pleroma.Web.StreamerTest do
|> Map.put("object", activity.data["object"])
|> Map.put("actor", user.ap_id)
- {:ok, %Pleroma.Activity{data: data, local: false} = announce} =
+ {:ok, %Pleroma.Activity{data: _data, local: false} = announce} =
Pleroma.Web.ActivityPub.Transmogrifier.handle_incoming(data)
assert_receive {:render_with_user, Pleroma.Web.StreamerView, "update.json", ^announce}
--
cgit v1.2.3
From 6d4b80822b15f5958518f4c6006862fb1f92354a Mon Sep 17 00:00:00 2001
From: Steven Fuchs