diff options
Diffstat (limited to 'test/web')
21 files changed, 1331 insertions, 334 deletions
| diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs index a1e83b380..8dd8e7e0a 100644 --- a/test/web/activity_pub/activity_pub_controller_test.exs +++ b/test/web/activity_pub/activity_pub_controller_test.exs @@ -8,7 +8,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do    alias Pleroma.Activity    alias Pleroma.Instances    alias Pleroma.Object -  alias Pleroma.Repo    alias Pleroma.User    alias Pleroma.Web.ActivityPub.ObjectView    alias Pleroma.Web.ActivityPub.UserView @@ -51,7 +50,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do          |> put_req_header("accept", "application/json")          |> get("/users/#{user.nickname}") -      user = Repo.get(User, user.id) +      user = User.get_by_id(user.id)        assert json_response(conn, 200) == UserView.render("user.json", %{user: user})      end @@ -66,7 +65,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do          |> put_req_header("accept", "application/activity+json")          |> get("/users/#{user.nickname}") -      user = Repo.get(User, user.id) +      user = User.get_by_id(user.id)        assert json_response(conn, 200) == UserView.render("user.json", %{user: user})      end @@ -84,7 +83,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do          )          |> get("/users/#{user.nickname}") -      user = Repo.get(User, user.id) +      user = User.get_by_id(user.id)        assert json_response(conn, 200) == UserView.render("user.json", %{user: user})      end @@ -543,7 +542,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        user = insert(:user)        Enum.each(1..15, fn _ -> -        user = Repo.get(User, user.id) +        user = User.get_by_id(user.id)          other_user = insert(:user)          User.follow(user, other_user)        end) diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs index ac5fbe0a9..17fec05b1 100644 --- a/test/web/activity_pub/activity_pub_test.exs +++ b/test/web/activity_pub/activity_pub_test.exs @@ -218,18 +218,18 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do        user = insert(:user)        {:ok, _} = -        CommonAPI.post(Repo.get(User, user.id), %{"status" => "1", "visibility" => "public"}) +        CommonAPI.post(User.get_by_id(user.id), %{"status" => "1", "visibility" => "public"})        {:ok, _} = -        CommonAPI.post(Repo.get(User, user.id), %{"status" => "2", "visibility" => "unlisted"}) +        CommonAPI.post(User.get_by_id(user.id), %{"status" => "2", "visibility" => "unlisted"})        {:ok, _} = -        CommonAPI.post(Repo.get(User, user.id), %{"status" => "2", "visibility" => "private"}) +        CommonAPI.post(User.get_by_id(user.id), %{"status" => "2", "visibility" => "private"})        {:ok, _} = -        CommonAPI.post(Repo.get(User, user.id), %{"status" => "3", "visibility" => "direct"}) +        CommonAPI.post(User.get_by_id(user.id), %{"status" => "3", "visibility" => "direct"}) -      user = Repo.get(User, user.id) +      user = User.get_by_id(user.id)        assert user.info.note_count == 2      end @@ -322,7 +322,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do      {:ok, user} = User.block(user, %{ap_id: activity_three.data["actor"]})      {:ok, _announce, %{data: %{"id" => id}}} = CommonAPI.repeat(activity_three.id, booster)      %Activity{} = boost_activity = Activity.get_create_by_object_ap_id(id) -    activity_three = Repo.get(Activity, activity_three.id) +    activity_three = Activity.get_by_id(activity_three.id)      activities =        ActivityPub.fetch_activities([], %{"blocking_user" => user, "skip_preload" => true}) @@ -380,7 +380,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do      {:ok, user} = User.mute(user, %User{ap_id: activity_three.data["actor"]})      {:ok, _announce, %{data: %{"id" => id}}} = CommonAPI.repeat(activity_three.id, booster)      %Activity{} = boost_activity = Activity.get_create_by_object_ap_id(id) -    activity_three = Repo.get(Activity, activity_three.id) +    activity_three = Activity.get_by_id(activity_three.id)      activities =        ActivityPub.fetch_activities([], %{"muting_user" => user, "skip_preload" => true}) @@ -559,7 +559,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do        {:ok, _, _, object} = ActivityPub.unlike(user, object)        assert object.data["like_count"] == 0 -      assert Repo.get(Activity, like_activity.id) == nil +      assert Activity.get_by_id(like_activity.id) == nil      end    end @@ -610,7 +610,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do        assert unannounce_activity.data["actor"] == user.ap_id        assert unannounce_activity.data["context"] == announce_activity.data["context"] -      assert Repo.get(Activity, announce_activity.id) == nil +      assert Activity.get_by_id(announce_activity.id) == nil      end    end @@ -635,16 +635,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do      end    end -  describe "fetch the latest Follow" do -    test "fetches the latest Follow activity" do -      %Activity{data: %{"type" => "Follow"}} = activity = insert(:follow_activity) -      follower = Repo.get_by(User, ap_id: activity.data["actor"]) -      followed = Repo.get_by(User, ap_id: activity.data["object"]) - -      assert activity == Utils.fetch_latest_follow(follower, followed) -    end -  end -    describe "fetching an object" do      test "it fetches an object" do        {:ok, object} = @@ -749,7 +739,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do        assert delete.data["actor"] == note.data["actor"]        assert delete.data["object"] == note.data["object"]["id"] -      assert Repo.get(Activity, delete.id) != nil +      assert Activity.get_by_id(delete.id) != nil        assert Repo.get(Object, object.id).data["type"] == "Tombstone"      end @@ -758,23 +748,23 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do        user = insert(:user, info: %{note_count: 10})        {:ok, a1} = -        CommonAPI.post(Repo.get(User, user.id), %{"status" => "yeah", "visibility" => "public"}) +        CommonAPI.post(User.get_by_id(user.id), %{"status" => "yeah", "visibility" => "public"})        {:ok, a2} = -        CommonAPI.post(Repo.get(User, user.id), %{"status" => "yeah", "visibility" => "unlisted"}) +        CommonAPI.post(User.get_by_id(user.id), %{"status" => "yeah", "visibility" => "unlisted"})        {:ok, a3} = -        CommonAPI.post(Repo.get(User, user.id), %{"status" => "yeah", "visibility" => "private"}) +        CommonAPI.post(User.get_by_id(user.id), %{"status" => "yeah", "visibility" => "private"})        {:ok, a4} = -        CommonAPI.post(Repo.get(User, user.id), %{"status" => "yeah", "visibility" => "direct"}) +        CommonAPI.post(User.get_by_id(user.id), %{"status" => "yeah", "visibility" => "direct"})        {:ok, _} = a1.data["object"]["id"] |> Object.get_by_ap_id() |> ActivityPub.delete()        {:ok, _} = a2.data["object"]["id"] |> Object.get_by_ap_id() |> ActivityPub.delete()        {:ok, _} = a3.data["object"]["id"] |> Object.get_by_ap_id() |> ActivityPub.delete()        {:ok, _} = a4.data["object"]["id"] |> Object.get_by_ap_id() |> ActivityPub.delete() -      user = Repo.get(User, user.id) +      user = User.get_by_id(user.id)        assert user.info.note_count == 10      end diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs index 50e8e40bd..47cffe257 100644 --- a/test/web/activity_pub/transmogrifier_test.exs +++ b/test/web/activity_pub/transmogrifier_test.exs @@ -461,7 +461,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        {:ok, %Activity{local: false}} = Transmogrifier.handle_incoming(data) -      refute Repo.get(Activity, activity.id) +      refute Activity.get_by_id(activity.id)      end      test "it fails for incoming deletes with spoofed origin" do @@ -481,7 +481,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        :error = Transmogrifier.handle_incoming(data) -      assert Repo.get(Activity, activity.id) +      assert Activity.get_by_id(activity.id)      end      test "it works for incoming unannounces with an existing notice" do @@ -639,7 +639,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        assert activity.data["object"] == follow_activity.data["id"] -      follower = Repo.get(User, follower.id) +      follower = User.get_by_id(follower.id)        assert User.following?(follower, followed) == true      end @@ -661,7 +661,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        {:ok, activity} = Transmogrifier.handle_incoming(accept_data)        assert activity.data["object"] == follow_activity.data["id"] -      follower = Repo.get(User, follower.id) +      follower = User.get_by_id(follower.id)        assert User.following?(follower, followed) == true      end @@ -681,7 +681,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        {:ok, activity} = Transmogrifier.handle_incoming(accept_data)        assert activity.data["object"] == follow_activity.data["id"] -      follower = Repo.get(User, follower.id) +      follower = User.get_by_id(follower.id)        assert User.following?(follower, followed) == true      end @@ -700,7 +700,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        :error = Transmogrifier.handle_incoming(accept_data) -      follower = Repo.get(User, follower.id) +      follower = User.get_by_id(follower.id)        refute User.following?(follower, followed) == true      end @@ -719,7 +719,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        :error = Transmogrifier.handle_incoming(accept_data) -      follower = Repo.get(User, follower.id) +      follower = User.get_by_id(follower.id)        refute User.following?(follower, followed) == true      end @@ -744,7 +744,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        {:ok, activity} = Transmogrifier.handle_incoming(reject_data)        refute activity.local -      follower = Repo.get(User, follower.id) +      follower = User.get_by_id(follower.id)        assert User.following?(follower, followed) == false      end @@ -766,7 +766,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        {:ok, %Activity{data: _}} = Transmogrifier.handle_incoming(reject_data) -      follower = Repo.get(User, follower.id) +      follower = User.get_by_id(follower.id)        assert User.following?(follower, followed) == false      end @@ -1020,7 +1020,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        {:ok, unrelated_activity} = CommonAPI.post(user_two, %{"status" => "test"})        assert "http://localhost:4001/users/rye@niu.moe/followers" in activity.recipients -      user = Repo.get(User, user.id) +      user = User.get_by_id(user.id)        assert user.info.note_count == 1        {:ok, user} = Transmogrifier.upgrade_user_from_ap_id("https://niu.moe/users/rye") @@ -1028,13 +1028,10 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        assert user.info.note_count == 1        assert user.follower_address == "https://niu.moe/users/rye/followers" -      # Wait for the background task -      :timer.sleep(1000) - -      user = Repo.get(User, user.id) +      user = User.get_by_id(user.id)        assert user.info.note_count == 1 -      activity = Repo.get(Activity, activity.id) +      activity = Activity.get_by_id(activity.id)        assert user.follower_address in activity.recipients        assert %{ @@ -1057,10 +1054,10 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        refute "..." in activity.recipients -      unrelated_activity = Repo.get(Activity, unrelated_activity.id) +      unrelated_activity = Activity.get_by_id(unrelated_activity.id)        refute user.follower_address in unrelated_activity.recipients -      user_two = Repo.get(User, user_two.id) +      user_two = User.get_by_id(user_two.id)        assert user.follower_address in user_two.following        refute "..." in user_two.following      end diff --git a/test/web/activity_pub/utils_test.exs b/test/web/activity_pub/utils_test.exs index 2bd3ddf93..758214e68 100644 --- a/test/web/activity_pub/utils_test.exs +++ b/test/web/activity_pub/utils_test.exs @@ -1,10 +1,34 @@  defmodule Pleroma.Web.ActivityPub.UtilsTest do    use Pleroma.DataCase +  alias Pleroma.Activity +  alias Pleroma.Repo +  alias Pleroma.User +  alias Pleroma.Web.ActivityPub.ActivityPub    alias Pleroma.Web.ActivityPub.Utils    alias Pleroma.Web.CommonAPI    import Pleroma.Factory +  describe "fetch the latest Follow" do +    test "fetches the latest Follow activity" do +      %Activity{data: %{"type" => "Follow"}} = activity = insert(:follow_activity) +      follower = Repo.get_by(User, ap_id: activity.data["actor"]) +      followed = Repo.get_by(User, ap_id: activity.data["object"]) + +      assert activity == Utils.fetch_latest_follow(follower, followed) +    end +  end + +  describe "fetch the latest Block" do +    test "fetches the latest Block activity" do +      blocker = insert(:user) +      blocked = insert(:user) +      {:ok, activity} = ActivityPub.block(blocker, blocked) + +      assert activity == Utils.fetch_latest_block(blocker, blocked) +    end +  end +    describe "determine_explicit_mentions()" do      test "works with an object that has mentions" do        object = %{ @@ -169,4 +193,16 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do        assert Utils.fetch_ordered_collection("http://example.com/outbox", 5) == [0, 1]      end    end + +  test "make_json_ld_header/0" do +    assert Utils.make_json_ld_header() == %{ +             "@context" => [ +               "https://www.w3.org/ns/activitystreams", +               "http://localhost:4001/schemas/litepub-0.1.jsonld", +               %{ +                 "@language" => "und" +               } +             ] +           } +  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 2f53416a3..ca6bd0e97 100644 --- a/test/web/admin_api/admin_api_controller_test.exs +++ b/test/web/admin_api/admin_api_controller_test.exs @@ -5,7 +5,6 @@  defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do    use Pleroma.Web.ConnCase -  alias Pleroma.Repo    alias Pleroma.User    import Pleroma.Factory @@ -75,6 +74,50 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do      end    end +  describe "/api/pleroma/admin/user/follow" do +    test "allows to force-follow another user" do +      admin = insert(:user, info: %{is_admin: true}) +      user = insert(:user) +      follower = insert(:user) + +      build_conn() +      |> assign(:user, admin) +      |> put_req_header("accept", "application/json") +      |> post("/api/pleroma/admin/user/follow", %{ +        "follower" => follower.nickname, +        "followed" => user.nickname +      }) + +      user = User.get_by_id(user.id) +      follower = User.get_by_id(follower.id) + +      assert User.following?(follower, user) +    end +  end + +  describe "/api/pleroma/admin/user/unfollow" do +    test "allows to force-unfollow another user" do +      admin = insert(:user, info: %{is_admin: true}) +      user = insert(:user) +      follower = insert(:user) + +      User.follow(follower, user) + +      build_conn() +      |> assign(:user, admin) +      |> put_req_header("accept", "application/json") +      |> post("/api/pleroma/admin/user/unfollow", %{ +        "follower" => follower.nickname, +        "followed" => user.nickname +      }) + +      user = User.get_by_id(user.id) +      follower = User.get_by_id(follower.id) + +      refute User.following?(follower, user) +    end +  end +    describe "PUT /api/pleroma/admin/users/tag" do      setup do        admin = insert(:user, info: %{is_admin: true}) @@ -101,13 +144,13 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do        user2: user2      } do        assert json_response(conn, :no_content) -      assert Repo.get(User, user1.id).tags == ["x", "foo", "bar"] -      assert Repo.get(User, user2.id).tags == ["y", "foo", "bar"] +      assert User.get_by_id(user1.id).tags == ["x", "foo", "bar"] +      assert User.get_by_id(user2.id).tags == ["y", "foo", "bar"]      end      test "it does not modify tags of not specified users", %{conn: conn, user3: user3} do        assert json_response(conn, :no_content) -      assert Repo.get(User, user3.id).tags == ["unchanged"] +      assert User.get_by_id(user3.id).tags == ["unchanged"]      end    end @@ -137,13 +180,13 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do        user2: user2      } do        assert json_response(conn, :no_content) -      assert Repo.get(User, user1.id).tags == [] -      assert Repo.get(User, user2.id).tags == ["y"] +      assert User.get_by_id(user1.id).tags == [] +      assert User.get_by_id(user2.id).tags == ["y"]      end      test "it does not modify tags of not specified users", %{conn: conn, user3: user3} do        assert json_response(conn, :no_content) -      assert Repo.get(User, user3.id).tags == ["unchanged"] +      assert User.get_by_id(user3.id).tags == ["unchanged"]      end    end @@ -213,7 +256,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do          conn          |> put("/api/pleroma/admin/activation_status/#{user.nickname}", %{status: false}) -      user = Repo.get(User, user.id) +      user = User.get_by_id(user.id)        assert user.info.deactivated == true        assert json_response(conn, :no_content)      end @@ -225,7 +268,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do          conn          |> put("/api/pleroma/admin/activation_status/#{user.nickname}", %{status: true}) -      user = Repo.get(User, user.id) +      user = User.get_by_id(user.id)        assert user.info.deactivated == false        assert json_response(conn, :no_content)      end diff --git a/test/web/common_api/common_api_utils_test.exs b/test/web/common_api/common_api_utils_test.exs index e04b9f9b5..f0c59d5c3 100644 --- a/test/web/common_api/common_api_utils_test.exs +++ b/test/web/common_api/common_api_utils_test.exs @@ -153,4 +153,40 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do        assert conversation_id == object.id      end    end + +  describe "formats date to asctime" do +    test "when date is in ISO 8601 format" do +      date = DateTime.utc_now() |> DateTime.to_iso8601() + +      expected = +        date +        |> DateTime.from_iso8601() +        |> elem(1) +        |> Calendar.Strftime.strftime!("%a %b %d %H:%M:%S %z %Y") + +      assert Utils.date_to_asctime(date) == expected +    end + +    test "when date is a binary in wrong format" do +      date = DateTime.utc_now() + +      expected = "" + +      assert Utils.date_to_asctime(date) == expected +    end + +    test "when date is a Unix timestamp" do +      date = DateTime.utc_now() |> DateTime.to_unix() + +      expected = "" + +      assert Utils.date_to_asctime(date) == expected +    end + +    test "when date is nil" do +      expected = "" + +      assert Utils.date_to_asctime(nil) == expected +    end +  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 5e6ee0024..9e19fb48e 100644 --- a/test/web/mastodon_api/mastodon_api_controller_test.exs +++ b/test/web/mastodon_api/mastodon_api_controller_test.exs @@ -10,6 +10,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do    alias Pleroma.Notification    alias Pleroma.Object    alias Pleroma.Repo +  alias Pleroma.ScheduledActivity    alias Pleroma.User    alias Pleroma.Web.ActivityPub.ActivityPub    alias Pleroma.Web.CommonAPI @@ -101,7 +102,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do      assert %{"content" => "cofe", "id" => id, "spoiler_text" => "2hu", "sensitive" => false} =               json_response(conn_one, 200) -    assert Repo.get(Activity, id) +    assert Activity.get_by_id(id)      conn_two =        conn @@ -140,7 +141,56 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        |> post("/api/v1/statuses", %{"status" => "cofe", "sensitive" => true})      assert %{"content" => "cofe", "id" => id, "sensitive" => true} = json_response(conn, 200) -    assert Repo.get(Activity, id) +    assert Activity.get_by_id(id) +  end + +  test "posting a fake status", %{conn: conn} do +    user = insert(:user) + +    real_conn = +      conn +      |> assign(:user, user) +      |> 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) + +    assert real_status +    assert Object.get_by_ap_id(real_status["uri"]) + +    real_status = +      real_status +      |> Map.put("id", nil) +      |> Map.put("url", nil) +      |> Map.put("uri", nil) +      |> Map.put("created_at", nil) +      |> Kernel.put_in(["pleroma", "conversation_id"], nil) + +    fake_conn = +      conn +      |> assign(:user, user) +      |> 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) + +    assert fake_status +    refute Object.get_by_ap_id(fake_status["uri"]) + +    fake_status = +      fake_status +      |> Map.put("id", nil) +      |> Map.put("url", nil) +      |> Map.put("uri", nil) +      |> Map.put("created_at", nil) +      |> Kernel.put_in(["pleroma", "conversation_id"], nil) + +    assert real_status == fake_status    end    test "posting a status with OGP link preview", %{conn: conn} do @@ -155,7 +205,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        })      assert %{"id" => id, "card" => %{"title" => "The Rock"}} = json_response(conn, 200) -    assert Repo.get(Activity, id) +    assert Activity.get_by_id(id)      Pleroma.Config.put([:rich_media, :enabled], false)    end @@ -170,7 +220,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        |> post("api/v1/statuses", %{"status" => content, "visibility" => "direct"})      assert %{"id" => id, "visibility" => "direct"} = json_response(conn, 200) -    assert activity = Repo.get(Activity, id) +    assert activity = Activity.get_by_id(id)      assert activity.recipients == [user2.ap_id, user1.ap_id]      assert activity.data["to"] == [user2.ap_id]      assert activity.data["cc"] == [] @@ -340,7 +390,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do      assert %{"content" => "xD", "id" => id} = json_response(conn, 200) -    activity = Repo.get(Activity, id) +    activity = Activity.get_by_id(id)      assert activity.data["context"] == replied_to.data["context"]      assert activity.data["object"]["inReplyToStatusId"] == replied_to.id @@ -356,7 +406,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do      assert %{"content" => "xD", "id" => id} = json_response(conn, 200) -    activity = Repo.get(Activity, id) +    activity = Activity.get_by_id(id)      assert activity    end @@ -455,7 +505,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        assert %{} = json_response(conn, 200) -      refute Repo.get(Activity, activity.id) +      refute Activity.get_by_id(activity.id)      end      test "when you didn't create it", %{conn: conn} do @@ -469,7 +519,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        assert %{"error" => _} = json_response(conn, 403) -      assert Repo.get(Activity, activity.id) == activity +      assert Activity.get_by_id(activity.id) == activity      end      test "when you're an admin or moderator", %{conn: conn} do @@ -492,8 +542,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        assert %{} = json_response(res_conn, 200) -      refute Repo.get(Activity, activity1.id) -      refute Repo.get(Activity, activity2.id) +      refute Activity.get_by_id(activity1.id) +      refute Activity.get_by_id(activity2.id)      end    end @@ -1163,8 +1213,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        {:ok, _activity} = ActivityPub.follow(other_user, user) -      user = Repo.get(User, user.id) -      other_user = Repo.get(User, other_user.id) +      user = User.get_by_id(user.id) +      other_user = User.get_by_id(other_user.id)        assert User.following?(other_user, user) == false @@ -1183,8 +1233,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        {:ok, _activity} = ActivityPub.follow(other_user, user) -      user = Repo.get(User, user.id) -      other_user = Repo.get(User, other_user.id) +      user = User.get_by_id(user.id) +      other_user = User.get_by_id(other_user.id)        assert User.following?(other_user, user) == false @@ -1196,8 +1246,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        assert relationship = json_response(conn, 200)        assert to_string(other_user.id) == relationship["id"] -      user = Repo.get(User, user.id) -      other_user = Repo.get(User, other_user.id) +      user = User.get_by_id(user.id) +      other_user = User.get_by_id(other_user.id)        assert User.following?(other_user, user) == true      end @@ -1220,7 +1270,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        {:ok, _activity} = ActivityPub.follow(other_user, user) -      user = Repo.get(User, user.id) +      user = User.get_by_id(user.id)        conn =          build_conn() @@ -1230,8 +1280,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        assert relationship = json_response(conn, 200)        assert to_string(other_user.id) == relationship["id"] -      user = Repo.get(User, user.id) -      other_user = Repo.get(User, other_user.id) +      user = User.get_by_id(user.id) +      other_user = User.get_by_id(other_user.id)        assert User.following?(other_user, user) == false      end @@ -1516,7 +1566,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do      assert %{"id" => _id, "following" => true} = json_response(conn, 200) -    user = Repo.get(User, user.id) +    user = User.get_by_id(user.id)      conn =        build_conn() @@ -1525,7 +1575,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do      assert %{"id" => _id, "following" => false} = json_response(conn, 200) -    user = Repo.get(User, user.id) +    user = User.get_by_id(user.id)      conn =        build_conn() @@ -1547,7 +1597,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do      assert %{"id" => _id, "muting" => true} = json_response(conn, 200) -    user = Repo.get(User, user.id) +    user = User.get_by_id(user.id)      conn =        build_conn() @@ -1583,7 +1633,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do      assert %{"id" => _id, "blocking" => true} = json_response(conn, 200) -    user = Repo.get(User, user.id) +    user = User.get_by_id(user.id)      conn =        build_conn() @@ -1940,7 +1990,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do      {:ok, _} = TwitterAPI.create_status(user, %{"status" => "cofe"})      # Stats should count users with missing or nil `info.deactivated` value -    user = Repo.get(User, user.id) +    user = User.get_by_id(user.id)      info_change = Changeset.change(user.info, %{deactivated: nil})      {:ok, _user} = @@ -2316,4 +2366,323 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do        assert link_header =~ ~r/max_id=#{notification1.id}/      end    end + +  test "accounts fetches correct account for nicknames beginning with numbers", %{conn: conn} do +    # Need to set an old-style integer ID to reproduce the problem +    # (these are no longer assigned to new accounts but were preserved +    # for existing accounts during the migration to flakeIDs) +    user_one = insert(:user, %{id: 1212}) +    user_two = insert(:user, %{nickname: "#{user_one.id}garbage"}) + +    resp_one = +      conn +      |> get("/api/v1/accounts/#{user_one.id}") + +    resp_two = +      conn +      |> get("/api/v1/accounts/#{user_two.nickname}") + +    resp_three = +      conn +      |> get("/api/v1/accounts/#{user_two.id}") + +    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 + +  describe "custom emoji" do +    test "with tags", %{conn: conn} do +      [emoji | _body] = +        conn +        |> get("/api/v1/custom_emojis") +        |> json_response(200) + +      assert Map.has_key?(emoji, "shortcode") +      assert Map.has_key?(emoji, "static_url") +      assert Map.has_key?(emoji, "tags") +      assert is_list(emoji["tags"]) +      assert Map.has_key?(emoji, "url") +      assert Map.has_key?(emoji, "visible_in_picker") +    end +  end + +  describe "index/2 redirections" do +    setup %{conn: conn} do +      session_opts = [ +        store: :cookie, +        key: "_test", +        signing_salt: "cooldude" +      ] + +      conn = +        conn +        |> Plug.Session.call(Plug.Session.init(session_opts)) +        |> fetch_session() + +      test_path = "/web/statuses/test" +      %{conn: conn, path: test_path} +    end + +    test "redirects not logged-in users to the login page", %{conn: conn, path: path} do +      conn = get(conn, path) + +      assert conn.status == 302 +      assert redirected_to(conn) == "/web/login" +    end + +    test "does not redirect logged in users to the login page", %{conn: conn, path: path} do +      token = insert(:oauth_token) + +      conn = +        conn +        |> assign(:user, token.user) +        |> put_session(:oauth_token, token.token) +        |> get(path) + +      assert conn.status == 200 +    end + +    test "saves referer path to session", %{conn: conn, path: path} do +      conn = get(conn, path) +      return_to = Plug.Conn.get_session(conn, :return_to) + +      assert return_to == path +    end + +    test "redirects to the saved path after log in", %{conn: conn, path: path} do +      app = insert(:oauth_app, client_name: "Mastodon-Local", redirect_uris: ".") +      auth = insert(:oauth_authorization, app: app) + +      conn = +        conn +        |> put_session(:return_to, path) +        |> get("/web/login", %{code: auth.token}) + +      assert conn.status == 302 +      assert redirected_to(conn) == path +    end + +    test "redirects to the getting-started page when referer is not present", %{conn: conn} do +      app = insert(:oauth_app, client_name: "Mastodon-Local", redirect_uris: ".") +      auth = insert(:oauth_authorization, app: app) + +      conn = get(conn, "/web/login", %{code: auth.token}) + +      assert conn.status == 302 +      assert redirected_to(conn) == "/web/getting-started" +    end +  end + +  describe "scheduled activities" do +    test "creates a scheduled activity", %{conn: conn} do +      user = insert(:user) +      scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond) + +      conn = +        conn +        |> assign(:user, user) +        |> post("/api/v1/statuses", %{ +          "status" => "scheduled", +          "scheduled_at" => scheduled_at +        }) + +      assert %{"scheduled_at" => expected_scheduled_at} = json_response(conn, 200) +      assert expected_scheduled_at == Pleroma.Web.CommonAPI.Utils.to_masto_date(scheduled_at) +      assert [] == Repo.all(Activity) +    end + +    test "creates a scheduled activity with a media attachment", %{conn: conn} do +      user = insert(:user) +      scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond) + +      file = %Plug.Upload{ +        content_type: "image/jpg", +        path: Path.absname("test/fixtures/image.jpg"), +        filename: "an_image.jpg" +      } + +      {:ok, upload} = ActivityPub.upload(file, actor: user.ap_id) + +      conn = +        conn +        |> assign(:user, user) +        |> 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 %{"type" => "image"} = media_attachment +    end + +    test "skips the scheduling and creates the activity if scheduled_at is earlier than 5 minutes from now", +         %{conn: conn} do +      user = insert(:user) + +      scheduled_at = +        NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(5) - 1, :millisecond) + +      conn = +        conn +        |> assign(:user, user) +        |> post("/api/v1/statuses", %{ +          "status" => "not scheduled", +          "scheduled_at" => scheduled_at +        }) + +      assert %{"content" => "not scheduled"} = json_response(conn, 200) +      assert [] == Repo.all(ScheduledActivity) +    end + +    test "returns error when daily user limit is exceeded", %{conn: conn} do +      user = insert(:user) + +      today = +        NaiveDateTime.utc_now() +        |> NaiveDateTime.add(:timer.minutes(6), :millisecond) +        |> NaiveDateTime.to_iso8601() + +      attrs = %{params: %{}, scheduled_at: today} +      {:ok, _} = ScheduledActivity.create(user, attrs) +      {:ok, _} = ScheduledActivity.create(user, attrs) + +      conn = +        conn +        |> assign(:user, user) +        |> post("/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => today}) + +      assert %{"error" => "daily limit exceeded"} == json_response(conn, 422) +    end + +    test "returns error when total user limit is exceeded", %{conn: conn} do +      user = insert(:user) + +      today = +        NaiveDateTime.utc_now() +        |> NaiveDateTime.add(:timer.minutes(6), :millisecond) +        |> NaiveDateTime.to_iso8601() + +      tomorrow = +        NaiveDateTime.utc_now() +        |> NaiveDateTime.add(:timer.hours(36), :millisecond) +        |> NaiveDateTime.to_iso8601() + +      attrs = %{params: %{}, scheduled_at: today} +      {:ok, _} = ScheduledActivity.create(user, attrs) +      {:ok, _} = ScheduledActivity.create(user, attrs) +      {:ok, _} = ScheduledActivity.create(user, %{params: %{}, scheduled_at: tomorrow}) + +      conn = +        conn +        |> assign(:user, user) +        |> post("/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => tomorrow}) + +      assert %{"error" => "total limit exceeded"} == json_response(conn, 422) +    end + +    test "shows scheduled activities", %{conn: conn} do +      user = insert(:user) +      scheduled_activity_id1 = insert(:scheduled_activity, user: user).id |> to_string() +      scheduled_activity_id2 = insert(:scheduled_activity, user: user).id |> to_string() +      scheduled_activity_id3 = insert(:scheduled_activity, user: user).id |> to_string() +      scheduled_activity_id4 = insert(:scheduled_activity, user: user).id |> to_string() + +      conn = +        conn +        |> assign(:user, user) + +      # min_id +      conn_res = +        conn +        |> get("/api/v1/scheduled_statuses?limit=2&min_id=#{scheduled_activity_id1}") + +      result = json_response(conn_res, 200) +      assert [%{"id" => ^scheduled_activity_id3}, %{"id" => ^scheduled_activity_id2}] = result + +      # since_id +      conn_res = +        conn +        |> get("/api/v1/scheduled_statuses?limit=2&since_id=#{scheduled_activity_id1}") + +      result = json_response(conn_res, 200) +      assert [%{"id" => ^scheduled_activity_id4}, %{"id" => ^scheduled_activity_id3}] = result + +      # max_id +      conn_res = +        conn +        |> get("/api/v1/scheduled_statuses?limit=2&max_id=#{scheduled_activity_id4}") + +      result = json_response(conn_res, 200) +      assert [%{"id" => ^scheduled_activity_id3}, %{"id" => ^scheduled_activity_id2}] = result +    end + +    test "shows a scheduled activity", %{conn: conn} do +      user = insert(:user) +      scheduled_activity = insert(:scheduled_activity, user: user) + +      res_conn = +        conn +        |> assign(:user, user) +        |> get("/api/v1/scheduled_statuses/#{scheduled_activity.id}") + +      assert %{"id" => scheduled_activity_id} = json_response(res_conn, 200) +      assert scheduled_activity_id == scheduled_activity.id |> to_string() + +      res_conn = +        conn +        |> assign(:user, user) +        |> get("/api/v1/scheduled_statuses/404") + +      assert %{"error" => "Record not found"} = json_response(res_conn, 404) +    end + +    test "updates a scheduled activity", %{conn: conn} do +      user = insert(:user) +      scheduled_activity = insert(:scheduled_activity, user: user) + +      new_scheduled_at = +        NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond) + +      res_conn = +        conn +        |> assign(:user, user) +        |> put("/api/v1/scheduled_statuses/#{scheduled_activity.id}", %{ +          scheduled_at: new_scheduled_at +        }) + +      assert %{"scheduled_at" => expected_scheduled_at} = json_response(res_conn, 200) +      assert expected_scheduled_at == Pleroma.Web.CommonAPI.Utils.to_masto_date(new_scheduled_at) + +      res_conn = +        conn +        |> assign(:user, user) +        |> put("/api/v1/scheduled_statuses/404", %{scheduled_at: new_scheduled_at}) + +      assert %{"error" => "Record not found"} = json_response(res_conn, 404) +    end + +    test "deletes a scheduled activity", %{conn: conn} do +      user = insert(:user) +      scheduled_activity = insert(:scheduled_activity, user: user) + +      res_conn = +        conn +        |> assign(:user, user) +        |> delete("/api/v1/scheduled_statuses/#{scheduled_activity.id}") + +      assert %{} = json_response(res_conn, 200) +      assert nil == Repo.get(ScheduledActivity, scheduled_activity.id) + +      res_conn = +        conn +        |> assign(:user, user) +        |> delete("/api/v1/scheduled_statuses/#{scheduled_activity.id}") + +      assert %{"error" => "Record not found"} = json_response(res_conn, 404) +    end +  end  end diff --git a/test/web/mastodon_api/notification_view_test.exs b/test/web/mastodon_api/notification_view_test.exs index b826a7e61..f2c1eb76c 100644 --- a/test/web/mastodon_api/notification_view_test.exs +++ b/test/web/mastodon_api/notification_view_test.exs @@ -21,7 +21,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do      mentioned_user = insert(:user)      {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{mentioned_user.nickname}"})      {:ok, [notification]} = Notification.create_notifications(activity) -    user = Repo.get(User, user.id) +    user = User.get_by_id(user.id)      expected = %{        id: to_string(notification.id), @@ -44,7 +44,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do      {:ok, create_activity} = CommonAPI.post(user, %{"status" => "hey"})      {:ok, favorite_activity, _object} = CommonAPI.favorite(create_activity.id, another_user)      {:ok, [notification]} = Notification.create_notifications(favorite_activity) -    create_activity = Repo.get(Activity, create_activity.id) +    create_activity = Activity.get_by_id(create_activity.id)      expected = %{        id: to_string(notification.id), @@ -66,7 +66,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do      {: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 = Repo.get(Activity, create_activity.id) +    reblog_activity = Activity.get_by_id(create_activity.id)      expected = %{        id: to_string(notification.id), diff --git a/test/web/mastodon_api/scheduled_activity_view_test.exs b/test/web/mastodon_api/scheduled_activity_view_test.exs new file mode 100644 index 000000000..ecbb855d4 --- /dev/null +++ b/test/web/mastodon_api/scheduled_activity_view_test.exs @@ -0,0 +1,68 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.MastodonAPI.ScheduledActivityViewTest do +  use Pleroma.DataCase +  alias Pleroma.ScheduledActivity +  alias Pleroma.Web.ActivityPub.ActivityPub +  alias Pleroma.Web.CommonAPI +  alias Pleroma.Web.CommonAPI.Utils +  alias Pleroma.Web.MastodonAPI.ScheduledActivityView +  alias Pleroma.Web.MastodonAPI.StatusView +  import Pleroma.Factory + +  test "A scheduled activity with a media attachment" do +    user = insert(:user) +    {:ok, activity} = CommonAPI.post(user, %{"status" => "hi"}) + +    scheduled_at = +      NaiveDateTime.utc_now() +      |> NaiveDateTime.add(:timer.minutes(10), :millisecond) +      |> NaiveDateTime.to_iso8601() + +    file = %Plug.Upload{ +      content_type: "image/jpg", +      path: Path.absname("test/fixtures/image.jpg"), +      filename: "an_image.jpg" +    } + +    {:ok, upload} = ActivityPub.upload(file, actor: user.ap_id) + +    attrs = %{ +      params: %{ +        "media_ids" => [upload.id], +        "status" => "hi", +        "sensitive" => true, +        "spoiler_text" => "spoiler", +        "visibility" => "unlisted", +        "in_reply_to_id" => to_string(activity.id) +      }, +      scheduled_at: scheduled_at +    } + +    {:ok, scheduled_activity} = ScheduledActivity.create(user, attrs) +    result = ScheduledActivityView.render("show.json", %{scheduled_activity: scheduled_activity}) + +    expected = %{ +      id: to_string(scheduled_activity.id), +      media_attachments: +        %{"media_ids" => [upload.id]} +        |> Utils.attachments_from_ids() +        |> Enum.map(&StatusView.render("attachment.json", %{attachment: &1})), +      params: %{ +        in_reply_to_id: to_string(activity.id), +        media_ids: [upload.id], +        poll: nil, +        scheduled_at: nil, +        sensitive: true, +        spoiler_text: "spoiler", +        text: "hi", +        visibility: "unlisted" +      }, +      scheduled_at: Utils.to_masto_date(scheduled_activity.scheduled_at) +    } + +    assert expected == result +  end +end diff --git a/test/web/mastodon_api/status_view_test.exs b/test/web/mastodon_api/status_view_test.exs index e1c9b2c8f..8db92ac16 100644 --- a/test/web/mastodon_api/status_view_test.exs +++ b/test/web/mastodon_api/status_view_test.exs @@ -175,7 +175,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do      status = StatusView.render("status.json", %{activity: activity}) -    actor = Repo.get_by(User, ap_id: activity.actor) +    actor = User.get_by_ap_id(activity.actor)      assert status.mentions ==               Enum.map([user, actor], fn u -> AccountView.render("mention.json", %{user: u}) end) diff --git a/test/web/oauth/oauth_controller_test.exs b/test/web/oauth/oauth_controller_test.exs index 84ec7b4ee..ac7843f9b 100644 --- a/test/web/oauth/oauth_controller_test.exs +++ b/test/web/oauth/oauth_controller_test.exs @@ -5,266 +5,676 @@  defmodule Pleroma.Web.OAuth.OAuthControllerTest do    use Pleroma.Web.ConnCase    import Pleroma.Factory +  import Mock +  alias Pleroma.Registration    alias Pleroma.Repo    alias Pleroma.Web.OAuth.Authorization    alias Pleroma.Web.OAuth.Token -  test "redirects with oauth authorization" do -    user = insert(:user) -    app = insert(:oauth_app, scopes: ["read", "write", "follow"]) +  @session_opts [ +    store: :cookie, +    key: "_test", +    signing_salt: "cooldude" +  ] + +  describe "in OAuth consumer mode, " do +    setup do +      oauth_consumer_strategies_path = [:auth, :oauth_consumer_strategies] +      oauth_consumer_strategies = Pleroma.Config.get(oauth_consumer_strategies_path) +      Pleroma.Config.put(oauth_consumer_strategies_path, ~w(twitter facebook)) + +      on_exit(fn -> +        Pleroma.Config.put(oauth_consumer_strategies_path, oauth_consumer_strategies) +      end) + +      [ +        app: insert(:oauth_app), +        conn: +          build_conn() +          |> Plug.Session.call(Plug.Session.init(@session_opts)) +          |> fetch_session() +      ] +    end -    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" -        } -      }) +    test "GET /oauth/authorize renders auth forms, including OAuth consumer form", %{ +      app: app, +      conn: conn +    } do +      conn = +        get( +          conn, +          "/oauth/authorize", +          %{ +            "response_type" => "code", +            "client_id" => app.client_id, +            "redirect_uri" => app.redirect_uris, +            "scope" => "read" +          } +        ) + +      assert response = html_response(conn, 200) +      assert response =~ "Sign in with Twitter" +      assert response =~ o_auth_path(conn, :prepare_request) +    end + +    test "GET /oauth/prepare_request encodes parameters as `state` and redirects", %{ +      app: app, +      conn: conn +    } do +      conn = +        get( +          conn, +          "/oauth/prepare_request", +          %{ +            "provider" => "twitter", +            "scope" => "read follow", +            "client_id" => app.client_id, +            "redirect_uri" => app.redirect_uris, +            "state" => "a_state" +          } +        ) + +      assert response = html_response(conn, 302) + +      redirect_query = URI.parse(redirected_to(conn)).query +      assert %{"state" => state_param} = URI.decode_query(redirect_query) +      assert {:ok, state_components} = Poison.decode(state_param) + +      expected_client_id = app.client_id +      expected_redirect_uri = app.redirect_uris + +      assert %{ +               "scope" => "read follow", +               "client_id" => ^expected_client_id, +               "redirect_uri" => ^expected_redirect_uri, +               "state" => "a_state" +             } = state_components +    end + +    test "with user-bound registration, GET /oauth/<provider>/callback redirects to `redirect_uri` with `code`", +         %{app: app, conn: conn} do +      registration = insert(:registration) + +      state_params = %{ +        "scope" => Enum.join(app.scopes, " "), +        "client_id" => app.client_id, +        "redirect_uri" => app.redirect_uris, +        "state" => "" +      } + +      with_mock Pleroma.Web.Auth.Authenticator, +        get_registration: fn _, _ -> {:ok, registration} end do +        conn = +          get( +            conn, +            "/oauth/twitter/callback", +            %{ +              "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM", +              "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs", +              "provider" => "twitter", +              "state" => Poison.encode!(state_params) +            } +          ) + +        assert response = html_response(conn, 302) +        assert redirected_to(conn) =~ ~r/#{app.redirect_uris}\?code=.+/ +      end +    end + +    test "with user-unbound registration, GET /oauth/<provider>/callback renders registration_details page", +         %{app: app, conn: conn} do +      registration = insert(:registration, user: nil) + +      state_params = %{ +        "scope" => "read write", +        "client_id" => app.client_id, +        "redirect_uri" => app.redirect_uris, +        "state" => "a_state" +      } + +      with_mock Pleroma.Web.Auth.Authenticator, +        get_registration: fn _, _ -> {:ok, registration} end do +        conn = +          get( +            conn, +            "/oauth/twitter/callback", +            %{ +              "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM", +              "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs", +              "provider" => "twitter", +              "state" => Poison.encode!(state_params) +            } +          ) + +        assert response = html_response(conn, 200) +        assert response =~ ~r/name="op" type="submit" value="register"/ +        assert response =~ ~r/name="op" type="submit" value="connect"/ +        assert response =~ Registration.email(registration) +        assert response =~ Registration.nickname(registration) +      end +    end -    target = redirected_to(conn) -    assert target =~ app.redirect_uris +    test "on authentication error, GET /oauth/<provider>/callback redirects to `redirect_uri`", %{ +      app: app, +      conn: conn +    } do +      state_params = %{ +        "scope" => Enum.join(app.scopes, " "), +        "client_id" => app.client_id, +        "redirect_uri" => app.redirect_uris, +        "state" => "" +      } + +      conn = +        conn +        |> assign(:ueberauth_failure, %{errors: [%{message: "(error description)"}]}) +        |> get( +          "/oauth/twitter/callback", +          %{ +            "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM", +            "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs", +            "provider" => "twitter", +            "state" => Poison.encode!(state_params) +          } +        ) + +      assert response = html_response(conn, 302) +      assert redirected_to(conn) == app.redirect_uris +      assert get_flash(conn, :error) == "Failed to authenticate: (error description)." +    end -    query = URI.parse(target).query |> URI.query_decoder() |> Map.new() +    test "GET /oauth/registration_details renders registration details form", %{ +      app: app, +      conn: conn +    } do +      conn = +        get( +          conn, +          "/oauth/registration_details", +          %{ +            "scopes" => app.scopes, +            "client_id" => app.client_id, +            "redirect_uri" => app.redirect_uris, +            "state" => "a_state", +            "nickname" => nil, +            "email" => "john@doe.com" +          } +        ) + +      assert response = html_response(conn, 200) +      assert response =~ ~r/name="op" type="submit" value="register"/ +      assert response =~ ~r/name="op" type="submit" value="connect"/ +    end -    assert %{"state" => "statepassed", "code" => code} = query -    auth = Repo.get_by(Authorization, token: code) -    assert auth -    assert auth.scopes == ["read", "write"] +    test "with valid params, POST /oauth/register?op=register redirects to `redirect_uri` with `code`", +         %{ +           app: app, +           conn: conn +         } do +      registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil}) + +      conn = +        conn +        |> put_session(:registration_id, registration.id) +        |> post( +          "/oauth/register", +          %{ +            "op" => "register", +            "scopes" => app.scopes, +            "client_id" => app.client_id, +            "redirect_uri" => app.redirect_uris, +            "state" => "a_state", +            "nickname" => "availablenick", +            "email" => "available@email.com" +          } +        ) + +      assert response = html_response(conn, 302) +      assert redirected_to(conn) =~ ~r/#{app.redirect_uris}\?code=.+/ +    end + +    test "with invalid params, POST /oauth/register?op=register renders registration_details page", +         %{ +           app: app, +           conn: conn +         } do +      another_user = insert(:user) +      registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil}) + +      params = %{ +        "op" => "register", +        "scopes" => app.scopes, +        "client_id" => app.client_id, +        "redirect_uri" => app.redirect_uris, +        "state" => "a_state", +        "nickname" => "availablenickname", +        "email" => "available@email.com" +      } + +      for {bad_param, bad_param_value} <- +            [{"nickname", another_user.nickname}, {"email", another_user.email}] do +        bad_params = Map.put(params, bad_param, bad_param_value) + +        conn = +          conn +          |> put_session(:registration_id, registration.id) +          |> post("/oauth/register", bad_params) + +        assert html_response(conn, 403) =~ ~r/name="op" type="submit" value="register"/ +        assert get_flash(conn, :error) == "Error: #{bad_param} has already been taken." +      end +    end + +    test "with valid params, POST /oauth/register?op=connect redirects to `redirect_uri` with `code`", +         %{ +           app: app, +           conn: conn +         } do +      user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("testpassword")) +      registration = insert(:registration, user: nil) + +      conn = +        conn +        |> put_session(:registration_id, registration.id) +        |> post( +          "/oauth/register", +          %{ +            "op" => "connect", +            "scopes" => app.scopes, +            "client_id" => app.client_id, +            "redirect_uri" => app.redirect_uris, +            "state" => "a_state", +            "auth_name" => user.nickname, +            "password" => "testpassword" +          } +        ) + +      assert response = html_response(conn, 302) +      assert redirected_to(conn) =~ ~r/#{app.redirect_uris}\?code=.+/ +    end + +    test "with invalid params, POST /oauth/register?op=connect renders registration_details page", +         %{ +           app: app, +           conn: conn +         } do +      user = insert(:user) +      registration = insert(:registration, user: nil) + +      params = %{ +        "op" => "connect", +        "scopes" => app.scopes, +        "client_id" => app.client_id, +        "redirect_uri" => app.redirect_uris, +        "state" => "a_state", +        "auth_name" => user.nickname, +        "password" => "wrong password" +      } + +      conn = +        conn +        |> put_session(:registration_id, registration.id) +        |> post("/oauth/register", params) + +      assert html_response(conn, 401) =~ ~r/name="op" type="submit" value="connect"/ +      assert get_flash(conn, :error) == "Invalid Username/Password" +    end    end -  test "returns 401 for wrong credentials", %{conn: conn} do -    user = insert(:user) -    app = insert(:oauth_app) +  describe "GET /oauth/authorize" do +    setup do +      [ +        app: insert(:oauth_app, redirect_uris: "https://redirect.url"), +        conn: +          build_conn() +          |> Plug.Session.call(Plug.Session.init(@session_opts)) +          |> fetch_session() +      ] +    end -    result = -      conn -      |> post("/oauth/authorize", %{ -        "authorization" => %{ -          "name" => user.nickname, -          "password" => "wrong", -          "client_id" => app.client_id, -          "redirect_uri" => app.redirect_uris, -          "state" => "statepassed", -          "scope" => Enum.join(app.scopes, " ") -        } -      }) -      |> html_response(:unauthorized) - -    # Keep the details -    assert result =~ app.client_id -    assert result =~ app.redirect_uris - -    # Error message -    assert result =~ "Invalid Username/Password" +    test "renders authentication page", %{app: app, conn: conn} do +      conn = +        get( +          conn, +          "/oauth/authorize", +          %{ +            "response_type" => "code", +            "client_id" => app.client_id, +            "redirect_uri" => app.redirect_uris, +            "scope" => "read" +          } +        ) + +      assert html_response(conn, 200) =~ ~s(type="submit") +    end + +    test "renders authentication page if user is already authenticated but `force_login` is tru-ish", +         %{app: app, conn: conn} do +      token = insert(:oauth_token, app_id: app.id) + +      conn = +        conn +        |> put_session(:oauth_token, token.token) +        |> get( +          "/oauth/authorize", +          %{ +            "response_type" => "code", +            "client_id" => app.client_id, +            "redirect_uri" => app.redirect_uris, +            "scope" => "read", +            "force_login" => "true" +          } +        ) + +      assert html_response(conn, 200) =~ ~s(type="submit") +    end + +    test "redirects to app if user is already authenticated", %{app: app, conn: conn} do +      token = insert(:oauth_token, app_id: app.id) + +      conn = +        conn +        |> put_session(:oauth_token, token.token) +        |> get( +          "/oauth/authorize", +          %{ +            "response_type" => "code", +            "client_id" => app.client_id, +            "redirect_uri" => app.redirect_uris, +            "scope" => "read" +          } +        ) + +      assert redirected_to(conn) == "https://redirect.url" +    end    end -  test "returns 401 for missing scopes", %{conn: conn} do -    user = insert(:user) -    app = insert(:oauth_app) +  describe "POST /oauth/authorize" do +    test "redirects with oauth authorization" do +      user = insert(:user) +      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" +          } +        }) + +      target = redirected_to(conn) +      assert target =~ app.redirect_uris + +      query = URI.parse(target).query |> URI.query_decoder() |> Map.new() + +      assert %{"state" => "statepassed", "code" => code} = query +      auth = Repo.get_by(Authorization, token: code) +      assert auth +      assert auth.scopes == ["read", "write"] +    end -    result = -      conn -      |> post("/oauth/authorize", %{ -        "authorization" => %{ -          "name" => user.nickname, -          "password" => "test", -          "client_id" => app.client_id, -          "redirect_uri" => app.redirect_uris, -          "state" => "statepassed", -          "scope" => "" -        } -      }) -      |> html_response(:unauthorized) - -    # Keep the details -    assert result =~ app.client_id -    assert result =~ app.redirect_uris - -    # Error message -    assert result =~ "This action is outside the authorized scopes" +    test "returns 401 for wrong credentials", %{conn: conn} do +      user = insert(:user) +      app = insert(:oauth_app) + +      result = +        conn +        |> post("/oauth/authorize", %{ +          "authorization" => %{ +            "name" => user.nickname, +            "password" => "wrong", +            "client_id" => app.client_id, +            "redirect_uri" => app.redirect_uris, +            "state" => "statepassed", +            "scope" => Enum.join(app.scopes, " ") +          } +        }) +        |> html_response(:unauthorized) + +      # Keep the details +      assert result =~ app.client_id +      assert result =~ app.redirect_uris + +      # Error message +      assert result =~ "Invalid Username/Password" +    end + +    test "returns 401 for missing scopes", %{conn: conn} do +      user = insert(:user) +      app = insert(:oauth_app) + +      result = +        conn +        |> post("/oauth/authorize", %{ +          "authorization" => %{ +            "name" => user.nickname, +            "password" => "test", +            "client_id" => app.client_id, +            "redirect_uri" => app.redirect_uris, +            "state" => "statepassed", +            "scope" => "" +          } +        }) +        |> html_response(:unauthorized) + +      # Keep the details +      assert result =~ app.client_id +      assert result =~ app.redirect_uris + +      # Error message +      assert result =~ "This action is outside the authorized scopes" +    end + +    test "returns 401 for scopes beyond app scopes", %{conn: conn} do +      user = insert(:user) +      app = insert(:oauth_app, scopes: ["read", "write"]) + +      result = +        conn +        |> post("/oauth/authorize", %{ +          "authorization" => %{ +            "name" => user.nickname, +            "password" => "test", +            "client_id" => app.client_id, +            "redirect_uri" => app.redirect_uris, +            "state" => "statepassed", +            "scope" => "read write follow" +          } +        }) +        |> html_response(:unauthorized) + +      # Keep the details +      assert result =~ app.client_id +      assert result =~ app.redirect_uris + +      # Error message +      assert result =~ "This action is outside the authorized scopes" +    end    end -  test "returns 401 for scopes beyond app scopes", %{conn: conn} do -    user = insert(:user) -    app = insert(:oauth_app, scopes: ["read", "write"]) +  describe "POST /oauth/token" do +    test "issues a token for an all-body request" do +      user = insert(:user) +      app = insert(:oauth_app, scopes: ["read", "write"]) -    result = -      conn -      |> post("/oauth/authorize", %{ -        "authorization" => %{ -          "name" => user.nickname, -          "password" => "test", -          "client_id" => app.client_id, +      {:ok, auth} = Authorization.create_authorization(app, user, ["write"]) + +      conn = +        build_conn() +        |> post("/oauth/token", %{ +          "grant_type" => "authorization_code", +          "code" => auth.token,            "redirect_uri" => app.redirect_uris, -          "state" => "statepassed", -          "scope" => "read write follow" -        } -      }) -      |> html_response(:unauthorized) - -    # Keep the details -    assert result =~ app.client_id -    assert result =~ app.redirect_uris - -    # Error message -    assert result =~ "This action is outside the authorized scopes" -  end +          "client_id" => app.client_id, +          "client_secret" => app.client_secret +        }) -  test "issues a token for an all-body request" do -    user = insert(:user) -    app = insert(:oauth_app, scopes: ["read", "write"]) +      assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200) -    {:ok, auth} = Authorization.create_authorization(app, user, ["write"]) +      token = Repo.get_by(Token, token: token) +      assert token +      assert token.scopes == auth.scopes +      assert user.ap_id == ap_id +    end -    conn = -      build_conn() -      |> post("/oauth/token", %{ -        "grant_type" => "authorization_code", -        "code" => auth.token, -        "redirect_uri" => app.redirect_uris, -        "client_id" => app.client_id, -        "client_secret" => app.client_secret -      }) +    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)) -    assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200) +      app = insert(:oauth_app, scopes: ["read", "write"]) -    token = Repo.get_by(Token, token: token) -    assert token -    assert token.scopes == auth.scopes -    assert user.ap_id == ap_id -  end +      # Note: "scope" param is intentionally omitted +      conn = +        build_conn() +        |> post("/oauth/token", %{ +          "grant_type" => "password", +          "username" => user.nickname, +          "password" => password, +          "client_id" => app.client_id, +          "client_secret" => app.client_secret +        }) -  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)) +      assert %{"access_token" => token} = json_response(conn, 200) -    app = insert(:oauth_app, scopes: ["read", "write"]) +      token = Repo.get_by(Token, token: token) +      assert token +      assert token.scopes == app.scopes +    end -    # Note: "scope" param is intentionally omitted -    conn = -      build_conn() -      |> post("/oauth/token", %{ -        "grant_type" => "password", -        "username" => user.nickname, -        "password" => password, -        "client_id" => app.client_id, -        "client_secret" => app.client_secret -      }) +    test "issues a token for request with HTTP basic auth client credentials" do +      user = insert(:user) +      app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"]) -    assert %{"access_token" => token} = json_response(conn, 200) +      {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"]) +      assert auth.scopes == ["scope1", "scope2"] -    token = Repo.get_by(Token, token: token) -    assert token -    assert token.scopes == app.scopes -  end +      app_encoded = +        (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret)) +        |> Base.encode64() -  test "issues a token for request with HTTP basic auth client credentials" do -    user = insert(:user) -    app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"]) +      conn = +        build_conn() +        |> put_req_header("authorization", "Basic " <> app_encoded) +        |> post("/oauth/token", %{ +          "grant_type" => "authorization_code", +          "code" => auth.token, +          "redirect_uri" => app.redirect_uris +        }) -    {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"]) -    assert auth.scopes == ["scope1", "scope2"] +      assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200) -    app_encoded = -      (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret)) -      |> Base.encode64() +      assert scope == "scope1 scope2" -    conn = -      build_conn() -      |> put_req_header("authorization", "Basic " <> app_encoded) -      |> post("/oauth/token", %{ -        "grant_type" => "authorization_code", -        "code" => auth.token, -        "redirect_uri" => app.redirect_uris -      }) +      token = Repo.get_by(Token, token: token) +      assert token +      assert token.scopes == ["scope1", "scope2"] +    end -    assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200) +    test "rejects token exchange with invalid client credentials" do +      user = insert(:user) +      app = insert(:oauth_app) -    assert scope == "scope1 scope2" +      {:ok, auth} = Authorization.create_authorization(app, user) -    token = Repo.get_by(Token, token: token) -    assert token -    assert token.scopes == ["scope1", "scope2"] -  end +      conn = +        build_conn() +        |> put_req_header("authorization", "Basic JTIxOiVGMCU5RiVBNCVCNwo=") +        |> post("/oauth/token", %{ +          "grant_type" => "authorization_code", +          "code" => auth.token, +          "redirect_uri" => app.redirect_uris +        }) -  test "rejects token exchange with invalid client credentials" do -    user = insert(:user) -    app = insert(:oauth_app) +      assert resp = json_response(conn, 400) +      assert %{"error" => _} = resp +      refute Map.has_key?(resp, "access_token") +    end -    {:ok, auth} = Authorization.create_authorization(app, user) +    test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do +      setting = Pleroma.Config.get([:instance, :account_activation_required]) -    conn = -      build_conn() -      |> put_req_header("authorization", "Basic JTIxOiVGMCU5RiVBNCVCNwo=") -      |> post("/oauth/token", %{ -        "grant_type" => "authorization_code", -        "code" => auth.token, -        "redirect_uri" => app.redirect_uris -      }) +      unless setting do +        Pleroma.Config.put([:instance, :account_activation_required], true) +        on_exit(fn -> Pleroma.Config.put([:instance, :account_activation_required], setting) end) +      end -    assert resp = json_response(conn, 400) -    assert %{"error" => _} = resp -    refute Map.has_key?(resp, "access_token") -  end +      password = "testpassword" +      user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password)) +      info_change = Pleroma.User.Info.confirmation_changeset(user.info, :unconfirmed) -  test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do -    setting = Pleroma.Config.get([:instance, :account_activation_required]) +      {:ok, user} = +        user +        |> Ecto.Changeset.change() +        |> Ecto.Changeset.put_embed(:info, info_change) +        |> Repo.update() -    unless setting do -      Pleroma.Config.put([:instance, :account_activation_required], true) -      on_exit(fn -> Pleroma.Config.put([:instance, :account_activation_required], setting) end) -    end +      refute Pleroma.User.auth_active?(user) -    password = "testpassword" -    user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password)) -    info_change = Pleroma.User.Info.confirmation_changeset(user.info, :unconfirmed) +      app = insert(:oauth_app) -    {:ok, user} = -      user -      |> Ecto.Changeset.change() -      |> Ecto.Changeset.put_embed(:info, info_change) -      |> Repo.update() +      conn = +        build_conn() +        |> post("/oauth/token", %{ +          "grant_type" => "password", +          "username" => user.nickname, +          "password" => password, +          "client_id" => app.client_id, +          "client_secret" => app.client_secret +        }) -    refute Pleroma.User.auth_active?(user) +      assert resp = json_response(conn, 403) +      assert %{"error" => _} = resp +      refute Map.has_key?(resp, "access_token") +    end -    app = insert(:oauth_app) +    test "rejects token exchange for valid credentials belonging to deactivated user" do +      password = "testpassword" -    conn = -      build_conn() -      |> post("/oauth/token", %{ -        "grant_type" => "password", -        "username" => user.nickname, -        "password" => password, -        "client_id" => app.client_id, -        "client_secret" => app.client_secret -      }) +      user = +        insert(:user, +          password_hash: Comeonin.Pbkdf2.hashpwsalt(password), +          info: %{deactivated: true} +        ) -    assert resp = json_response(conn, 403) -    assert %{"error" => _} = resp -    refute Map.has_key?(resp, "access_token") -  end +      app = insert(:oauth_app) -  test "rejects an invalid authorization code" do -    app = insert(:oauth_app) +      conn = +        build_conn() +        |> post("/oauth/token", %{ +          "grant_type" => "password", +          "username" => user.nickname, +          "password" => password, +          "client_id" => app.client_id, +          "client_secret" => app.client_secret +        }) -    conn = -      build_conn() -      |> post("/oauth/token", %{ -        "grant_type" => "authorization_code", -        "code" => "Imobviouslyinvalid", -        "redirect_uri" => app.redirect_uris, -        "client_id" => app.client_id, -        "client_secret" => app.client_secret -      }) +      assert resp = json_response(conn, 403) +      assert %{"error" => _} = resp +      refute Map.has_key?(resp, "access_token") +    end + +    test "rejects an invalid authorization code" do +      app = insert(:oauth_app) -    assert resp = json_response(conn, 400) -    assert %{"error" => _} = json_response(conn, 400) -    refute Map.has_key?(resp, "access_token") +      conn = +        build_conn() +        |> post("/oauth/token", %{ +          "grant_type" => "authorization_code", +          "code" => "Imobviouslyinvalid", +          "redirect_uri" => app.redirect_uris, +          "client_id" => app.client_id, +          "client_secret" => app.client_secret +        }) + +      assert resp = json_response(conn, 400) +      assert %{"error" => _} = json_response(conn, 400) +      refute Map.has_key?(resp, "access_token") +    end    end  end diff --git a/test/web/ostatus/activity_representer_test.exs b/test/web/ostatus/activity_representer_test.exs index 5cb135b4c..a4bb68c4d 100644 --- a/test/web/ostatus/activity_representer_test.exs +++ b/test/web/ostatus/activity_representer_test.exs @@ -116,10 +116,10 @@ defmodule Pleroma.Web.OStatus.ActivityRepresenterTest do      {:ok, announce, _object} = ActivityPub.announce(user, object) -    announce = Repo.get(Activity, announce.id) +    announce = Activity.get_by_id(announce.id)      note_user = User.get_cached_by_ap_id(note.data["actor"]) -    note = Repo.get(Activity, note.id) +    note = Activity.get_by_id(note.id)      note_xml =        ActivityRepresenter.to_simple_form(note, note_user, true) diff --git a/test/web/ostatus/incoming_documents/delete_handling_test.exs b/test/web/ostatus/incoming_documents/delete_handling_test.exs index 412d894fd..ca6e61339 100644 --- a/test/web/ostatus/incoming_documents/delete_handling_test.exs +++ b/test/web/ostatus/incoming_documents/delete_handling_test.exs @@ -6,7 +6,6 @@ defmodule Pleroma.Web.OStatus.DeleteHandlingTest do    alias Pleroma.Activity    alias Pleroma.Object -  alias Pleroma.Repo    alias Pleroma.Web.OStatus    setup do @@ -32,10 +31,10 @@ defmodule Pleroma.Web.OStatus.DeleteHandlingTest do        {:ok, [delete]} = OStatus.handle_incoming(incoming) -      refute Repo.get(Activity, note.id) -      refute Repo.get(Activity, like.id) +      refute Activity.get_by_id(note.id) +      refute Activity.get_by_id(like.id)        assert Object.get_by_ap_id(note.data["object"]["id"]).data["type"] == "Tombstone" -      assert Repo.get(Activity, second_note.id) +      assert Activity.get_by_id(second_note.id)        assert Object.get_by_ap_id(second_note.data["object"]["id"])        assert delete.data["type"] == "Delete" diff --git a/test/web/ostatus/ostatus_test.exs b/test/web/ostatus/ostatus_test.exs index 76b90e186..9fd100f63 100644 --- a/test/web/ostatus/ostatus_test.exs +++ b/test/web/ostatus/ostatus_test.exs @@ -154,7 +154,7 @@ defmodule Pleroma.Web.OStatusTest do      assert "https://pleroma.soykaf.com/users/lain" in activity.data["to"]      refute activity.local -    retweeted_activity = Repo.get(Activity, retweeted_activity.id) +    retweeted_activity = Activity.get_by_id(retweeted_activity.id)      assert retweeted_activity.data["type"] == "Create"      assert retweeted_activity.data["actor"] == "https://pleroma.soykaf.com/users/lain"      refute retweeted_activity.local @@ -181,7 +181,7 @@ defmodule Pleroma.Web.OStatusTest do      assert user.ap_id in activity.data["to"]      refute activity.local -    retweeted_activity = Repo.get(Activity, retweeted_activity.id) +    retweeted_activity = Activity.get_by_id(retweeted_activity.id)      assert note_activity.id == retweeted_activity.id      assert retweeted_activity.data["type"] == "Create"      assert retweeted_activity.data["actor"] == user.ap_id @@ -344,7 +344,7 @@ defmodule Pleroma.Web.OStatusTest do        {:ok, user} = OStatus.find_or_make_user(uri) -      user = Repo.get(Pleroma.User, user.id) +      user = Pleroma.User.get_by_id(user.id)        assert user.name == "Constance Variable"        assert user.nickname == "lambadalambda@social.heldscal.la"        assert user.local == false diff --git a/test/web/push/impl_test.exs b/test/web/push/impl_test.exs index 3f9f3d809..6bac2c9f6 100644 --- a/test/web/push/impl_test.exs +++ b/test/web/push/impl_test.exs @@ -64,17 +64,19 @@ defmodule Pleroma.Web.Push.ImplTest do          }        ) -    assert Impl.perform_send(notif) == [:ok, :ok] +    assert Impl.perform(notif) == [:ok, :ok]    end +  @tag capture_log: true    test "returns error if notif does not match " do -    assert Impl.perform_send(%{}) == :error +    assert Impl.perform(%{}) == :error    end    test "successful message sending" do      assert Impl.push_message(@message, @sub, @api_key, %Subscription{}) == :ok    end +  @tag capture_log: true    test "fail message sending" do      assert Impl.push_message(               @message, diff --git a/test/web/salmon/salmon_test.exs b/test/web/salmon/salmon_test.exs index 265e1abbd..35503259b 100644 --- a/test/web/salmon/salmon_test.exs +++ b/test/web/salmon/salmon_test.exs @@ -99,7 +99,7 @@ defmodule Pleroma.Web.Salmon.SalmonTest do      }      {:ok, activity} = Repo.insert(%Activity{data: activity_data, recipients: activity_data["to"]}) -    user = Repo.get_by(User, ap_id: activity.data["actor"]) +    user = User.get_by_ap_id(activity.data["actor"])      {:ok, user} = Pleroma.Web.WebFinger.ensure_keys_present(user)      poster = fn url, _data, _headers -> diff --git a/test/web/twitter_api/twitter_api_controller_test.exs b/test/web/twitter_api/twitter_api_controller_test.exs index 083540017..72b7ea85e 100644 --- a/test/web/twitter_api/twitter_api_controller_test.exs +++ b/test/web/twitter_api/twitter_api_controller_test.exs @@ -719,7 +719,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do          |> with_credentials(current_user.nickname, "test")          |> post("/api/friendships/create.json", %{user_id: followed.id}) -      current_user = Repo.get(User, current_user.id) +      current_user = User.get_by_id(current_user.id)        assert User.ap_followers(followed) in current_user.following        assert json_response(conn, 200) == @@ -734,8 +734,8 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do          |> with_credentials(current_user.nickname, "test")          |> post("/api/friendships/create.json", %{user_id: followed.id}) -      current_user = Repo.get(User, current_user.id) -      followed = Repo.get(User, followed.id) +      current_user = User.get_by_id(current_user.id) +      followed = User.get_by_id(followed.id)        refute User.ap_followers(followed) in current_user.following @@ -764,7 +764,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do          |> with_credentials(current_user.nickname, "test")          |> post("/api/friendships/destroy.json", %{user_id: followed.id}) -      current_user = Repo.get(User, current_user.id) +      current_user = User.get_by_id(current_user.id)        assert current_user.following == [current_user.ap_id]        assert json_response(conn, 200) == @@ -788,7 +788,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do          |> with_credentials(current_user.nickname, "test")          |> post("/api/blocks/create.json", %{user_id: blocked.id}) -      current_user = Repo.get(User, current_user.id) +      current_user = User.get_by_id(current_user.id)        assert User.blocks?(current_user, blocked)        assert json_response(conn, 200) == @@ -815,7 +815,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do          |> with_credentials(current_user.nickname, "test")          |> post("/api/blocks/destroy.json", %{user_id: blocked.id}) -      current_user = Repo.get(User, current_user.id) +      current_user = User.get_by_id(current_user.id)        assert current_user.info.blocks == []        assert json_response(conn, 200) == @@ -846,7 +846,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do          |> with_credentials(current_user.nickname, "test")          |> post("/api/qvitter/update_avatar.json", %{img: avatar_image}) -      current_user = Repo.get(User, current_user.id) +      current_user = User.get_by_id(current_user.id)        assert is_map(current_user.avatar)        assert json_response(conn, 200) == @@ -954,8 +954,8 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do          |> with_credentials(current_user.nickname, "test")          |> post(request_path) -      activity = Repo.get(Activity, note_activity.id) -      activity_user = Repo.get_by(User, ap_id: note_activity.data["actor"]) +      activity = Activity.get_by_id(note_activity.id) +      activity_user = User.get_by_ap_id(note_activity.data["actor"])        assert json_response(response, 200) ==                 ActivityView.render("activity.json", %{ @@ -992,8 +992,8 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do          |> with_credentials(current_user.nickname, "test")          |> post(request_path) -      activity = Repo.get(Activity, note_activity.id) -      activity_user = Repo.get_by(User, ap_id: note_activity.data["actor"]) +      activity = Activity.get_by_id(note_activity.id) +      activity_user = User.get_by_ap_id(note_activity.data["actor"])        assert json_response(response, 200) ==                 ActivityView.render("activity.json", %{ @@ -1021,7 +1021,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do        user = json_response(conn, 200) -      fetched_user = Repo.get_by(User, nickname: "lain") +      fetched_user = User.get_by_nickname("lain")        assert user == UserView.render("show.json", %{user: fetched_user})      end @@ -1109,7 +1109,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do      test "it confirms the user account", %{conn: conn, user: user} do        get(conn, "/api/account/confirm_email/#{user.id}/#{user.info.confirmation_token}") -      user = Repo.get(User, user.id) +      user = User.get_by_id(user.id)        refute user.info.confirmation_pending        refute user.info.confirmation_token @@ -1727,7 +1727,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do          })        assert json_response(conn, 200) == %{"status" => "success"} -      fetched_user = Repo.get(User, current_user.id) +      fetched_user = User.get_by_id(current_user.id)        assert Pbkdf2.checkpw("newpass", fetched_user.password_hash) == true      end    end @@ -1768,8 +1768,8 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do        {:ok, _activity} = ActivityPub.follow(other_user, user) -      user = Repo.get(User, user.id) -      other_user = Repo.get(User, other_user.id) +      user = User.get_by_id(user.id) +      other_user = User.get_by_id(other_user.id)        assert User.following?(other_user, user) == false @@ -1808,8 +1808,8 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do        {:ok, _activity} = ActivityPub.follow(other_user, user) -      user = Repo.get(User, user.id) -      other_user = Repo.get(User, other_user.id) +      user = User.get_by_id(user.id) +      other_user = User.get_by_id(other_user.id)        assert User.following?(other_user, user) == false @@ -1831,8 +1831,8 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do        {:ok, _activity} = ActivityPub.follow(other_user, user) -      user = Repo.get(User, user.id) -      other_user = Repo.get(User, other_user.id) +      user = User.get_by_id(user.id) +      other_user = User.get_by_id(other_user.id)        assert User.following?(other_user, user) == false diff --git a/test/web/twitter_api/twitter_api_test.exs b/test/web/twitter_api/twitter_api_test.exs index b823bfd68..6c00244de 100644 --- a/test/web/twitter_api/twitter_api_test.exs +++ b/test/web/twitter_api/twitter_api_test.exs @@ -275,7 +275,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do      {:ok, user} = TwitterAPI.register_user(data) -    fetched_user = Repo.get_by(User, nickname: "lain") +    fetched_user = User.get_by_nickname("lain")      assert UserView.render("show.json", %{user: user}) ==               UserView.render("show.json", %{user: fetched_user}) @@ -293,7 +293,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do      {:ok, user} = TwitterAPI.register_user(data) -    fetched_user = Repo.get_by(User, nickname: "lain") +    fetched_user = User.get_by_nickname("lain")      assert UserView.render("show.json", %{user: user}) ==               UserView.render("show.json", %{user: fetched_user}) @@ -369,7 +369,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do      {:ok, user} = TwitterAPI.register_user(data) -    fetched_user = Repo.get_by(User, nickname: "vinny") +    fetched_user = User.get_by_nickname("vinny")      token = Repo.get_by(UserInviteToken, token: token.token)      assert token.used == true @@ -393,7 +393,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do      {:error, msg} = TwitterAPI.register_user(data)      assert msg == "Invalid token" -    refute Repo.get_by(User, nickname: "GrimReaper") +    refute User.get_by_nickname("GrimReaper")    end    @moduletag skip: "needs 'registrations_open: false' in config" @@ -414,7 +414,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do      {:error, msg} = TwitterAPI.register_user(data)      assert msg == "Expired token" -    refute Repo.get_by(User, nickname: "GrimReaper") +    refute User.get_by_nickname("GrimReaper")    end    test "it returns the error on registration problems" do @@ -429,7 +429,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do      {:error, error_object} = TwitterAPI.register_user(data)      assert is_binary(error_object[:error]) -    refute Repo.get_by(User, nickname: "lain") +    refute User.get_by_nickname("lain")    end    test "it assigns an integer conversation_id" do diff --git a/test/web/twitter_api/util_controller_test.exs b/test/web/twitter_api/util_controller_test.exs index 832fdc096..410f20f87 100644 --- a/test/web/twitter_api/util_controller_test.exs +++ b/test/web/twitter_api/util_controller_test.exs @@ -6,6 +6,11 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do    alias Pleroma.Web.CommonAPI    import Pleroma.Factory +  setup do +    Tesla.Mock.mock(fn env -> apply(HttpRequestMock, :request, [env]) end) +    :ok +  end +    describe "POST /api/pleroma/follow_import" do      test "it returns HTTP 200", %{conn: conn} do        user1 = insert(:user) @@ -164,4 +169,47 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do        assert response == Jason.encode!(config |> Enum.into(%{})) |> Jason.decode!()      end    end + +  describe "/api/pleroma/emoji" do +    test "returns json with custom emoji with tags", %{conn: conn} do +      [emoji | _body] = +        conn +        |> get("/api/pleroma/emoji") +        |> json_response(200) + +      [key] = Map.keys(emoji) + +      %{ +        ^key => %{ +          "image_url" => url, +          "tags" => tags +        } +      } = emoji + +      assert is_binary(url) +      assert is_list(tags) +    end +  end + +  describe "GET /ostatus_subscribe?acct=...." do +    test "adds status to pleroma instance if the `acct` is a status", %{conn: conn} do +      conn = +        get( +          conn, +          "/ostatus_subscribe?acct=https://mastodon.social/users/emelie/statuses/101849165031453009" +        ) + +      assert redirected_to(conn) =~ "/notice/" +    end + +    test "show follow account page if the `acct` is a account link", %{conn: conn} do +      response = +        get( +          conn, +          "/ostatus_subscribe?acct=https://mastodon.social/users/emelie" +        ) + +      assert html_response(response, 200) =~ "Log in to follow" +    end +  end  end diff --git a/test/web/twitter_api/views/activity_view_test.exs b/test/web/twitter_api/views/activity_view_test.exs index a1776b3e6..ee9a0c834 100644 --- a/test/web/twitter_api/views/activity_view_test.exs +++ b/test/web/twitter_api/views/activity_view_test.exs @@ -281,7 +281,7 @@ defmodule Pleroma.Web.TwitterAPI.ActivityViewTest do      convo_id = Utils.context_to_conversation_id(activity.data["object"]["context"]) -    activity = Repo.get(Activity, activity.id) +    activity = Activity.get_by_id(activity.id)      result = ActivityView.render("activity.json", activity: announce) diff --git a/test/web/twitter_api/views/user_view_test.exs b/test/web/twitter_api/views/user_view_test.exs index 4e7f94795..0feaf4b64 100644 --- a/test/web/twitter_api/views/user_view_test.exs +++ b/test/web/twitter_api/views/user_view_test.exs @@ -292,7 +292,7 @@ defmodule Pleroma.Web.TwitterAPI.UserViewTest do        }      } -    blocker = Repo.get(User, blocker.id) +    blocker = User.get_by_id(blocker.id)      assert represented == UserView.render("show.json", %{user: user, for: blocker})    end | 
