Merge branch 'develop' into admin-be

This commit is contained in:
Alexander Strizhakov 2020-01-11 12:15:42 +03:00
commit 1630ecaa20
No known key found for this signature in database
GPG key ID: 022896A53AEF1381
39 changed files with 1263 additions and 1966 deletions

View file

@ -18,16 +18,13 @@ def call(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
token = assigns[:token] token = assigns[:token]
scopes = transform_scopes(scopes, options) scopes = transform_scopes(scopes, options)
matched_scopes = token && filter_descendants(scopes, token.scopes) matched_scopes = (token && filter_descendants(scopes, token.scopes)) || []
cond do cond do
is_nil(token) -> token && op == :| && Enum.any?(matched_scopes) ->
maybe_perform_instance_privacy_check(conn, options)
op == :| && Enum.any?(matched_scopes) ->
conn conn
op == :& && matched_scopes == scopes -> token && op == :& && matched_scopes == scopes ->
conn conn
options[:fallback] == :proceed_unauthenticated -> options[:fallback] == :proceed_unauthenticated ->

View file

@ -1430,9 +1430,36 @@ def get_or_fetch_by_ap_id(ap_id) do
Creates an internal service actor by URI if missing. Creates an internal service actor by URI if missing.
Optionally takes nickname for addressing. Optionally takes nickname for addressing.
""" """
def get_or_create_service_actor_by_ap_id(uri, nickname \\ nil) do @spec get_or_create_service_actor_by_ap_id(String.t(), String.t()) :: User.t() | nil
with user when is_nil(user) <- get_cached_by_ap_id(uri) do def get_or_create_service_actor_by_ap_id(uri, nickname) do
{:ok, user} = {_, user} =
case get_cached_by_ap_id(uri) do
nil ->
with {:error, %{errors: errors}} <- create_service_actor(uri, nickname) do
Logger.error("Cannot create service actor: #{uri}/.\n#{inspect(errors)}")
{:error, nil}
end
%User{invisible: false} = user ->
set_invisible(user)
user ->
{:ok, user}
end
user
end
@spec set_invisible(User.t()) :: {:ok, User.t()}
defp set_invisible(user) do
user
|> change(%{invisible: true})
|> update_and_set_cache()
end
@spec create_service_actor(String.t(), String.t()) ::
{:ok, User.t()} | {:error, Ecto.Changeset.t()}
defp create_service_actor(uri, nickname) do
%User{ %User{
invisible: true, invisible: true,
local: true, local: true,
@ -1440,10 +1467,10 @@ def get_or_create_service_actor_by_ap_id(uri, nickname \\ nil) do
nickname: nickname, nickname: nickname,
follower_address: uri <> "/followers" follower_address: uri <> "/followers"
} }
|> change
|> unique_constraint(:nickname)
|> Repo.insert() |> Repo.insert()
|> set_cache()
user
end
end end
# AP style # AP style
@ -1855,9 +1882,9 @@ def admin_api_update(user, params) do
]) ])
with {:ok, updated_user} <- update_and_set_cache(changeset) do with {:ok, updated_user} <- update_and_set_cache(changeset) do
if user.is_admin && !updated_user.is_admin do if user.is_admin != updated_user.is_admin do
# Tokens & authorizations containing any admin scopes must be revoked (revoking all). # Admin status change results in change of accessible OAuth scopes, and instead of changing
# This is an extra safety measure (tokens' admin scopes won't be accepted for non-admins). # already issued tokens we revoke them, requiring user to sign in again
global_sign_out(user) global_sign_out(user)
end end

View file

@ -9,10 +9,12 @@ defmodule Pleroma.Web.ActivityPub.Relay do
alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.ActivityPub.ActivityPub
require Logger require Logger
@relay_nickname "relay"
def get_actor do def get_actor do
actor = actor =
relay_ap_id() relay_ap_id()
|> User.get_or_create_service_actor_by_ap_id() |> User.get_or_create_service_actor_by_ap_id(@relay_nickname)
actor actor
end end

View file

@ -88,7 +88,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
plug( plug(
OAuthScopesPlug, OAuthScopesPlug,
%{scopes: ["read"], admin: true} %{scopes: ["read"], admin: true}
when action in [:config_show, :migrate_to_db, :migrate_from_db, :list_log] when action in [:config_show, :migrate_from_db, :list_log]
) )
plug( plug(

View file

@ -20,19 +20,22 @@ defmodule Pleroma.Web.MastoFEController do
plug(Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug when action != :index) plug(Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug when action != :index)
@doc "GET /web/*path" @doc "GET /web/*path"
def index(%{assigns: %{user: user}} = conn, _params) do def index(%{assigns: %{user: user, token: token}} = conn, _params)
token = get_session(conn, :oauth_token) when not is_nil(user) and not is_nil(token) do
if user && token do
conn conn
|> put_layout(false) |> put_layout(false)
|> render("index.html", token: token, user: user, custom_emojis: Pleroma.Emoji.get_all()) |> render("index.html",
else token: token.token,
user: user,
custom_emojis: Pleroma.Emoji.get_all()
)
end
def index(conn, _params) do
conn conn
|> put_session(:return_to, conn.request_path) |> put_session(:return_to, conn.request_path)
|> redirect(to: "/web/login") |> redirect(to: "/web/login")
end end
end
@doc "GET /web/manifest.json" @doc "GET /web/manifest.json"
def manifest(conn, _params) do def manifest(conn, _params) do

View file

@ -52,7 +52,7 @@ def list_from(conn, %{"instance_address" => address}) do
@doc """ @doc """
Lists the packs available on the instance as JSON. Lists the packs available on the instance as JSON.
The information is public and does not require authentification. The format is The information is public and does not require authentication. The format is
a map of "pack directory name" to pack.json contents. a map of "pack directory name" to pack.json contents.
""" """
def list_packs(conn, _params) do def list_packs(conn, _params) do

View file

@ -22,7 +22,14 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIController do
plug( plug(
OAuthScopesPlug, OAuthScopesPlug,
%{scopes: ["read:statuses"]} when action in [:conversation, :conversation_statuses] %{scopes: ["read:statuses"]}
when action in [:conversation, :conversation_statuses, :emoji_reactions_by]
)
plug(
OAuthScopesPlug,
%{scopes: ["write:statuses"]}
when action in [:react_with_emoji, :unreact_with_emoji]
) )
plug( plug(

View file

@ -22,7 +22,14 @@ defmodule Pleroma.Web.TwitterAPI.UtilController do
plug( plug(
OAuthScopesPlug, OAuthScopesPlug,
%{scopes: ["follow", "write:follows"]} %{scopes: ["follow", "write:follows"]}
when action in [:do_remote_follow, :follow_import] when action == :follow_import
)
# Note: follower can submit the form (with password auth) not being signed in (having no token)
plug(
OAuthScopesPlug,
%{fallback: :proceed_unauthenticated, scopes: ["follow", "write:follows"]}
when action == :do_remote_follow
) )
plug(OAuthScopesPlug, %{scopes: ["follow", "write:blocks"]} when action == :blocks_import) plug(OAuthScopesPlug, %{scopes: ["follow", "write:blocks"]} when action == :blocks_import)
@ -113,6 +120,28 @@ defp is_status?(acct) do
end end
end end
def do_remote_follow(%{assigns: %{user: user}} = conn, %{"user" => %{"id" => id}})
when not is_nil(user) do
with {:fetch_user, %User{} = followee} <- {:fetch_user, User.get_cached_by_id(id)},
{:ok, _follower, _followee, _activity} <- CommonAPI.follow(user, followee) do
conn
|> render("followed.html", %{error: false})
else
# Was already following user
{:error, "Could not follow user:" <> _rest} ->
render(conn, "followed.html", %{error: "Error following account"})
{:fetch_user, error} ->
Logger.debug("Remote follow failed with error #{inspect(error)}")
render(conn, "followed.html", %{error: "Could not find user"})
e ->
Logger.debug("Remote follow failed with error #{inspect(e)}")
render(conn, "followed.html", %{error: "Something went wrong."})
end
end
# Note: "id" is the id of followee user, disregard incorrect placing under "authorization"
def do_remote_follow(conn, %{ def do_remote_follow(conn, %{
"authorization" => %{"name" => username, "password" => password, "id" => id} "authorization" => %{"name" => username, "password" => password, "id" => id}
}) do }) do
@ -146,24 +175,12 @@ def do_remote_follow(conn, %{
end end
end end
def do_remote_follow(%{assigns: %{user: user}} = conn, %{"user" => %{"id" => id}}) do def do_remote_follow(%{assigns: %{user: nil}} = conn, _) do
with {:fetch_user, %User{} = followee} <- {:fetch_user, User.get_cached_by_id(id)}, render(conn, "followed.html", %{error: "Insufficient permissions: follow | write:follows."})
{:ok, _follower, _followee, _activity} <- CommonAPI.follow(user, followee) do
conn
|> render("followed.html", %{error: false})
else
# Was already following user
{:error, "Could not follow user:" <> _rest} ->
render(conn, "followed.html", %{error: "Error following account"})
{:fetch_user, error} ->
Logger.debug("Remote follow failed with error #{inspect(error)}")
render(conn, "followed.html", %{error: "Could not find user"})
e ->
Logger.debug("Remote follow failed with error #{inspect(e)}")
render(conn, "followed.html", %{error: "Something went wrong."})
end end
def do_remote_follow(conn, _) do
render(conn, "followed.html", %{error: "Something went wrong."})
end end
def notifications_read(%{assigns: %{user: user}} = conn, %{"id" => notification_id}) do def notifications_read(%{assigns: %{user: user}} = conn, %{"id" => notification_id}) do
@ -346,7 +363,9 @@ def change_email(%{assigns: %{user: user}} = conn, params) do
end end
def delete_account(%{assigns: %{user: user}} = conn, params) do def delete_account(%{assigns: %{user: user}} = conn, params) do
case CommonAPI.Utils.confirm_current_password(user, params["password"]) do password = params["password"] || ""
case CommonAPI.Utils.confirm_current_password(user, password) do
{:ok, user} -> {:ok, user} ->
User.delete(user) User.delete(user)
json(conn, %{status: "success"}) json(conn, %{status: "success"})

View file

@ -98,7 +98,7 @@ test "it creates a notification for user if the user blocks the activity author"
assert Notification.create_notification(activity, user) assert Notification.create_notification(activity, user)
end end
test "it creates a notificatin for the user if the user mutes the activity author" do test "it creates a notification for the user if the user mutes the activity author" do
muter = insert(:user) muter = insert(:user)
muted = insert(:user) muted = insert(:user)
{:ok, _} = User.mute(muter, muted) {:ok, _} = User.mute(muter, muted)

View file

@ -16,34 +16,6 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do
:ok :ok
end end
describe "when `assigns[:token]` is nil, " do
test "with :skip_instance_privacy_check option, proceeds with no op", %{conn: conn} do
conn =
conn
|> assign(:user, insert(:user))
|> OAuthScopesPlug.call(%{scopes: ["read"], skip_instance_privacy_check: true})
refute conn.halted
assert conn.assigns[:user]
refute called(EnsurePublicOrAuthenticatedPlug.call(conn, :_))
end
test "without :skip_instance_privacy_check option, calls EnsurePublicOrAuthenticatedPlug", %{
conn: conn
} do
conn =
conn
|> assign(:user, insert(:user))
|> OAuthScopesPlug.call(%{scopes: ["read"]})
refute conn.halted
assert conn.assigns[:user]
assert called(EnsurePublicOrAuthenticatedPlug.call(conn, :_))
end
end
test "if `token.scopes` fulfills specified 'any of' conditions, " <> test "if `token.scopes` fulfills specified 'any of' conditions, " <>
"proceeds with no op", "proceeds with no op",
%{conn: conn} do %{conn: conn} do
@ -75,64 +47,56 @@ test "if `token.scopes` fulfills specified 'all of' conditions, " <>
end end
describe "with `fallback: :proceed_unauthenticated` option, " do describe "with `fallback: :proceed_unauthenticated` option, " do
test "if `token.scopes` doesn't fulfill specified 'any of' conditions, " <> test "if `token.scopes` doesn't fulfill specified conditions, " <>
"clears `assigns[:user]` and calls EnsurePublicOrAuthenticatedPlug", "clears :user and :token assigns and calls EnsurePublicOrAuthenticatedPlug",
%{conn: conn} do %{conn: conn} do
token = insert(:oauth_token, scopes: ["read", "write"]) |> Repo.preload(:user) user = insert(:user)
token1 = insert(:oauth_token, scopes: ["read", "write"], user: user)
conn = for token <- [token1, nil], op <- [:|, :&] do
ret_conn =
conn conn
|> assign(:user, token.user) |> assign(:user, user)
|> assign(:token, token)
|> OAuthScopesPlug.call(%{scopes: ["follow"], fallback: :proceed_unauthenticated})
refute conn.halted
refute conn.assigns[:user]
assert called(EnsurePublicOrAuthenticatedPlug.call(conn, :_))
end
test "if `token.scopes` doesn't fulfill specified 'all of' conditions, " <>
"clears `assigns[:user] and calls EnsurePublicOrAuthenticatedPlug",
%{conn: conn} do
token = insert(:oauth_token, scopes: ["read", "write"]) |> Repo.preload(:user)
conn =
conn
|> assign(:user, token.user)
|> assign(:token, token) |> assign(:token, token)
|> OAuthScopesPlug.call(%{ |> OAuthScopesPlug.call(%{
scopes: ["read", "follow"], scopes: ["follow"],
op: :&, op: op,
fallback: :proceed_unauthenticated fallback: :proceed_unauthenticated
}) })
refute conn.halted refute ret_conn.halted
refute conn.assigns[:user] refute ret_conn.assigns[:user]
refute ret_conn.assigns[:token]
assert called(EnsurePublicOrAuthenticatedPlug.call(conn, :_)) assert called(EnsurePublicOrAuthenticatedPlug.call(ret_conn, :_))
end
end end
test "with :skip_instance_privacy_check option, " <> test "with :skip_instance_privacy_check option, " <>
"if `token.scopes` doesn't fulfill specified conditions, " <> "if `token.scopes` doesn't fulfill specified conditions, " <>
"clears `assigns[:user]` and does not call EnsurePublicOrAuthenticatedPlug", "clears :user and :token assigns and does NOT call EnsurePublicOrAuthenticatedPlug",
%{conn: conn} do %{conn: conn} do
token = insert(:oauth_token, scopes: ["read:statuses", "write"]) |> Repo.preload(:user) user = insert(:user)
token1 = insert(:oauth_token, scopes: ["read:statuses", "write"], user: user)
conn = for token <- [token1, nil], op <- [:|, :&] do
ret_conn =
conn conn
|> assign(:user, token.user) |> assign(:user, user)
|> assign(:token, token) |> assign(:token, token)
|> OAuthScopesPlug.call(%{ |> OAuthScopesPlug.call(%{
scopes: ["read"], scopes: ["read"],
op: op,
fallback: :proceed_unauthenticated, fallback: :proceed_unauthenticated,
skip_instance_privacy_check: true skip_instance_privacy_check: true
}) })
refute conn.halted refute ret_conn.halted
refute conn.assigns[:user] refute ret_conn.assigns[:user]
refute ret_conn.assigns[:token]
refute called(EnsurePublicOrAuthenticatedPlug.call(conn, :_)) refute called(EnsurePublicOrAuthenticatedPlug.call(ret_conn, :_))
end
end end
end end
@ -140,25 +104,27 @@ test "with :skip_instance_privacy_check option, " <>
test "if `token.scopes` does not fulfill specified 'any of' conditions, " <> test "if `token.scopes` does not fulfill specified 'any of' conditions, " <>
"returns 403 and halts", "returns 403 and halts",
%{conn: conn} do %{conn: conn} do
token = insert(:oauth_token, scopes: ["read", "write"]) for token <- [insert(:oauth_token, scopes: ["read", "write"]), nil] do
any_of_scopes = ["follow"] any_of_scopes = ["follow", "push"]
conn = ret_conn =
conn conn
|> assign(:token, token) |> assign(:token, token)
|> OAuthScopesPlug.call(%{scopes: any_of_scopes}) |> OAuthScopesPlug.call(%{scopes: any_of_scopes})
assert conn.halted assert ret_conn.halted
assert 403 == conn.status assert 403 == ret_conn.status
expected_error = "Insufficient permissions: #{Enum.join(any_of_scopes, ", ")}." expected_error = "Insufficient permissions: #{Enum.join(any_of_scopes, " | ")}."
assert Jason.encode!(%{error: expected_error}) == conn.resp_body assert Jason.encode!(%{error: expected_error}) == ret_conn.resp_body
end
end end
test "if `token.scopes` does not fulfill specified 'all of' conditions, " <> test "if `token.scopes` does not fulfill specified 'all of' conditions, " <>
"returns 403 and halts", "returns 403 and halts",
%{conn: conn} do %{conn: conn} do
token = insert(:oauth_token, scopes: ["read", "write"]) for token <- [insert(:oauth_token, scopes: ["read", "write"]), nil] do
token_scopes = (token && token.scopes) || []
all_of_scopes = ["write", "follow"] all_of_scopes = ["write", "follow"]
conn = conn =
@ -170,11 +136,12 @@ test "if `token.scopes` does not fulfill specified 'all of' conditions, " <>
assert 403 == conn.status assert 403 == conn.status
expected_error = expected_error =
"Insufficient permissions: #{Enum.join(all_of_scopes -- token.scopes, ", ")}." "Insufficient permissions: #{Enum.join(all_of_scopes -- token_scopes, " & ")}."
assert Jason.encode!(%{error: expected_error}) == conn.resp_body assert Jason.encode!(%{error: expected_error}) == conn.resp_body
end end
end end
end
describe "with hierarchical scopes, " do describe "with hierarchical scopes, " do
test "if `token.scopes` fulfills specified 'any of' conditions, " <> test "if `token.scopes` fulfills specified 'any of' conditions, " <>

View file

@ -28,6 +28,26 @@ defmodule Pleroma.Web.ConnCase do
# The default endpoint for testing # The default endpoint for testing
@endpoint Pleroma.Web.Endpoint @endpoint Pleroma.Web.Endpoint
# Sets up OAuth access with specified scopes
defp oauth_access(scopes, opts \\ []) do
user =
Keyword.get_lazy(opts, :user, fn ->
Pleroma.Factory.insert(:user)
end)
token =
Keyword.get_lazy(opts, :oauth_token, fn ->
Pleroma.Factory.insert(:oauth_token, user: user, scopes: scopes)
end)
conn =
build_conn()
|> assign(:user, user)
|> assign(:token, token)
%{user: user, token: token, conn: conn}
end
end end
end end

View file

@ -296,7 +296,7 @@ def oauth_app_factory do
%Pleroma.Web.OAuth.App{ %Pleroma.Web.OAuth.App{
client_name: "Some client", client_name: "Some client",
redirect_uris: "https://example.com/callback", redirect_uris: "https://example.com/callback",
scopes: ["read", "write", "follow", "push"], scopes: ["read", "write", "follow", "push", "admin"],
website: "https://example.com", website: "https://example.com",
client_id: Ecto.UUID.generate(), client_id: Ecto.UUID.generate(),
client_secret: "aaa;/&bbb" client_secret: "aaa;/&bbb"
@ -310,19 +310,37 @@ def instance_factory do
} }
end end
def oauth_token_factory do def oauth_token_factory(attrs \\ %{}) do
oauth_app = insert(:oauth_app) scopes = Map.get(attrs, :scopes, ["read"])
oauth_app = Map.get_lazy(attrs, :app, fn -> insert(:oauth_app, scopes: scopes) end)
user = Map.get_lazy(attrs, :user, fn -> build(:user) end)
valid_until =
Map.get(attrs, :valid_until, NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10))
%Pleroma.Web.OAuth.Token{ %Pleroma.Web.OAuth.Token{
token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(), token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(),
scopes: ["read"],
refresh_token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(), refresh_token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(),
user: build(:user), scopes: scopes,
app_id: oauth_app.id, user: user,
valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10) app: oauth_app,
valid_until: valid_until
} }
end end
def oauth_admin_token_factory(attrs \\ %{}) do
user = Map.get_lazy(attrs, :user, fn -> build(:user, is_admin: true) end)
scopes =
attrs
|> Map.get(:scopes, ["admin"])
|> Kernel.++(["admin"])
|> Enum.uniq()
attrs = Map.merge(attrs, %{user: user, scopes: scopes})
oauth_token_factory(attrs)
end
def oauth_authorization_factory do def oauth_authorization_factory do
%Pleroma.Web.OAuth.Authorization{ %Pleroma.Web.OAuth.Authorization{
token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false), token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false),

View file

@ -17,6 +17,7 @@ defmodule Pleroma.UserTest do
import Mock import Mock
import Pleroma.Factory import Pleroma.Factory
import ExUnit.CaptureLog
setup_all do setup_all do
Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
@ -26,6 +27,42 @@ defmodule Pleroma.UserTest do
clear_config([:instance, :account_activation_required]) clear_config([:instance, :account_activation_required])
describe "service actors" do describe "service actors" do
test "returns updated invisible actor" do
uri = "#{Pleroma.Web.Endpoint.url()}/relay"
followers_uri = "#{uri}/followers"
insert(
:user,
%{
nickname: "relay",
invisible: false,
local: true,
ap_id: uri,
follower_address: followers_uri
}
)
actor = User.get_or_create_service_actor_by_ap_id(uri, "relay")
assert actor.invisible
end
test "returns relay user" do
uri = "#{Pleroma.Web.Endpoint.url()}/relay"
followers_uri = "#{uri}/followers"
assert %User{
nickname: "relay",
invisible: true,
local: true,
ap_id: ^uri,
follower_address: ^followers_uri
} = User.get_or_create_service_actor_by_ap_id(uri, "relay")
assert capture_log(fn ->
refute User.get_or_create_service_actor_by_ap_id("/relay", "relay")
end) =~ "Cannot create service actor:"
end
test "returns invisible actor" do test "returns invisible actor" do
uri = "#{Pleroma.Web.Endpoint.url()}/internal/fetch-test" uri = "#{Pleroma.Web.Endpoint.url()}/internal/fetch-test"
followers_uri = "#{uri}/followers" followers_uri = "#{uri}/followers"

File diff suppressed because it is too large Load diff

View file

@ -18,6 +18,7 @@ test "put settings", %{conn: conn} do
conn = conn =
conn conn
|> assign(:user, user) |> assign(:user, user)
|> assign(:token, insert(:oauth_token, user: user, scopes: ["write:accounts"]))
|> put("/api/web/settings", %{"data" => %{"programming" => "socks"}}) |> put("/api/web/settings", %{"data" => %{"programming" => "socks"}})
assert _result = json_response(conn, 200) assert _result = json_response(conn, 200)
@ -63,12 +64,12 @@ test "redirects not logged-in users to the login page on private instances", %{
end end
test "does not redirect logged in users to the login page", %{conn: conn, path: path} do test "does not redirect logged in users to the login page", %{conn: conn, path: path} do
token = insert(:oauth_token) token = insert(:oauth_token, scopes: ["read"])
conn = conn =
conn conn
|> assign(:user, token.user) |> assign(:user, token.user)
|> put_session(:oauth_token, token.token) |> assign(:token, token)
|> get(path) |> get(path)
assert conn.status == 200 assert conn.status == 200

View file

@ -12,13 +12,11 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do
clear_config([:instance, :max_account_fields]) clear_config([:instance, :max_account_fields])
describe "updating credentials" do describe "updating credentials" do
test "sets user settings in a generic way", %{conn: conn} do setup do: oauth_access(["write:accounts"])
user = insert(:user)
test "sets user settings in a generic way", %{conn: conn} do
res_conn = res_conn =
conn patch(conn, "/api/v1/accounts/update_credentials", %{
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{
"pleroma_settings_store" => %{ "pleroma_settings_store" => %{
pleroma_fe: %{ pleroma_fe: %{
theme: "bla" theme: "bla"
@ -26,10 +24,10 @@ test "sets user settings in a generic way", %{conn: conn} do
} }
}) })
assert user = json_response(res_conn, 200) assert user_data = json_response(res_conn, 200)
assert user["pleroma"]["settings_store"] == %{"pleroma_fe" => %{"theme" => "bla"}} assert user_data["pleroma"]["settings_store"] == %{"pleroma_fe" => %{"theme" => "bla"}}
user = Repo.get(User, user["id"]) user = Repo.get(User, user_data["id"])
res_conn = res_conn =
conn conn
@ -42,15 +40,15 @@ test "sets user settings in a generic way", %{conn: conn} do
} }
}) })
assert user = json_response(res_conn, 200) assert user_data = json_response(res_conn, 200)
assert user["pleroma"]["settings_store"] == assert user_data["pleroma"]["settings_store"] ==
%{ %{
"pleroma_fe" => %{"theme" => "bla"}, "pleroma_fe" => %{"theme" => "bla"},
"masto_fe" => %{"theme" => "bla"} "masto_fe" => %{"theme" => "bla"}
} }
user = Repo.get(User, user["id"]) user = Repo.get(User, user_data["id"])
res_conn = res_conn =
conn conn
@ -63,9 +61,9 @@ test "sets user settings in a generic way", %{conn: conn} do
} }
}) })
assert user = json_response(res_conn, 200) assert user_data = json_response(res_conn, 200)
assert user["pleroma"]["settings_store"] == assert user_data["pleroma"]["settings_store"] ==
%{ %{
"pleroma_fe" => %{"theme" => "bla"}, "pleroma_fe" => %{"theme" => "bla"},
"masto_fe" => %{"theme" => "blub"} "masto_fe" => %{"theme" => "blub"}
@ -73,97 +71,67 @@ test "sets user settings in a generic way", %{conn: conn} do
end end
test "updates the user's bio", %{conn: conn} do test "updates the user's bio", %{conn: conn} do
user = insert(:user)
user2 = insert(:user) user2 = insert(:user)
conn = conn =
conn patch(conn, "/api/v1/accounts/update_credentials", %{
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{
"note" => "I drink #cofe with @#{user2.nickname}" "note" => "I drink #cofe with @#{user2.nickname}"
}) })
assert user = json_response(conn, 200) assert user_data = json_response(conn, 200)
assert user["note"] == assert user_data["note"] ==
~s(I drink <a class="hashtag" data-tag="cofe" href="http://localhost:4001/tag/cofe">#cofe</a> with <span class="h-card"><a data-user="#{ ~s(I drink <a class="hashtag" data-tag="cofe" href="http://localhost:4001/tag/cofe">#cofe</a> with <span class="h-card"><a data-user="#{
user2.id user2.id
}" class="u-url mention" href="#{user2.ap_id}" rel="ugc">@<span>#{user2.nickname}</span></a></span>) }" class="u-url mention" href="#{user2.ap_id}" rel="ugc">@<span>#{user2.nickname}</span></a></span>)
end end
test "updates the user's locking status", %{conn: conn} do test "updates the user's locking status", %{conn: conn} do
user = insert(:user) conn = patch(conn, "/api/v1/accounts/update_credentials", %{locked: "true"})
conn = assert user_data = json_response(conn, 200)
conn assert user_data["locked"] == true
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{locked: "true"})
assert user = json_response(conn, 200)
assert user["locked"] == true
end end
test "updates the user's allow_following_move", %{conn: conn} do test "updates the user's allow_following_move", %{user: user, conn: conn} do
user = insert(:user)
assert user.allow_following_move == true assert user.allow_following_move == true
conn = conn = patch(conn, "/api/v1/accounts/update_credentials", %{allow_following_move: "false"})
conn
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{allow_following_move: "false"})
assert refresh_record(user).allow_following_move == false assert refresh_record(user).allow_following_move == false
assert user = json_response(conn, 200) assert user_data = json_response(conn, 200)
assert user["pleroma"]["allow_following_move"] == false assert user_data["pleroma"]["allow_following_move"] == false
end end
test "updates the user's default scope", %{conn: conn} do test "updates the user's default scope", %{conn: conn} do
user = insert(:user) conn = patch(conn, "/api/v1/accounts/update_credentials", %{default_scope: "cofe"})
conn = assert user_data = json_response(conn, 200)
conn assert user_data["source"]["privacy"] == "cofe"
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{default_scope: "cofe"})
assert user = json_response(conn, 200)
assert user["source"]["privacy"] == "cofe"
end end
test "updates the user's hide_followers status", %{conn: conn} do test "updates the user's hide_followers status", %{conn: conn} do
user = insert(:user) conn = patch(conn, "/api/v1/accounts/update_credentials", %{hide_followers: "true"})
conn = assert user_data = json_response(conn, 200)
conn assert user_data["pleroma"]["hide_followers"] == true
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{hide_followers: "true"})
assert user = json_response(conn, 200)
assert user["pleroma"]["hide_followers"] == true
end end
test "updates the user's hide_followers_count and hide_follows_count", %{conn: conn} do test "updates the user's hide_followers_count and hide_follows_count", %{conn: conn} do
user = insert(:user)
conn = conn =
conn patch(conn, "/api/v1/accounts/update_credentials", %{
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{
hide_followers_count: "true", hide_followers_count: "true",
hide_follows_count: "true" hide_follows_count: "true"
}) })
assert user = json_response(conn, 200) assert user_data = json_response(conn, 200)
assert user["pleroma"]["hide_followers_count"] == true assert user_data["pleroma"]["hide_followers_count"] == true
assert user["pleroma"]["hide_follows_count"] == true assert user_data["pleroma"]["hide_follows_count"] == true
end end
test "updates the user's skip_thread_containment option", %{conn: conn} do test "updates the user's skip_thread_containment option", %{user: user, conn: conn} do
user = insert(:user)
response = response =
conn conn
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{skip_thread_containment: "true"}) |> patch("/api/v1/accounts/update_credentials", %{skip_thread_containment: "true"})
|> json_response(200) |> json_response(200)
@ -172,104 +140,68 @@ test "updates the user's skip_thread_containment option", %{conn: conn} do
end end
test "updates the user's hide_follows status", %{conn: conn} do test "updates the user's hide_follows status", %{conn: conn} do
user = insert(:user) conn = patch(conn, "/api/v1/accounts/update_credentials", %{hide_follows: "true"})
conn = assert user_data = json_response(conn, 200)
conn assert user_data["pleroma"]["hide_follows"] == true
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{hide_follows: "true"})
assert user = json_response(conn, 200)
assert user["pleroma"]["hide_follows"] == true
end end
test "updates the user's hide_favorites status", %{conn: conn} do test "updates the user's hide_favorites status", %{conn: conn} do
user = insert(:user) conn = patch(conn, "/api/v1/accounts/update_credentials", %{hide_favorites: "true"})
conn = assert user_data = json_response(conn, 200)
conn assert user_data["pleroma"]["hide_favorites"] == true
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{hide_favorites: "true"})
assert user = json_response(conn, 200)
assert user["pleroma"]["hide_favorites"] == true
end end
test "updates the user's show_role status", %{conn: conn} do test "updates the user's show_role status", %{conn: conn} do
user = insert(:user) conn = patch(conn, "/api/v1/accounts/update_credentials", %{show_role: "false"})
conn = assert user_data = json_response(conn, 200)
conn assert user_data["source"]["pleroma"]["show_role"] == false
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{show_role: "false"})
assert user = json_response(conn, 200)
assert user["source"]["pleroma"]["show_role"] == false
end end
test "updates the user's no_rich_text status", %{conn: conn} do test "updates the user's no_rich_text status", %{conn: conn} do
user = insert(:user) conn = patch(conn, "/api/v1/accounts/update_credentials", %{no_rich_text: "true"})
conn = assert user_data = json_response(conn, 200)
conn assert user_data["source"]["pleroma"]["no_rich_text"] == true
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{no_rich_text: "true"})
assert user = json_response(conn, 200)
assert user["source"]["pleroma"]["no_rich_text"] == true
end end
test "updates the user's name", %{conn: conn} do test "updates the user's name", %{conn: conn} do
user = insert(:user)
conn = conn =
conn patch(conn, "/api/v1/accounts/update_credentials", %{"display_name" => "markorepairs"})
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{"display_name" => "markorepairs"})
assert user = json_response(conn, 200) assert user_data = json_response(conn, 200)
assert user["display_name"] == "markorepairs" assert user_data["display_name"] == "markorepairs"
end end
test "updates the user's avatar", %{conn: conn} do test "updates the user's avatar", %{user: user, conn: conn} do
user = insert(:user)
new_avatar = %Plug.Upload{ new_avatar = %Plug.Upload{
content_type: "image/jpg", content_type: "image/jpg",
path: Path.absname("test/fixtures/image.jpg"), path: Path.absname("test/fixtures/image.jpg"),
filename: "an_image.jpg" filename: "an_image.jpg"
} }
conn = conn = patch(conn, "/api/v1/accounts/update_credentials", %{"avatar" => new_avatar})
conn
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{"avatar" => new_avatar})
assert user_response = json_response(conn, 200) assert user_response = json_response(conn, 200)
assert user_response["avatar"] != User.avatar_url(user) assert user_response["avatar"] != User.avatar_url(user)
end end
test "updates the user's banner", %{conn: conn} do test "updates the user's banner", %{user: user, conn: conn} do
user = insert(:user)
new_header = %Plug.Upload{ new_header = %Plug.Upload{
content_type: "image/jpg", content_type: "image/jpg",
path: Path.absname("test/fixtures/image.jpg"), path: Path.absname("test/fixtures/image.jpg"),
filename: "an_image.jpg" filename: "an_image.jpg"
} }
conn = conn = patch(conn, "/api/v1/accounts/update_credentials", %{"header" => new_header})
conn
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{"header" => new_header})
assert user_response = json_response(conn, 200) assert user_response = json_response(conn, 200)
assert user_response["header"] != User.banner_url(user) assert user_response["header"] != User.banner_url(user)
end end
test "updates the user's background", %{conn: conn} do test "updates the user's background", %{conn: conn} do
user = insert(:user)
new_header = %Plug.Upload{ new_header = %Plug.Upload{
content_type: "image/jpg", content_type: "image/jpg",
path: Path.absname("test/fixtures/image.jpg"), path: Path.absname("test/fixtures/image.jpg"),
@ -277,9 +209,7 @@ test "updates the user's background", %{conn: conn} do
} }
conn = conn =
conn patch(conn, "/api/v1/accounts/update_credentials", %{
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{
"pleroma_background_image" => new_header "pleroma_background_image" => new_header
}) })
@ -287,13 +217,13 @@ test "updates the user's background", %{conn: conn} do
assert user_response["pleroma"]["background_image"] assert user_response["pleroma"]["background_image"]
end end
test "requires 'write:accounts' permission", %{conn: conn} do test "requires 'write:accounts' permission" do
token1 = insert(:oauth_token, scopes: ["read"]) token1 = insert(:oauth_token, scopes: ["read"])
token2 = insert(:oauth_token, scopes: ["write", "follow"]) token2 = insert(:oauth_token, scopes: ["write", "follow"])
for token <- [token1, token2] do for token <- [token1, token2] do
conn = conn =
conn build_conn()
|> put_req_header("authorization", "Bearer #{token.token}") |> put_req_header("authorization", "Bearer #{token.token}")
|> patch("/api/v1/accounts/update_credentials", %{}) |> patch("/api/v1/accounts/update_credentials", %{})
@ -306,53 +236,44 @@ test "requires 'write:accounts' permission", %{conn: conn} do
end end
end end
test "updates profile emojos", %{conn: conn} do test "updates profile emojos", %{user: user, conn: conn} do
user = insert(:user)
note = "*sips :blank:*" note = "*sips :blank:*"
name = "I am :firefox:" name = "I am :firefox:"
conn = ret_conn =
conn patch(conn, "/api/v1/accounts/update_credentials", %{
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{
"note" => note, "note" => note,
"display_name" => name "display_name" => name
}) })
assert json_response(conn, 200) assert json_response(ret_conn, 200)
conn = conn = get(conn, "/api/v1/accounts/#{user.id}")
conn
|> get("/api/v1/accounts/#{user.id}")
assert user = json_response(conn, 200) assert user_data = json_response(conn, 200)
assert user["note"] == note assert user_data["note"] == note
assert user["display_name"] == name assert user_data["display_name"] == name
assert [%{"shortcode" => "blank"}, %{"shortcode" => "firefox"}] = user["emojis"] assert [%{"shortcode" => "blank"}, %{"shortcode" => "firefox"}] = user_data["emojis"]
end end
test "update fields", %{conn: conn} do test "update fields", %{conn: conn} do
user = insert(:user)
fields = [ fields = [
%{"name" => "<a href=\"http://google.com\">foo</a>", "value" => "<script>bar</script>"}, %{"name" => "<a href=\"http://google.com\">foo</a>", "value" => "<script>bar</script>"},
%{"name" => "link", "value" => "cofe.io"} %{"name" => "link", "value" => "cofe.io"}
] ]
account = account_data =
conn conn
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields}) |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
|> json_response(200) |> json_response(200)
assert account["fields"] == [ assert account_data["fields"] == [
%{"name" => "foo", "value" => "bar"}, %{"name" => "foo", "value" => "bar"},
%{"name" => "link", "value" => ~S(<a href="http://cofe.io" rel="ugc">cofe.io</a>)} %{"name" => "link", "value" => ~S(<a href="http://cofe.io" rel="ugc">cofe.io</a>)}
] ]
assert account["source"]["fields"] == [ assert account_data["source"]["fields"] == [
%{ %{
"name" => "<a href=\"http://google.com\">foo</a>", "name" => "<a href=\"http://google.com\">foo</a>",
"value" => "<script>bar</script>" "value" => "<script>bar</script>"
@ -372,7 +293,6 @@ test "update fields", %{conn: conn} do
account = account =
conn conn
|> put_req_header("content-type", "application/x-www-form-urlencoded") |> put_req_header("content-type", "application/x-www-form-urlencoded")
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", fields) |> patch("/api/v1/accounts/update_credentials", fields)
|> json_response(200) |> json_response(200)
@ -398,7 +318,6 @@ test "update fields", %{conn: conn} do
assert %{"error" => "Invalid request"} == assert %{"error" => "Invalid request"} ==
conn conn
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields}) |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
|> json_response(403) |> json_response(403)
@ -408,7 +327,6 @@ test "update fields", %{conn: conn} do
assert %{"error" => "Invalid request"} == assert %{"error" => "Invalid request"} ==
conn conn
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields}) |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
|> json_response(403) |> json_response(403)
@ -421,7 +339,6 @@ test "update fields", %{conn: conn} do
assert %{"error" => "Invalid request"} == assert %{"error" => "Invalid request"} ==
conn conn
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields}) |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
|> json_response(403) |> json_response(403)
@ -432,7 +349,6 @@ test "update fields", %{conn: conn} do
account = account =
conn conn
|> assign(:user, user)
|> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields}) |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})
|> json_response(200) |> json_response(200)

View file

@ -87,6 +87,7 @@ test "respects limit_to_local_content == :unauthenticated for remote user nickna
conn = conn =
build_conn() build_conn()
|> assign(:user, reading_user) |> assign(:user, reading_user)
|> assign(:token, insert(:oauth_token, user: reading_user, scopes: ["read:accounts"]))
|> get("/api/v1/accounts/#{user.nickname}") |> get("/api/v1/accounts/#{user.nickname}")
Pleroma.Config.put([:instance, :limit_to_local_content], limit_to_local) Pleroma.Config.put([:instance, :limit_to_local_content], limit_to_local)
@ -144,8 +145,9 @@ test "returns 404 for internal.fetch actor", %{conn: conn} do
end end
describe "user timelines" do describe "user timelines" do
test "respects blocks", %{conn: conn} do setup do: oauth_access(["read:statuses"])
user_one = insert(:user)
test "respects blocks", %{user: user_one, conn: conn} do
user_two = insert(:user) user_two = insert(:user)
user_three = insert(:user) user_three = insert(:user)
@ -154,46 +156,35 @@ test "respects blocks", %{conn: conn} do
{: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) {:ok, repeat, _} = CommonAPI.repeat(activity.id, user_three)
resp = resp = get(conn, "/api/v1/accounts/#{user_two.id}/statuses")
conn
|> get("/api/v1/accounts/#{user_two.id}/statuses")
assert [%{"id" => id}] = json_response(resp, 200) assert [%{"id" => id}] = json_response(resp, 200)
assert id == activity.id assert id == activity.id
# Even a blocked user will deliver the full user timeline, there would be # Even a blocked user will deliver the full user timeline, there would be
# no point in looking at a blocked users timeline otherwise # no point in looking at a blocked users timeline otherwise
resp = resp = get(conn, "/api/v1/accounts/#{user_two.id}/statuses")
conn
|> assign(:user, user_one)
|> get("/api/v1/accounts/#{user_two.id}/statuses")
assert [%{"id" => id}] = json_response(resp, 200) assert [%{"id" => id}] = json_response(resp, 200)
assert id == activity.id assert id == activity.id
resp = # Third user's timeline includes the repeat when viewed by unauthenticated user
conn resp = get(build_conn(), "/api/v1/accounts/#{user_three.id}/statuses")
|> get("/api/v1/accounts/#{user_three.id}/statuses")
assert [%{"id" => id}] = json_response(resp, 200) assert [%{"id" => id}] = json_response(resp, 200)
assert id == repeat.id assert id == repeat.id
# When viewing a third user's timeline, the blocked users will NOT be # When viewing a third user's timeline, the blocked users' statuses will NOT be shown
# shown. resp = get(conn, "/api/v1/accounts/#{user_three.id}/statuses")
resp =
conn
|> assign(:user, user_one)
|> get("/api/v1/accounts/#{user_three.id}/statuses")
assert [] = json_response(resp, 200) assert [] = json_response(resp, 200)
end end
test "gets a users statuses", %{conn: conn} do test "gets users statuses", %{conn: conn} do
user_one = insert(:user) user_one = insert(:user)
user_two = insert(:user) user_two = insert(:user)
user_three = insert(:user) user_three = insert(:user)
{:ok, user_three} = User.follow(user_three, user_one) {:ok, _user_three} = User.follow(user_three, user_one)
{:ok, activity} = CommonAPI.post(user_one, %{"status" => "HI!!!"}) {:ok, activity} = CommonAPI.post(user_one, %{"status" => "HI!!!"})
@ -206,9 +197,7 @@ test "gets a users statuses", %{conn: conn} do
{:ok, private_activity} = {:ok, private_activity} =
CommonAPI.post(user_one, %{"status" => "private", "visibility" => "private"}) CommonAPI.post(user_one, %{"status" => "private", "visibility" => "private"})
resp = resp = get(conn, "/api/v1/accounts/#{user_one.id}/statuses")
conn
|> get("/api/v1/accounts/#{user_one.id}/statuses")
assert [%{"id" => id}] = json_response(resp, 200) assert [%{"id" => id}] = json_response(resp, 200)
assert id == to_string(activity.id) assert id == to_string(activity.id)
@ -216,6 +205,7 @@ test "gets a users statuses", %{conn: conn} do
resp = resp =
conn conn
|> assign(:user, user_two) |> assign(:user, user_two)
|> assign(:token, insert(:oauth_token, user: user_two, scopes: ["read:statuses"]))
|> get("/api/v1/accounts/#{user_one.id}/statuses") |> get("/api/v1/accounts/#{user_one.id}/statuses")
assert [%{"id" => id_one}, %{"id" => id_two}] = json_response(resp, 200) assert [%{"id" => id_one}, %{"id" => id_two}] = json_response(resp, 200)
@ -225,6 +215,7 @@ test "gets a users statuses", %{conn: conn} do
resp = resp =
conn conn
|> assign(:user, user_three) |> assign(:user, user_three)
|> assign(:token, insert(:oauth_token, user: user_three, scopes: ["read:statuses"]))
|> get("/api/v1/accounts/#{user_one.id}/statuses") |> get("/api/v1/accounts/#{user_one.id}/statuses")
assert [%{"id" => id_one}, %{"id" => id_two}] = json_response(resp, 200) assert [%{"id" => id_one}, %{"id" => id_two}] = json_response(resp, 200)
@ -236,9 +227,7 @@ test "unimplemented pinned statuses feature", %{conn: conn} do
note = insert(:note_activity) note = insert(:note_activity)
user = User.get_cached_by_ap_id(note.data["actor"]) user = User.get_cached_by_ap_id(note.data["actor"])
conn = conn = get(conn, "/api/v1/accounts/#{user.id}/statuses?pinned=true")
conn
|> get("/api/v1/accounts/#{user.id}/statuses?pinned=true")
assert json_response(conn, 200) == [] assert json_response(conn, 200) == []
end end
@ -257,63 +246,51 @@ test "gets an users media", %{conn: conn} do
{:ok, image_post} = CommonAPI.post(user, %{"status" => "cofe", "media_ids" => [media_id]}) {:ok, image_post} = CommonAPI.post(user, %{"status" => "cofe", "media_ids" => [media_id]})
conn = conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"only_media" => "true"})
conn
|> get("/api/v1/accounts/#{user.id}/statuses", %{"only_media" => "true"})
assert [%{"id" => id}] = json_response(conn, 200) assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(image_post.id) assert id == to_string(image_post.id)
conn = conn = get(build_conn(), "/api/v1/accounts/#{user.id}/statuses", %{"only_media" => "1"})
build_conn()
|> get("/api/v1/accounts/#{user.id}/statuses", %{"only_media" => "1"})
assert [%{"id" => id}] = json_response(conn, 200) assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(image_post.id) assert id == to_string(image_post.id)
end end
test "gets a user's statuses without reblogs", %{conn: conn} do test "gets a user's statuses without reblogs", %{user: user, conn: conn} do
user = insert(:user)
{:ok, post} = CommonAPI.post(user, %{"status" => "HI!!!"}) {:ok, post} = CommonAPI.post(user, %{"status" => "HI!!!"})
{:ok, _, _} = CommonAPI.repeat(post.id, user) {:ok, _, _} = CommonAPI.repeat(post.id, user)
conn = conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"exclude_reblogs" => "true"})
conn
|> get("/api/v1/accounts/#{user.id}/statuses", %{"exclude_reblogs" => "true"})
assert [%{"id" => id}] = json_response(conn, 200) assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(post.id) assert id == to_string(post.id)
conn = conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"exclude_reblogs" => "1"})
conn
|> get("/api/v1/accounts/#{user.id}/statuses", %{"exclude_reblogs" => "1"})
assert [%{"id" => id}] = json_response(conn, 200) assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(post.id) assert id == to_string(post.id)
end end
test "filters user's statuses by a hashtag", %{conn: conn} do test "filters user's statuses by a hashtag", %{user: user, conn: conn} do
user = insert(:user)
{:ok, post} = CommonAPI.post(user, %{"status" => "#hashtag"}) {:ok, post} = CommonAPI.post(user, %{"status" => "#hashtag"})
{:ok, _post} = CommonAPI.post(user, %{"status" => "hashtag"}) {:ok, _post} = CommonAPI.post(user, %{"status" => "hashtag"})
conn = conn = get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"tagged" => "hashtag"})
conn
|> get("/api/v1/accounts/#{user.id}/statuses", %{"tagged" => "hashtag"})
assert [%{"id" => id}] = json_response(conn, 200) assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(post.id) assert id == to_string(post.id)
end end
test "the user views their own timelines and excludes direct messages", %{conn: conn} do test "the user views their own timelines and excludes direct messages", %{
user = insert(:user) user: user,
conn: conn
} do
{: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"})
conn = conn =
conn get(conn, "/api/v1/accounts/#{user.id}/statuses", %{"exclude_visibilities" => ["direct"]})
|> assign(:user, user)
|> get("/api/v1/accounts/#{user.id}/statuses", %{"exclude_visibilities" => ["direct"]})
assert [%{"id" => id}] = json_response(conn, 200) assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(public_activity.id) assert id == to_string(public_activity.id)
@ -321,46 +298,42 @@ test "the user views their own timelines and excludes direct messages", %{conn:
end end
describe "followers" do describe "followers" do
test "getting followers", %{conn: conn} do setup do: oauth_access(["read:accounts"])
user = insert(:user)
test "getting followers", %{user: user, conn: conn} do
other_user = insert(:user) other_user = insert(:user)
{:ok, user} = User.follow(user, other_user) {:ok, user} = User.follow(user, other_user)
conn = conn = get(conn, "/api/v1/accounts/#{other_user.id}/followers")
conn
|> get("/api/v1/accounts/#{other_user.id}/followers")
assert [%{"id" => id}] = json_response(conn, 200) assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(user.id) assert id == to_string(user.id)
end end
test "getting followers, hide_followers", %{conn: conn} do test "getting followers, hide_followers", %{user: user, conn: conn} do
user = insert(:user)
other_user = insert(:user, hide_followers: true) other_user = insert(:user, hide_followers: true)
{:ok, _user} = User.follow(user, other_user) {:ok, _user} = User.follow(user, other_user)
conn = conn = get(conn, "/api/v1/accounts/#{other_user.id}/followers")
conn
|> get("/api/v1/accounts/#{other_user.id}/followers")
assert [] == json_response(conn, 200) assert [] == json_response(conn, 200)
end end
test "getting followers, hide_followers, same user requesting", %{conn: conn} do test "getting followers, hide_followers, same user requesting" do
user = insert(:user) user = insert(:user)
other_user = insert(:user, hide_followers: true) other_user = insert(:user, hide_followers: true)
{:ok, _user} = User.follow(user, other_user) {:ok, _user} = User.follow(user, other_user)
conn = conn =
conn build_conn()
|> assign(:user, other_user) |> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"]))
|> get("/api/v1/accounts/#{other_user.id}/followers") |> get("/api/v1/accounts/#{other_user.id}/followers")
refute [] == json_response(conn, 200) refute [] == json_response(conn, 200)
end end
test "getting followers, pagination", %{conn: conn} do test "getting followers, pagination", %{user: user, conn: conn} do
user = insert(:user)
follower1 = insert(:user) follower1 = insert(:user)
follower2 = insert(:user) follower2 = insert(:user)
follower3 = insert(:user) follower3 = insert(:user)
@ -368,29 +341,19 @@ test "getting followers, pagination", %{conn: conn} do
{:ok, _} = User.follow(follower2, user) {:ok, _} = User.follow(follower2, user)
{:ok, _} = User.follow(follower3, user) {:ok, _} = User.follow(follower3, user)
conn = res_conn = get(conn, "/api/v1/accounts/#{user.id}/followers?since_id=#{follower1.id}")
conn
|> assign(:user, user)
res_conn =
conn
|> get("/api/v1/accounts/#{user.id}/followers?since_id=#{follower1.id}")
assert [%{"id" => id3}, %{"id" => id2}] = json_response(res_conn, 200) assert [%{"id" => id3}, %{"id" => id2}] = json_response(res_conn, 200)
assert id3 == follower3.id assert id3 == follower3.id
assert id2 == follower2.id assert id2 == follower2.id
res_conn = res_conn = get(conn, "/api/v1/accounts/#{user.id}/followers?max_id=#{follower3.id}")
conn
|> get("/api/v1/accounts/#{user.id}/followers?max_id=#{follower3.id}")
assert [%{"id" => id2}, %{"id" => id1}] = json_response(res_conn, 200) assert [%{"id" => id2}, %{"id" => id1}] = json_response(res_conn, 200)
assert id2 == follower2.id assert id2 == follower2.id
assert id1 == follower1.id assert id1 == follower1.id
res_conn = res_conn = get(conn, "/api/v1/accounts/#{user.id}/followers?limit=1&max_id=#{follower3.id}")
conn
|> get("/api/v1/accounts/#{user.id}/followers?limit=1&max_id=#{follower3.id}")
assert [%{"id" => id2}] = json_response(res_conn, 200) assert [%{"id" => id2}] = json_response(res_conn, 200)
assert id2 == follower2.id assert id2 == follower2.id
@ -402,46 +365,47 @@ test "getting followers, pagination", %{conn: conn} do
end end
describe "following" do describe "following" do
test "getting following", %{conn: conn} do setup do: oauth_access(["read:accounts"])
user = insert(:user)
test "getting following", %{user: user, conn: conn} do
other_user = insert(:user) other_user = insert(:user)
{:ok, user} = User.follow(user, other_user) {:ok, user} = User.follow(user, other_user)
conn = conn = get(conn, "/api/v1/accounts/#{user.id}/following")
conn
|> get("/api/v1/accounts/#{user.id}/following")
assert [%{"id" => id}] = json_response(conn, 200) assert [%{"id" => id}] = json_response(conn, 200)
assert id == to_string(other_user.id) assert id == to_string(other_user.id)
end end
test "getting following, hide_follows", %{conn: conn} do test "getting following, hide_follows, other user requesting" do
user = insert(:user, hide_follows: true) user = insert(:user, hide_follows: true)
other_user = insert(:user) other_user = insert(:user)
{:ok, user} = User.follow(user, other_user) {:ok, user} = User.follow(user, other_user)
conn = conn =
conn build_conn()
|> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"]))
|> get("/api/v1/accounts/#{user.id}/following") |> get("/api/v1/accounts/#{user.id}/following")
assert [] == json_response(conn, 200) assert [] == json_response(conn, 200)
end end
test "getting following, hide_follows, same user requesting", %{conn: conn} do test "getting following, hide_follows, same user requesting" do
user = insert(:user, hide_follows: true) user = insert(:user, hide_follows: true)
other_user = insert(:user) other_user = insert(:user)
{:ok, user} = User.follow(user, other_user) {:ok, user} = User.follow(user, other_user)
conn = conn =
conn build_conn()
|> assign(:user, user) |> assign(:user, user)
|> assign(:token, insert(:oauth_token, user: user, scopes: ["read:accounts"]))
|> get("/api/v1/accounts/#{user.id}/following") |> get("/api/v1/accounts/#{user.id}/following")
refute [] == json_response(conn, 200) refute [] == json_response(conn, 200)
end end
test "getting following, pagination", %{conn: conn} do test "getting following, pagination", %{user: user, conn: conn} do
user = insert(:user)
following1 = insert(:user) following1 = insert(:user)
following2 = insert(:user) following2 = insert(:user)
following3 = insert(:user) following3 = insert(:user)
@ -449,29 +413,20 @@ test "getting following, pagination", %{conn: conn} do
{:ok, _} = User.follow(user, following2) {:ok, _} = User.follow(user, following2)
{:ok, _} = User.follow(user, following3) {:ok, _} = User.follow(user, following3)
conn = res_conn = get(conn, "/api/v1/accounts/#{user.id}/following?since_id=#{following1.id}")
conn
|> assign(:user, user)
res_conn =
conn
|> get("/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(res_conn, 200)
assert id3 == following3.id assert id3 == following3.id
assert id2 == following2.id assert id2 == following2.id
res_conn = res_conn = get(conn, "/api/v1/accounts/#{user.id}/following?max_id=#{following3.id}")
conn
|> get("/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(res_conn, 200)
assert id2 == following2.id assert id2 == following2.id
assert id1 == following1.id assert id1 == following1.id
res_conn = res_conn =
conn get(conn, "/api/v1/accounts/#{user.id}/following?limit=1&max_id=#{following3.id}")
|> get("/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(res_conn, 200)
assert id2 == following2.id assert id2 == following2.id
@ -483,82 +438,52 @@ test "getting following, pagination", %{conn: conn} do
end end
describe "follow/unfollow" do describe "follow/unfollow" do
setup do: oauth_access(["follow"])
test "following / unfollowing a user", %{conn: conn} do test "following / unfollowing a user", %{conn: conn} do
user = insert(:user)
other_user = insert(:user) other_user = insert(:user)
conn = ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/follow")
conn
|> assign(:user, user)
|> post("/api/v1/accounts/#{other_user.id}/follow")
assert %{"id" => _id, "following" => true} = json_response(conn, 200) assert %{"id" => _id, "following" => true} = json_response(ret_conn, 200)
user = User.get_cached_by_id(user.id) ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/unfollow")
conn = assert %{"id" => _id, "following" => false} = json_response(ret_conn, 200)
build_conn()
|> assign(:user, user)
|> post("/api/v1/accounts/#{other_user.id}/unfollow")
assert %{"id" => _id, "following" => false} = json_response(conn, 200) conn = post(conn, "/api/v1/follows", %{"uri" => other_user.nickname})
user = User.get_cached_by_id(user.id)
conn =
build_conn()
|> assign(:user, user)
|> post("/api/v1/follows", %{"uri" => other_user.nickname})
assert %{"id" => id} = json_response(conn, 200) assert %{"id" => id} = json_response(conn, 200)
assert id == to_string(other_user.id) assert id == to_string(other_user.id)
end end
test "following without reblogs" do test "following without reblogs" do
follower = insert(:user) %{conn: conn} = oauth_access(["follow", "read:statuses"])
followed = insert(:user) followed = insert(:user)
other_user = insert(:user) other_user = insert(:user)
conn = ret_conn = post(conn, "/api/v1/accounts/#{followed.id}/follow?reblogs=false")
build_conn()
|> assign(:user, follower)
|> post("/api/v1/accounts/#{followed.id}/follow?reblogs=false")
assert %{"showing_reblogs" => false} = json_response(conn, 200) assert %{"showing_reblogs" => false} = json_response(ret_conn, 200)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "hey"}) {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hey"})
{:ok, reblog, _} = CommonAPI.repeat(activity.id, followed) {:ok, reblog, _} = CommonAPI.repeat(activity.id, followed)
conn = ret_conn = get(conn, "/api/v1/timelines/home")
build_conn()
|> assign(:user, User.get_cached_by_id(follower.id))
|> get("/api/v1/timelines/home")
assert [] == json_response(conn, 200) assert [] == json_response(ret_conn, 200)
conn = ret_conn = post(conn, "/api/v1/accounts/#{followed.id}/follow?reblogs=true")
build_conn()
|> assign(:user, User.get_cached_by_id(follower.id))
|> post("/api/v1/accounts/#{followed.id}/follow?reblogs=true")
assert %{"showing_reblogs" => true} = json_response(conn, 200) assert %{"showing_reblogs" => true} = json_response(ret_conn, 200)
conn = conn = get(conn, "/api/v1/timelines/home")
build_conn()
|> assign(:user, User.get_cached_by_id(follower.id))
|> get("/api/v1/timelines/home")
expected_activity_id = reblog.id expected_activity_id = reblog.id
assert [%{"id" => ^expected_activity_id}] = json_response(conn, 200) assert [%{"id" => ^expected_activity_id}] = json_response(conn, 200)
end end
test "following / unfollowing errors" do test "following / unfollowing errors", %{user: user, conn: conn} do
user = insert(:user)
conn =
build_conn()
|> assign(:user, user)
# self follow # self follow
conn_res = post(conn, "/api/v1/accounts/#{user.id}/follow") conn_res = post(conn, "/api/v1/accounts/#{user.id}/follow")
assert %{"error" => "Record not found"} = json_response(conn_res, 404) assert %{"error" => "Record not found"} = json_response(conn_res, 404)
@ -588,47 +513,34 @@ test "following / unfollowing errors" do
end end
describe "mute/unmute" do describe "mute/unmute" do
setup do: oauth_access(["write:mutes"])
test "with notifications", %{conn: conn} do test "with notifications", %{conn: conn} do
user = insert(:user)
other_user = insert(:user) other_user = insert(:user)
conn = ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/mute")
conn
|> assign(:user, user)
|> post("/api/v1/accounts/#{other_user.id}/mute")
response = json_response(conn, 200) response = json_response(ret_conn, 200)
assert %{"id" => _id, "muting" => true, "muting_notifications" => true} = response assert %{"id" => _id, "muting" => true, "muting_notifications" => true} = response
user = User.get_cached_by_id(user.id)
conn = conn = post(conn, "/api/v1/accounts/#{other_user.id}/unmute")
build_conn()
|> assign(:user, user)
|> post("/api/v1/accounts/#{other_user.id}/unmute")
response = json_response(conn, 200) response = json_response(conn, 200)
assert %{"id" => _id, "muting" => false, "muting_notifications" => false} = response assert %{"id" => _id, "muting" => false, "muting_notifications" => false} = response
end end
test "without notifications", %{conn: conn} do test "without notifications", %{conn: conn} do
user = insert(:user)
other_user = insert(:user) other_user = insert(:user)
conn = ret_conn =
conn post(conn, "/api/v1/accounts/#{other_user.id}/mute", %{"notifications" => "false"})
|> assign(:user, user)
|> post("/api/v1/accounts/#{other_user.id}/mute", %{"notifications" => "false"})
response = json_response(conn, 200) response = json_response(ret_conn, 200)
assert %{"id" => _id, "muting" => true, "muting_notifications" => false} = response assert %{"id" => _id, "muting" => true, "muting_notifications" => false} = response
user = User.get_cached_by_id(user.id)
conn = conn = post(conn, "/api/v1/accounts/#{other_user.id}/unmute")
build_conn()
|> assign(:user, user)
|> post("/api/v1/accounts/#{other_user.id}/unmute")
response = json_response(conn, 200) response = json_response(conn, 200)
assert %{"id" => _id, "muting" => false, "muting_notifications" => false} = response assert %{"id" => _id, "muting" => false, "muting_notifications" => false} = response
@ -639,8 +551,9 @@ test "without notifications", %{conn: conn} do
setup do setup do
user = insert(:user) 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)
[user: user, activity: activity] [conn: conn, user: user, activity: activity]
end end
test "returns pinned statuses", %{conn: conn, user: user, activity: activity} do test "returns pinned statuses", %{conn: conn, user: user, activity: activity} do
@ -648,7 +561,6 @@ test "returns pinned statuses", %{conn: conn, user: user, activity: activity} do
result = result =
conn conn
|> assign(:user, user)
|> get("/api/v1/accounts/#{user.id}/statuses?pinned=true") |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true")
|> json_response(200) |> json_response(200)
@ -658,23 +570,15 @@ test "returns pinned statuses", %{conn: conn, user: user, activity: activity} do
end end
end end
test "blocking / unblocking a user", %{conn: conn} do test "blocking / unblocking a user" do
user = insert(:user) %{conn: conn} = oauth_access(["follow"])
other_user = insert(:user) other_user = insert(:user)
conn = ret_conn = post(conn, "/api/v1/accounts/#{other_user.id}/block")
conn
|> assign(:user, user)
|> post("/api/v1/accounts/#{other_user.id}/block")
assert %{"id" => _id, "blocking" => true} = json_response(conn, 200) assert %{"id" => _id, "blocking" => true} = json_response(ret_conn, 200)
user = User.get_cached_by_id(user.id) conn = post(conn, "/api/v1/accounts/#{other_user.id}/unblock")
conn =
build_conn()
|> assign(:user, user)
|> post("/api/v1/accounts/#{other_user.id}/unblock")
assert %{"id" => _id, "blocking" => false} = json_response(conn, 200) assert %{"id" => _id, "blocking" => false} = json_response(conn, 200)
end end
@ -693,8 +597,7 @@ test "blocking / unblocking a user", %{conn: conn} do
test "Account registration via Application", %{conn: conn} do test "Account registration via Application", %{conn: conn} do
conn = conn =
conn post(conn, "/api/v1/apps", %{
|> post("/api/v1/apps", %{
client_name: "client_name", client_name: "client_name",
redirect_uris: "urn:ietf:wg:oauth:2.0:oob", redirect_uris: "urn:ietf:wg:oauth:2.0:oob",
scopes: "read, write, follow" scopes: "read, write, follow"
@ -711,8 +614,7 @@ test "Account registration via Application", %{conn: conn} do
} = json_response(conn, 200) } = json_response(conn, 200)
conn = conn =
conn post(conn, "/oauth/token", %{
|> post("/oauth/token", %{
grant_type: "client_credentials", grant_type: "client_credentials",
client_id: client_id, client_id: client_id,
client_secret: client_secret client_secret: client_secret
@ -769,13 +671,13 @@ test "rate limit", %{conn: conn} do
app_token = insert(:oauth_token, user: nil) app_token = insert(:oauth_token, user: nil)
conn = conn =
put_req_header(conn, "authorization", "Bearer " <> app_token.token) conn
|> put_req_header("authorization", "Bearer " <> app_token.token)
|> Map.put(:remote_ip, {15, 15, 15, 15}) |> Map.put(:remote_ip, {15, 15, 15, 15})
for i <- 1..5 do for i <- 1..5 do
conn = conn =
conn post(conn, "/api/v1/accounts", %{
|> post("/api/v1/accounts", %{
username: "#{i}lain", username: "#{i}lain",
email: "#{i}lain@example.org", email: "#{i}lain@example.org",
password: "PlzDontHackLain", password: "PlzDontHackLain",
@ -798,8 +700,7 @@ test "rate limit", %{conn: conn} do
end end
conn = conn =
conn post(conn, "/api/v1/accounts", %{
|> post("/api/v1/accounts", %{
username: "6lain", username: "6lain",
email: "6lain@example.org", email: "6lain@example.org",
password: "PlzDontHackLain", password: "PlzDontHackLain",
@ -815,9 +716,7 @@ test "returns bad_request if missing required params", %{
} do } do
app_token = insert(:oauth_token, user: nil) app_token = insert(:oauth_token, user: nil)
conn = conn = put_req_header(conn, "authorization", "Bearer " <> app_token.token)
conn
|> put_req_header("authorization", "Bearer " <> app_token.token)
res = post(conn, "/api/v1/accounts", valid_params) res = post(conn, "/api/v1/accounts", valid_params)
assert json_response(res, 200) assert json_response(res, 200)
@ -836,9 +735,7 @@ test "returns bad_request if missing required params", %{
end end
test "returns forbidden if token is invalid", %{conn: conn, valid_params: valid_params} do test "returns forbidden if token is invalid", %{conn: conn, valid_params: valid_params} do
conn = conn = put_req_header(conn, "authorization", "Bearer " <> "invalid-token")
conn
|> put_req_header("authorization", "Bearer " <> "invalid-token")
res = post(conn, "/api/v1/accounts", valid_params) res = post(conn, "/api/v1/accounts", valid_params)
assert json_response(res, 403) == %{"error" => "Invalid credentials"} assert json_response(res, 403) == %{"error" => "Invalid credentials"}
@ -846,15 +743,14 @@ test "returns forbidden if token is invalid", %{conn: conn, valid_params: valid_
end end
describe "GET /api/v1/accounts/:id/lists - account_lists" do describe "GET /api/v1/accounts/:id/lists - account_lists" do
test "returns lists to which the account belongs", %{conn: conn} do test "returns lists to which the account belongs" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:lists"])
other_user = insert(:user) other_user = insert(:user)
assert {:ok, %Pleroma.List{} = list} = Pleroma.List.create("Test List", user) assert {:ok, %Pleroma.List{} = list} = Pleroma.List.create("Test List", user)
{:ok, %{following: _following}} = Pleroma.List.follow(list, other_user) {:ok, %{following: _following}} = Pleroma.List.follow(list, other_user)
res = res =
conn conn
|> assign(:user, user)
|> get("/api/v1/accounts/#{other_user.id}/lists") |> get("/api/v1/accounts/#{other_user.id}/lists")
|> json_response(200) |> json_response(200)
@ -863,13 +759,9 @@ test "returns lists to which the account belongs", %{conn: conn} do
end end
describe "verify_credentials" do describe "verify_credentials" do
test "verify_credentials", %{conn: conn} do test "verify_credentials" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:accounts"])
conn = get(conn, "/api/v1/accounts/verify_credentials")
conn =
conn
|> assign(:user, user)
|> get("/api/v1/accounts/verify_credentials")
response = json_response(conn, 200) response = json_response(conn, 200)
@ -878,25 +770,21 @@ test "verify_credentials", %{conn: conn} do
assert id == to_string(user.id) assert id == to_string(user.id)
end end
test "verify_credentials default scope unlisted", %{conn: conn} do test "verify_credentials default scope unlisted" do
user = insert(:user, default_scope: "unlisted") user = insert(:user, default_scope: "unlisted")
%{conn: conn} = oauth_access(["read:accounts"], user: user)
conn = conn = get(conn, "/api/v1/accounts/verify_credentials")
conn
|> assign(:user, user)
|> get("/api/v1/accounts/verify_credentials")
assert %{"id" => id, "source" => %{"privacy" => "unlisted"}} = json_response(conn, 200) assert %{"id" => id, "source" => %{"privacy" => "unlisted"}} = json_response(conn, 200)
assert id == to_string(user.id) assert id == to_string(user.id)
end end
test "locked accounts", %{conn: conn} do test "locked accounts" do
user = insert(:user, default_scope: "private") user = insert(:user, default_scope: "private")
%{conn: conn} = oauth_access(["read:accounts"], user: user)
conn = conn = get(conn, "/api/v1/accounts/verify_credentials")
conn
|> assign(:user, user)
|> get("/api/v1/accounts/verify_credentials")
assert %{"id" => id, "source" => %{"privacy" => "private"}} = json_response(conn, 200) assert %{"id" => id, "source" => %{"privacy" => "private"}} = json_response(conn, 200)
assert id == to_string(user.id) assert id == to_string(user.id)
@ -904,15 +792,13 @@ test "locked accounts", %{conn: conn} do
end end
describe "user relationships" do describe "user relationships" do
test "returns the relationships for the current user", %{conn: conn} do setup do: oauth_access(["read:follows"])
user = insert(:user)
other_user = insert(:user)
{:ok, user} = User.follow(user, other_user)
conn = test "returns the relationships for the current user", %{user: user, conn: conn} do
conn other_user = insert(:user)
|> assign(:user, user) {:ok, _user} = User.follow(user, other_user)
|> get("/api/v1/accounts/relationships", %{"id" => [other_user.id]})
conn = get(conn, "/api/v1/accounts/relationships", %{"id" => [other_user.id]})
assert [relationship] = json_response(conn, 200) assert [relationship] = json_response(conn, 200)
@ -920,34 +806,26 @@ test "returns the relationships for the current user", %{conn: conn} do
end end
test "returns an empty list on a bad request", %{conn: conn} do test "returns an empty list on a bad request", %{conn: conn} do
user = insert(:user) conn = get(conn, "/api/v1/accounts/relationships", %{})
conn =
conn
|> assign(:user, user)
|> get("/api/v1/accounts/relationships", %{})
assert [] = json_response(conn, 200) assert [] = json_response(conn, 200)
end end
end end
test "getting a list of mutes", %{conn: conn} do test "getting a list of mutes" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:mutes"])
other_user = insert(:user) other_user = insert(:user)
{:ok, _user_relationships} = User.mute(user, other_user) {:ok, _user_relationships} = User.mute(user, other_user)
conn = conn = get(conn, "/api/v1/mutes")
conn
|> assign(:user, user)
|> get("/api/v1/mutes")
other_user_id = to_string(other_user.id) other_user_id = to_string(other_user.id)
assert [%{"id" => ^other_user_id}] = json_response(conn, 200) assert [%{"id" => ^other_user_id}] = json_response(conn, 200)
end end
test "getting a list of blocks", %{conn: conn} do test "getting a list of blocks" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:blocks"])
other_user = insert(:user) other_user = insert(:user)
{:ok, _user_relationship} = User.block(user, other_user) {:ok, _user_relationship} = User.block(user, other_user)

View file

@ -10,8 +10,9 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do
import Pleroma.Factory import Pleroma.Factory
test "returns a list of conversations", %{conn: conn} do setup do: oauth_access(["read:statuses"])
user_one = insert(:user)
test "returns a list of conversations", %{user: user_one, conn: conn} do
user_two = insert(:user) user_two = insert(:user)
user_three = insert(:user) user_three = insert(:user)
@ -33,10 +34,7 @@ test "returns a list of conversations", %{conn: conn} do
"visibility" => "private" "visibility" => "private"
}) })
res_conn = res_conn = get(conn, "/api/v1/conversations")
conn
|> assign(:user, user_one)
|> get("/api/v1/conversations")
assert response = json_response(res_conn, 200) assert response = json_response(res_conn, 200)
@ -59,8 +57,7 @@ test "returns a list of conversations", %{conn: conn} do
assert User.get_cached_by_id(user_one.id).unread_conversation_count == 0 assert User.get_cached_by_id(user_one.id).unread_conversation_count == 0
end end
test "filters conversations by recipients", %{conn: conn} do test "filters conversations by recipients", %{user: user_one, conn: conn} do
user_one = insert(:user)
user_two = insert(:user) user_two = insert(:user)
user_three = insert(:user) user_three = insert(:user)
@ -96,7 +93,6 @@ test "filters conversations by recipients", %{conn: conn} do
[conversation1, conversation2] = [conversation1, conversation2] =
conn conn
|> assign(:user, user_one)
|> get("/api/v1/conversations", %{"recipients" => [user_two.id]}) |> get("/api/v1/conversations", %{"recipients" => [user_two.id]})
|> json_response(200) |> json_response(200)
@ -105,15 +101,13 @@ test "filters conversations by recipients", %{conn: conn} do
[conversation1] = [conversation1] =
conn conn
|> assign(:user, user_one)
|> get("/api/v1/conversations", %{"recipients" => [user_two.id, user_three.id]}) |> get("/api/v1/conversations", %{"recipients" => [user_two.id, user_three.id]})
|> json_response(200) |> json_response(200)
assert conversation1["last_status"]["id"] == direct3.id assert conversation1["last_status"]["id"] == direct3.id
end end
test "updates the last_status on reply", %{conn: conn} do test "updates the last_status on reply", %{user: user_one, conn: conn} do
user_one = insert(:user)
user_two = insert(:user) user_two = insert(:user)
{:ok, direct} = {:ok, direct} =
@ -131,15 +125,13 @@ test "updates the last_status on reply", %{conn: conn} do
[%{"last_status" => res_last_status}] = [%{"last_status" => res_last_status}] =
conn conn
|> assign(:user, user_one)
|> get("/api/v1/conversations") |> get("/api/v1/conversations")
|> json_response(200) |> json_response(200)
assert res_last_status["id"] == direct_reply.id assert res_last_status["id"] == direct_reply.id
end end
test "the user marks a conversation as read", %{conn: conn} do test "the user marks a conversation as read", %{user: user_one, conn: conn} do
user_one = insert(:user)
user_two = insert(:user) user_two = insert(:user)
{:ok, direct} = {:ok, direct} =
@ -151,15 +143,21 @@ test "the user marks a conversation as read", %{conn: conn} do
assert User.get_cached_by_id(user_one.id).unread_conversation_count == 0 assert User.get_cached_by_id(user_one.id).unread_conversation_count == 0
assert User.get_cached_by_id(user_two.id).unread_conversation_count == 1 assert User.get_cached_by_id(user_two.id).unread_conversation_count == 1
[%{"id" => direct_conversation_id, "unread" => true}] = user_two_conn =
conn build_conn()
|> assign(:user, user_two) |> assign(:user, user_two)
|> assign(
:token,
insert(:oauth_token, user: user_two, scopes: ["read:statuses", "write:conversations"])
)
[%{"id" => direct_conversation_id, "unread" => true}] =
user_two_conn
|> get("/api/v1/conversations") |> get("/api/v1/conversations")
|> json_response(200) |> json_response(200)
%{"unread" => false} = %{"unread" => false} =
conn user_two_conn
|> assign(:user, user_two)
|> post("/api/v1/conversations/#{direct_conversation_id}/read") |> post("/api/v1/conversations/#{direct_conversation_id}/read")
|> json_response(200) |> json_response(200)
@ -176,7 +174,6 @@ test "the user marks a conversation as read", %{conn: conn} do
[%{"unread" => true}] = [%{"unread" => true}] =
conn conn
|> assign(:user, user_one)
|> get("/api/v1/conversations") |> get("/api/v1/conversations")
|> json_response(200) |> json_response(200)
@ -195,8 +192,7 @@ test "the user marks a conversation as read", %{conn: conn} do
assert User.get_cached_by_id(user_two.id).unread_conversation_count == 0 assert User.get_cached_by_id(user_two.id).unread_conversation_count == 0
end end
test "(vanilla) Mastodon frontend behaviour", %{conn: conn} do test "(vanilla) Mastodon frontend behaviour", %{user: user_one, conn: conn} do
user_one = insert(:user)
user_two = insert(:user) user_two = insert(:user)
{:ok, direct} = {:ok, direct} =
@ -205,10 +201,7 @@ test "(vanilla) Mastodon frontend behaviour", %{conn: conn} do
"visibility" => "direct" "visibility" => "direct"
}) })
res_conn = res_conn = get(conn, "/api/v1/statuses/#{direct.id}/context")
conn
|> assign(:user, user_one)
|> get("/api/v1/statuses/#{direct.id}/context")
assert %{"ancestors" => [], "descendants" => []} == json_response(res_conn, 200) assert %{"ancestors" => [], "descendants" => []} == json_response(res_conn, 200)
end end

View file

@ -9,31 +9,25 @@ defmodule Pleroma.Web.MastodonAPI.DomainBlockControllerTest do
import Pleroma.Factory import Pleroma.Factory
test "blocking / unblocking a domain", %{conn: conn} do test "blocking / unblocking a domain" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:blocks"])
other_user = insert(:user, %{ap_id: "https://dogwhistle.zone/@pundit"}) other_user = insert(:user, %{ap_id: "https://dogwhistle.zone/@pundit"})
conn = ret_conn = post(conn, "/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"})
conn
|> assign(:user, user)
|> post("/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"})
assert %{} = json_response(conn, 200) assert %{} = json_response(ret_conn, 200)
user = User.get_cached_by_ap_id(user.ap_id) user = User.get_cached_by_ap_id(user.ap_id)
assert User.blocks?(user, other_user) assert User.blocks?(user, other_user)
conn = ret_conn = delete(conn, "/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"})
build_conn()
|> assign(:user, user)
|> delete("/api/v1/domain_blocks", %{"domain" => "dogwhistle.zone"})
assert %{} = json_response(conn, 200) assert %{} = json_response(ret_conn, 200)
user = User.get_cached_by_ap_id(user.ap_id) user = User.get_cached_by_ap_id(user.ap_id)
refute User.blocks?(user, other_user) refute User.blocks?(user, other_user)
end end
test "getting a list of domain blocks", %{conn: conn} do test "getting a list of domain blocks" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:blocks"])
{:ok, user} = User.block_domain(user, "bad.site") {:ok, user} = User.block_domain(user, "bad.site")
{:ok, user} = User.block_domain(user, "even.worse.site") {:ok, user} = User.block_domain(user, "even.worse.site")

View file

@ -7,20 +7,15 @@ defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do
alias Pleroma.Web.MastodonAPI.FilterView alias Pleroma.Web.MastodonAPI.FilterView
import Pleroma.Factory test "creating a filter" do
%{conn: conn} = oauth_access(["write:filters"])
test "creating a filter", %{conn: conn} do
user = insert(:user)
filter = %Pleroma.Filter{ filter = %Pleroma.Filter{
phrase: "knights", phrase: "knights",
context: ["home"] context: ["home"]
} }
conn = conn = post(conn, "/api/v1/filters", %{"phrase" => filter.phrase, context: filter.context})
conn
|> assign(:user, user)
|> post("/api/v1/filters", %{"phrase" => filter.phrase, context: filter.context})
assert response = json_response(conn, 200) assert response = json_response(conn, 200)
assert response["phrase"] == filter.phrase assert response["phrase"] == filter.phrase
@ -30,8 +25,8 @@ test "creating a filter", %{conn: conn} do
assert response["id"] != "" assert response["id"] != ""
end end
test "fetching a list of filters", %{conn: conn} do test "fetching a list of filters" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:filters"])
query_one = %Pleroma.Filter{ query_one = %Pleroma.Filter{
user_id: user.id, user_id: user.id,
@ -52,7 +47,6 @@ test "fetching a list of filters", %{conn: conn} do
response = response =
conn conn
|> assign(:user, user)
|> get("/api/v1/filters") |> get("/api/v1/filters")
|> json_response(200) |> json_response(200)
@ -64,8 +58,8 @@ test "fetching a list of filters", %{conn: conn} do
) )
end end
test "get a filter", %{conn: conn} do test "get a filter" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:filters"])
query = %Pleroma.Filter{ query = %Pleroma.Filter{
user_id: user.id, user_id: user.id,
@ -76,16 +70,13 @@ test "get a filter", %{conn: conn} do
{:ok, filter} = Pleroma.Filter.create(query) {:ok, filter} = Pleroma.Filter.create(query)
conn = conn = get(conn, "/api/v1/filters/#{filter.filter_id}")
conn
|> assign(:user, user)
|> get("/api/v1/filters/#{filter.filter_id}")
assert _response = json_response(conn, 200) assert _response = json_response(conn, 200)
end end
test "update a filter", %{conn: conn} do test "update a filter" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:filters"])
query = %Pleroma.Filter{ query = %Pleroma.Filter{
user_id: user.id, user_id: user.id,
@ -102,9 +93,7 @@ test "update a filter", %{conn: conn} do
} }
conn = conn =
conn put(conn, "/api/v1/filters/#{query.filter_id}", %{
|> assign(:user, user)
|> put("/api/v1/filters/#{query.filter_id}", %{
phrase: new.phrase, phrase: new.phrase,
context: new.context context: new.context
}) })
@ -114,8 +103,8 @@ test "update a filter", %{conn: conn} do
assert response["context"] == new.context assert response["context"] == new.context
end end
test "delete a filter", %{conn: conn} do test "delete a filter" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:filters"])
query = %Pleroma.Filter{ query = %Pleroma.Filter{
user_id: user.id, user_id: user.id,
@ -126,10 +115,7 @@ test "delete a filter", %{conn: conn} do
{:ok, filter} = Pleroma.Filter.create(query) {:ok, filter} = Pleroma.Filter.create(query)
conn = conn = delete(conn, "/api/v1/filters/#{filter.filter_id}")
conn
|> assign(:user, user)
|> delete("/api/v1/filters/#{filter.filter_id}")
assert response = json_response(conn, 200) assert response = json_response(conn, 200)
assert response == %{} assert response == %{}

View file

@ -11,8 +11,13 @@ defmodule Pleroma.Web.MastodonAPI.FollowRequestControllerTest do
import Pleroma.Factory import Pleroma.Factory
describe "locked accounts" do describe "locked accounts" do
test "/api/v1/follow_requests works" do setup do
user = insert(:user, locked: true) user = insert(:user, locked: true)
%{conn: conn} = oauth_access(["follow"], user: user)
%{user: user, conn: conn}
end
test "/api/v1/follow_requests works", %{user: user, conn: conn} do
other_user = insert(:user) other_user = insert(:user)
{:ok, _activity} = ActivityPub.follow(other_user, user) {:ok, _activity} = ActivityPub.follow(other_user, user)
@ -20,17 +25,13 @@ test "/api/v1/follow_requests works" do
assert User.following?(other_user, user) == false assert User.following?(other_user, user) == false
conn = conn = get(conn, "/api/v1/follow_requests")
build_conn()
|> assign(:user, user)
|> get("/api/v1/follow_requests")
assert [relationship] = json_response(conn, 200) assert [relationship] = json_response(conn, 200)
assert to_string(other_user.id) == relationship["id"] assert to_string(other_user.id) == relationship["id"]
end end
test "/api/v1/follow_requests/:id/authorize works" do test "/api/v1/follow_requests/:id/authorize works", %{user: user, conn: conn} do
user = insert(:user, locked: true)
other_user = insert(:user) other_user = insert(:user)
{:ok, _activity} = ActivityPub.follow(other_user, user) {:ok, _activity} = ActivityPub.follow(other_user, user)
@ -41,10 +42,7 @@ test "/api/v1/follow_requests/:id/authorize works" do
assert User.following?(other_user, user) == false assert User.following?(other_user, user) == false
conn = conn = post(conn, "/api/v1/follow_requests/#{other_user.id}/authorize")
build_conn()
|> assign(:user, user)
|> post("/api/v1/follow_requests/#{other_user.id}/authorize")
assert relationship = json_response(conn, 200) assert relationship = json_response(conn, 200)
assert to_string(other_user.id) == relationship["id"] assert to_string(other_user.id) == relationship["id"]
@ -55,18 +53,14 @@ test "/api/v1/follow_requests/:id/authorize works" do
assert User.following?(other_user, user) == true assert User.following?(other_user, user) == true
end end
test "/api/v1/follow_requests/:id/reject works" do test "/api/v1/follow_requests/:id/reject works", %{user: user, conn: conn} do
user = insert(:user, locked: true)
other_user = insert(:user) other_user = insert(:user)
{:ok, _activity} = ActivityPub.follow(other_user, user) {:ok, _activity} = ActivityPub.follow(other_user, user)
user = User.get_cached_by_id(user.id) user = User.get_cached_by_id(user.id)
conn = conn = post(conn, "/api/v1/follow_requests/#{other_user.id}/reject")
build_conn()
|> assign(:user, user)
|> post("/api/v1/follow_requests/#{other_user.id}/reject")
assert relationship = json_response(conn, 200) assert relationship = json_response(conn, 200)
assert to_string(other_user.id) == relationship["id"] assert to_string(other_user.id) == relationship["id"]

View file

@ -9,44 +9,35 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do
import Pleroma.Factory import Pleroma.Factory
test "creating a list", %{conn: conn} do test "creating a list" do
user = insert(:user) %{conn: conn} = oauth_access(["write:lists"])
conn = conn = post(conn, "/api/v1/lists", %{"title" => "cuties"})
conn
|> assign(:user, user)
|> post("/api/v1/lists", %{"title" => "cuties"})
assert %{"title" => title} = json_response(conn, 200) assert %{"title" => title} = json_response(conn, 200)
assert title == "cuties" assert title == "cuties"
end end
test "renders error for invalid params", %{conn: conn} do test "renders error for invalid params" do
user = insert(:user) %{conn: conn} = oauth_access(["write:lists"])
conn = conn = post(conn, "/api/v1/lists", %{"title" => nil})
conn
|> assign(:user, user)
|> post("/api/v1/lists", %{"title" => nil})
assert %{"error" => "can't be blank"} == json_response(conn, :unprocessable_entity) assert %{"error" => "can't be blank"} == json_response(conn, :unprocessable_entity)
end end
test "listing a user's lists", %{conn: conn} do test "listing a user's lists" do
user = insert(:user) %{conn: conn} = oauth_access(["read:lists", "write:lists"])
conn conn
|> assign(:user, user)
|> post("/api/v1/lists", %{"title" => "cuties"}) |> post("/api/v1/lists", %{"title" => "cuties"})
|> json_response(:ok)
conn conn
|> assign(:user, user)
|> post("/api/v1/lists", %{"title" => "cofe"}) |> post("/api/v1/lists", %{"title" => "cofe"})
|> json_response(:ok)
conn = conn = get(conn, "/api/v1/lists")
conn
|> assign(:user, user)
|> get("/api/v1/lists")
assert [ assert [
%{"id" => _, "title" => "cofe"}, %{"id" => _, "title" => "cofe"},
@ -54,41 +45,35 @@ test "listing a user's lists", %{conn: conn} do
] = json_response(conn, :ok) ] = json_response(conn, :ok)
end end
test "adding users to a list", %{conn: conn} do test "adding users to a list" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:lists"])
other_user = insert(:user) other_user = insert(:user)
{:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.create("name", user)
conn = conn = post(conn, "/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]})
conn
|> assign(:user, user)
|> post("/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]})
assert %{} == json_response(conn, 200) assert %{} == json_response(conn, 200)
%Pleroma.List{following: following} = Pleroma.List.get(list.id, user) %Pleroma.List{following: following} = Pleroma.List.get(list.id, user)
assert following == [other_user.follower_address] assert following == [other_user.follower_address]
end end
test "removing users from a list", %{conn: conn} do test "removing users from a list" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:lists"])
other_user = insert(:user) other_user = insert(:user)
third_user = insert(:user) third_user = insert(:user)
{:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.create("name", user)
{:ok, list} = Pleroma.List.follow(list, other_user) {:ok, list} = Pleroma.List.follow(list, other_user)
{:ok, list} = Pleroma.List.follow(list, third_user) {:ok, list} = Pleroma.List.follow(list, third_user)
conn = conn = delete(conn, "/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]})
conn
|> assign(:user, user)
|> delete("/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]})
assert %{} == json_response(conn, 200) assert %{} == json_response(conn, 200)
%Pleroma.List{following: following} = Pleroma.List.get(list.id, user) %Pleroma.List{following: following} = Pleroma.List.get(list.id, user)
assert following == [third_user.follower_address] assert following == [third_user.follower_address]
end end
test "listing users in a list", %{conn: conn} do test "listing users in a list" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:lists"])
other_user = insert(:user) other_user = insert(:user)
{:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.create("name", user)
{:ok, list} = Pleroma.List.follow(list, other_user) {:ok, list} = Pleroma.List.follow(list, other_user)
@ -102,8 +87,8 @@ test "listing users in a list", %{conn: conn} do
assert id == to_string(other_user.id) assert id == to_string(other_user.id)
end end
test "retrieving a list", %{conn: conn} do test "retrieving a list" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:lists"])
{:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.create("name", user)
conn = conn =
@ -115,32 +100,26 @@ test "retrieving a list", %{conn: conn} do
assert id == to_string(list.id) assert id == to_string(list.id)
end end
test "renders 404 if list is not found", %{conn: conn} do test "renders 404 if list is not found" do
user = insert(:user) %{conn: conn} = oauth_access(["read:lists"])
conn = conn = get(conn, "/api/v1/lists/666")
conn
|> assign(:user, user)
|> get("/api/v1/lists/666")
assert %{"error" => "List not found"} = json_response(conn, :not_found) assert %{"error" => "List not found"} = json_response(conn, :not_found)
end end
test "renaming a list", %{conn: conn} do test "renaming a list" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:lists"])
{:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.create("name", user)
conn = conn = put(conn, "/api/v1/lists/#{list.id}", %{"title" => "newname"})
conn
|> assign(:user, user)
|> put("/api/v1/lists/#{list.id}", %{"title" => "newname"})
assert %{"title" => name} = json_response(conn, 200) assert %{"title" => name} = json_response(conn, 200)
assert name == "newname" assert name == "newname"
end end
test "validates title when renaming a list", %{conn: conn} do test "validates title when renaming a list" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:lists"])
{:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.create("name", user)
conn = conn =
@ -151,14 +130,11 @@ test "validates title when renaming a list", %{conn: conn} do
assert %{"error" => "can't be blank"} == json_response(conn, :unprocessable_entity) assert %{"error" => "can't be blank"} == json_response(conn, :unprocessable_entity)
end end
test "deleting a list", %{conn: conn} do test "deleting a list" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:lists"])
{:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.create("name", user)
conn = conn = delete(conn, "/api/v1/lists/#{list.id}")
conn
|> assign(:user, user)
|> delete("/api/v1/lists/#{list.id}")
assert %{} = json_response(conn, 200) assert %{} = json_response(conn, 200)
assert is_nil(Repo.get(Pleroma.List, list.id)) assert is_nil(Repo.get(Pleroma.List, list.id))

View file

@ -9,23 +9,17 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.ActivityPub.ActivityPub
import Pleroma.Factory setup do: oauth_access(["write:media"])
describe "media upload" do describe "media upload" do
setup do setup do
user = insert(:user)
conn =
build_conn()
|> assign(:user, user)
image = %Plug.Upload{ image = %Plug.Upload{
content_type: "image/jpg", content_type: "image/jpg",
path: Path.absname("test/fixtures/image.jpg"), path: Path.absname("test/fixtures/image.jpg"),
filename: "an_image.jpg" filename: "an_image.jpg"
} }
[conn: conn, image: image] [image: image]
end end
clear_config([:media_proxy]) clear_config([:media_proxy])
@ -49,9 +43,7 @@ test "returns uploaded image", %{conn: conn, image: image} do
end end
describe "PUT /api/v1/media/:id" do describe "PUT /api/v1/media/:id" do
setup do setup %{user: actor} do
actor = insert(:user)
file = %Plug.Upload{ file = %Plug.Upload{
content_type: "image/jpg", content_type: "image/jpg",
path: Path.absname("test/fixtures/image.jpg"), path: Path.absname("test/fixtures/image.jpg"),
@ -65,13 +57,12 @@ test "returns uploaded image", %{conn: conn, image: image} do
description: "test-m" description: "test-m"
) )
[actor: actor, object: object] [object: object]
end end
test "updates name of media", %{conn: conn, actor: actor, object: object} do test "updates name of media", %{conn: conn, object: object} do
media = media =
conn conn
|> assign(:user, actor)
|> put("/api/v1/media/#{object.id}", %{"description" => "test-media"}) |> put("/api/v1/media/#{object.id}", %{"description" => "test-media"})
|> json_response(:ok) |> json_response(:ok)
@ -79,10 +70,9 @@ test "updates name of media", %{conn: conn, actor: actor, object: object} do
assert refresh_record(object).data["name"] == "test-media" assert refresh_record(object).data["name"] == "test-media"
end end
test "returns error wheb request is bad", %{conn: conn, actor: actor, object: object} do test "returns error when request is bad", %{conn: conn, object: object} do
media = media =
conn conn
|> assign(:user, actor)
|> put("/api/v1/media/#{object.id}", %{}) |> put("/api/v1/media/#{object.id}", %{})
|> json_response(400) |> json_response(400)

View file

@ -12,8 +12,8 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do
import Pleroma.Factory import Pleroma.Factory
test "list of notifications", %{conn: conn} do test "list of notifications" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"}) {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
@ -34,18 +34,15 @@ test "list of notifications", %{conn: conn} do
assert response == expected_response assert response == expected_response
end end
test "getting a single notification", %{conn: conn} do test "getting a single notification" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user) 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) {:ok, [notification]} = Notification.create_notifications(activity)
conn = conn = get(conn, "/api/v1/notifications/#{notification.id}")
conn
|> assign(:user, user)
|> get("/api/v1/notifications/#{notification.id}")
expected_response = expected_response =
"hi <span class=\"h-card\"><a data-user=\"#{user.id}\" class=\"u-url mention\" href=\"#{ "hi <span class=\"h-card\"><a data-user=\"#{user.id}\" class=\"u-url mention\" href=\"#{
@ -56,8 +53,8 @@ test "getting a single notification", %{conn: conn} do
assert response == expected_response assert response == expected_response
end end
test "dismissing a single notification", %{conn: conn} do test "dismissing a single notification" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:notifications"])
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"}) {:ok, activity} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
@ -72,32 +69,26 @@ test "dismissing a single notification", %{conn: conn} do
assert %{} = json_response(conn, 200) assert %{} = json_response(conn, 200)
end end
test "clearing all notifications", %{conn: conn} do test "clearing all notifications" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:notifications", "read:notifications"])
other_user = insert(:user) 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) {:ok, [_notification]} = Notification.create_notifications(activity)
conn = ret_conn = post(conn, "/api/v1/notifications/clear")
conn
|> assign(:user, user)
|> post("/api/v1/notifications/clear")
assert %{} = json_response(conn, 200) assert %{} = json_response(ret_conn, 200)
conn = ret_conn = get(conn, "/api/v1/notifications")
build_conn()
|> assign(:user, user)
|> get("/api/v1/notifications")
assert all = json_response(conn, 200) assert all = json_response(ret_conn, 200)
assert all == [] assert all == []
end end
test "paginates notifications using min_id, since_id, max_id, and limit", %{conn: conn} do test "paginates notifications using min_id, since_id, max_id, and limit" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user) other_user = insert(:user)
{:ok, activity1} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"}) {:ok, activity1} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
@ -138,8 +129,8 @@ test "paginates notifications using min_id, since_id, max_id, and limit", %{conn
end end
describe "exclude_visibilities" do describe "exclude_visibilities" do
test "filters notifications for mentions", %{conn: conn} do test "filters notifications for mentions" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user) other_user = insert(:user)
{:ok, public_activity} = {:ok, public_activity} =
@ -154,8 +145,6 @@ test "filters notifications for mentions", %{conn: conn} do
{:ok, private_activity} = {:ok, private_activity} =
CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "private"}) CommonAPI.post(other_user, %{"status" => "@#{user.nickname}", "visibility" => "private"})
conn = assign(conn, :user, user)
conn_res = conn_res =
get(conn, "/api/v1/notifications", %{ get(conn, "/api/v1/notifications", %{
exclude_visibilities: ["public", "unlisted", "private"] exclude_visibilities: ["public", "unlisted", "private"]
@ -189,9 +178,9 @@ test "filters notifications for mentions", %{conn: conn} do
assert id == public_activity.id assert id == public_activity.id
end end
test "filters notifications for Like activities", %{conn: conn} do test "filters notifications for Like activities" do
user = insert(:user) user = insert(:user)
other_user = insert(:user) %{user: other_user, conn: conn} = oauth_access(["read:notifications"])
{:ok, public_activity} = {:ok, public_activity} =
CommonAPI.post(other_user, %{"status" => ".", "visibility" => "public"}) CommonAPI.post(other_user, %{"status" => ".", "visibility" => "public"})
@ -212,7 +201,6 @@ test "filters notifications for Like activities", %{conn: conn} do
activity_ids = activity_ids =
conn conn
|> assign(:user, other_user)
|> get("/api/v1/notifications", %{exclude_visibilities: ["direct"]}) |> get("/api/v1/notifications", %{exclude_visibilities: ["direct"]})
|> json_response(200) |> json_response(200)
|> Enum.map(& &1["status"]["id"]) |> Enum.map(& &1["status"]["id"])
@ -224,7 +212,6 @@ test "filters notifications for Like activities", %{conn: conn} do
activity_ids = activity_ids =
conn conn
|> assign(:user, other_user)
|> get("/api/v1/notifications", %{exclude_visibilities: ["unlisted"]}) |> get("/api/v1/notifications", %{exclude_visibilities: ["unlisted"]})
|> json_response(200) |> json_response(200)
|> Enum.map(& &1["status"]["id"]) |> Enum.map(& &1["status"]["id"])
@ -236,7 +223,6 @@ test "filters notifications for Like activities", %{conn: conn} do
activity_ids = activity_ids =
conn conn
|> assign(:user, other_user)
|> get("/api/v1/notifications", %{exclude_visibilities: ["private"]}) |> get("/api/v1/notifications", %{exclude_visibilities: ["private"]})
|> json_response(200) |> json_response(200)
|> Enum.map(& &1["status"]["id"]) |> Enum.map(& &1["status"]["id"])
@ -248,7 +234,6 @@ test "filters notifications for Like activities", %{conn: conn} do
activity_ids = activity_ids =
conn conn
|> assign(:user, other_user)
|> get("/api/v1/notifications", %{exclude_visibilities: ["public"]}) |> get("/api/v1/notifications", %{exclude_visibilities: ["public"]})
|> json_response(200) |> json_response(200)
|> Enum.map(& &1["status"]["id"]) |> Enum.map(& &1["status"]["id"])
@ -259,9 +244,9 @@ test "filters notifications for Like activities", %{conn: conn} do
assert direct_activity.id in activity_ids assert direct_activity.id in activity_ids
end end
test "filters notifications for Announce activities", %{conn: conn} do test "filters notifications for Announce activities" do
user = insert(:user) user = insert(:user)
other_user = insert(:user) %{user: other_user, conn: conn} = oauth_access(["read:notifications"])
{:ok, public_activity} = {:ok, public_activity} =
CommonAPI.post(other_user, %{"status" => ".", "visibility" => "public"}) CommonAPI.post(other_user, %{"status" => ".", "visibility" => "public"})
@ -274,7 +259,6 @@ test "filters notifications for Announce activities", %{conn: conn} do
activity_ids = activity_ids =
conn conn
|> assign(:user, other_user)
|> get("/api/v1/notifications", %{exclude_visibilities: ["unlisted"]}) |> get("/api/v1/notifications", %{exclude_visibilities: ["unlisted"]})
|> json_response(200) |> json_response(200)
|> Enum.map(& &1["status"]["id"]) |> Enum.map(& &1["status"]["id"])
@ -284,8 +268,8 @@ test "filters notifications for Announce activities", %{conn: conn} do
end end
end end
test "filters notifications using exclude_types", %{conn: conn} do test "filters notifications using exclude_types" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user) other_user = insert(:user)
{:ok, mention_activity} = CommonAPI.post(other_user, %{"status" => "hey @#{user.nickname}"}) {:ok, mention_activity} = CommonAPI.post(other_user, %{"status" => "hey @#{user.nickname}"})
@ -299,8 +283,6 @@ test "filters notifications using exclude_types", %{conn: conn} do
reblog_notification_id = get_notification_id_by_activity(reblog_activity) reblog_notification_id = get_notification_id_by_activity(reblog_activity)
follow_notification_id = get_notification_id_by_activity(follow_activity) follow_notification_id = get_notification_id_by_activity(follow_activity)
conn = assign(conn, :user, user)
conn_res = conn_res =
get(conn, "/api/v1/notifications", %{exclude_types: ["mention", "favourite", "reblog"]}) get(conn, "/api/v1/notifications", %{exclude_types: ["mention", "favourite", "reblog"]})
@ -322,8 +304,8 @@ test "filters notifications using exclude_types", %{conn: conn} do
assert [%{"id" => ^reblog_notification_id}] = json_response(conn_res, 200) assert [%{"id" => ^reblog_notification_id}] = json_response(conn_res, 200)
end end
test "destroy multiple", %{conn: conn} do test "destroy multiple" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:notifications", "write:notifications"])
other_user = insert(:user) other_user = insert(:user)
{:ok, activity1} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"}) {:ok, activity1} = CommonAPI.post(other_user, %{"status" => "hi @#{user.nickname}"})
@ -336,8 +318,6 @@ test "destroy multiple", %{conn: conn} do
notification3_id = get_notification_id_by_activity(activity3) notification3_id = get_notification_id_by_activity(activity3)
notification4_id = get_notification_id_by_activity(activity4) notification4_id = get_notification_id_by_activity(activity4)
conn = assign(conn, :user, user)
result = result =
conn conn
|> get("/api/v1/notifications") |> get("/api/v1/notifications")
@ -348,6 +328,7 @@ test "destroy multiple", %{conn: conn} do
conn2 = conn2 =
conn conn
|> assign(:user, other_user) |> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:notifications"]))
result = result =
conn2 conn2
@ -372,97 +353,110 @@ test "destroy multiple", %{conn: conn} do
assert [%{"id" => ^notification4_id}, %{"id" => ^notification3_id}] = result assert [%{"id" => ^notification4_id}, %{"id" => ^notification3_id}] = result
end end
test "doesn't see notifications after muting user with notifications", %{conn: conn} do test "doesn't see notifications after muting user with notifications" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:notifications"])
user2 = insert(:user) user2 = insert(:user)
{:ok, _, _, _} = CommonAPI.follow(user, user2) {:ok, _, _, _} = CommonAPI.follow(user, user2)
{:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"}) {:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"})
conn = assign(conn, :user, user) ret_conn = get(conn, "/api/v1/notifications")
conn = get(conn, "/api/v1/notifications") assert length(json_response(ret_conn, 200)) == 1
assert length(json_response(conn, 200)) == 1
{:ok, _user_relationships} = User.mute(user, user2) {:ok, _user_relationships} = User.mute(user, user2)
conn = assign(build_conn(), :user, user)
conn = get(conn, "/api/v1/notifications") conn = get(conn, "/api/v1/notifications")
assert json_response(conn, 200) == [] assert json_response(conn, 200) == []
end end
test "see notifications after muting user without notifications", %{conn: conn} do test "see notifications after muting user without notifications" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:notifications"])
user2 = insert(:user) user2 = insert(:user)
{:ok, _, _, _} = CommonAPI.follow(user, user2) {:ok, _, _, _} = CommonAPI.follow(user, user2)
{:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"}) {:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"})
conn = assign(conn, :user, user) ret_conn = get(conn, "/api/v1/notifications")
conn = get(conn, "/api/v1/notifications") assert length(json_response(ret_conn, 200)) == 1
assert length(json_response(conn, 200)) == 1
{:ok, _user_relationships} = User.mute(user, user2, false) {:ok, _user_relationships} = User.mute(user, user2, false)
conn = assign(build_conn(), :user, user)
conn = get(conn, "/api/v1/notifications") conn = get(conn, "/api/v1/notifications")
assert length(json_response(conn, 200)) == 1 assert length(json_response(conn, 200)) == 1
end end
test "see notifications after muting user with notifications and with_muted parameter", %{ test "see notifications after muting user with notifications and with_muted parameter" do
conn: conn %{user: user, conn: conn} = oauth_access(["read:notifications"])
} do
user = insert(:user)
user2 = insert(:user) user2 = insert(:user)
{:ok, _, _, _} = CommonAPI.follow(user, user2) {:ok, _, _, _} = CommonAPI.follow(user, user2)
{:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"}) {:ok, _} = CommonAPI.post(user2, %{"status" => "hey @#{user.nickname}"})
conn = assign(conn, :user, user) ret_conn = get(conn, "/api/v1/notifications")
conn = get(conn, "/api/v1/notifications") assert length(json_response(ret_conn, 200)) == 1
assert length(json_response(conn, 200)) == 1
{:ok, _user_relationships} = User.mute(user, user2) {:ok, _user_relationships} = User.mute(user, user2)
conn = assign(build_conn(), :user, user)
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(conn, 200)) == 1
end end
test "see move notifications with `with_move` parameter", %{ test "see move notifications with `with_move` parameter" do
conn: conn
} do
old_user = insert(:user) old_user = insert(:user)
new_user = insert(:user, also_known_as: [old_user.ap_id]) new_user = insert(:user, also_known_as: [old_user.ap_id])
follower = insert(:user) %{user: follower, conn: conn} = oauth_access(["read:notifications"])
User.follow(follower, old_user) User.follow(follower, old_user)
Pleroma.Web.ActivityPub.ActivityPub.move(old_user, new_user) Pleroma.Web.ActivityPub.ActivityPub.move(old_user, new_user)
Pleroma.Tests.ObanHelpers.perform_all() Pleroma.Tests.ObanHelpers.perform_all()
conn = ret_conn = get(conn, "/api/v1/notifications")
conn
|> assign(:user, follower)
|> get("/api/v1/notifications")
assert json_response(conn, 200) == [] assert json_response(ret_conn, 200) == []
conn = conn = get(conn, "/api/v1/notifications", %{"with_move" => "true"})
build_conn()
|> assign(:user, follower)
|> get("/api/v1/notifications", %{"with_move" => "true"})
assert length(json_response(conn, 200)) == 1 assert length(json_response(conn, 200)) == 1
end end
describe "link headers" do
test "preserves parameters in link headers" do
%{user: user, conn: conn} = oauth_access(["read:notifications"])
other_user = insert(:user)
{:ok, activity1} =
CommonAPI.post(other_user, %{
"status" => "hi @#{user.nickname}",
"visibility" => "public"
})
{:ok, activity2} =
CommonAPI.post(other_user, %{
"status" => "hi @#{user.nickname}",
"visibility" => "public"
})
notification1 = Repo.get_by(Notification, activity_id: activity1.id)
notification2 = Repo.get_by(Notification, activity_id: activity2.id)
conn =
conn
|> assign(:user, user)
|> get("/api/v1/notifications", %{media_only: true})
assert [link_header] = get_resp_header(conn, "link")
assert link_header =~ ~r/media_only=true/
assert link_header =~ ~r/min_id=#{notification2.id}/
assert link_header =~ ~r/max_id=#{notification1.id}/
end
end
defp get_notification_id_by_activity(%{id: id}) do defp get_notification_id_by_activity(%{id: id}) do
Notification Notification
|> Repo.get_by(activity_id: id) |> Repo.get_by(activity_id: id)

View file

@ -11,9 +11,9 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do
import Pleroma.Factory import Pleroma.Factory
describe "GET /api/v1/polls/:id" do describe "GET /api/v1/polls/:id" do
test "returns poll entity for object id", %{conn: conn} do setup do: oauth_access(["read:statuses"])
user = insert(:user)
test "returns poll entity for object id", %{user: user, conn: conn} do
{:ok, activity} = {:ok, activity} =
CommonAPI.post(user, %{ CommonAPI.post(user, %{
"status" => "Pleroma does", "status" => "Pleroma does",
@ -22,10 +22,7 @@ test "returns poll entity for object id", %{conn: conn} do
object = Object.normalize(activity) object = Object.normalize(activity)
conn = conn = get(conn, "/api/v1/polls/#{object.id}")
conn
|> assign(:user, user)
|> get("/api/v1/polls/#{object.id}")
response = json_response(conn, 200) response = json_response(conn, 200)
id = to_string(object.id) id = to_string(object.id)
@ -33,11 +30,10 @@ test "returns poll entity for object id", %{conn: conn} do
end end
test "does not expose polls for private statuses", %{conn: conn} do test "does not expose polls for private statuses", %{conn: conn} do
user = insert(:user)
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = {:ok, activity} =
CommonAPI.post(user, %{ CommonAPI.post(other_user, %{
"status" => "Pleroma does", "status" => "Pleroma does",
"poll" => %{"options" => ["what Mastodon't", "n't what Mastodoes"], "expires_in" => 20}, "poll" => %{"options" => ["what Mastodon't", "n't what Mastodoes"], "expires_in" => 20},
"visibility" => "private" "visibility" => "private"
@ -45,22 +41,20 @@ test "does not expose polls for private statuses", %{conn: conn} do
object = Object.normalize(activity) object = Object.normalize(activity)
conn = conn = get(conn, "/api/v1/polls/#{object.id}")
conn
|> assign(:user, other_user)
|> get("/api/v1/polls/#{object.id}")
assert json_response(conn, 404) assert json_response(conn, 404)
end end
end end
describe "POST /api/v1/polls/:id/votes" do describe "POST /api/v1/polls/:id/votes" do
setup do: oauth_access(["write:statuses"])
test "votes are added to the poll", %{conn: conn} do test "votes are added to the poll", %{conn: conn} do
user = insert(:user)
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = {:ok, activity} =
CommonAPI.post(user, %{ CommonAPI.post(other_user, %{
"status" => "A very delicious sandwich", "status" => "A very delicious sandwich",
"poll" => %{ "poll" => %{
"options" => ["Lettuce", "Grilled Bacon", "Tomato"], "options" => ["Lettuce", "Grilled Bacon", "Tomato"],
@ -71,10 +65,7 @@ test "votes are added to the poll", %{conn: conn} do
object = Object.normalize(activity) object = Object.normalize(activity)
conn = conn = post(conn, "/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1, 2]})
conn
|> assign(:user, other_user)
|> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1, 2]})
assert json_response(conn, 200) assert json_response(conn, 200)
object = Object.get_by_id(object.id) object = Object.get_by_id(object.id)
@ -84,9 +75,7 @@ test "votes are added to the poll", %{conn: conn} do
end) end)
end end
test "author can't vote", %{conn: conn} do test "author can't vote", %{user: user, conn: conn} do
user = insert(:user)
{:ok, activity} = {:ok, activity} =
CommonAPI.post(user, %{ CommonAPI.post(user, %{
"status" => "Am I cute?", "status" => "Am I cute?",
@ -96,7 +85,6 @@ test "author can't vote", %{conn: conn} do
object = Object.normalize(activity) object = Object.normalize(activity)
assert conn assert conn
|> assign(:user, user)
|> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [1]}) |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [1]})
|> json_response(422) == %{"error" => "Poll's author can't vote"} |> json_response(422) == %{"error" => "Poll's author can't vote"}
@ -106,11 +94,10 @@ test "author can't vote", %{conn: conn} do
end end
test "does not allow multiple choices on a single-choice question", %{conn: conn} do test "does not allow multiple choices on a single-choice question", %{conn: conn} do
user = insert(:user)
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = {:ok, activity} =
CommonAPI.post(user, %{ CommonAPI.post(other_user, %{
"status" => "The glass is", "status" => "The glass is",
"poll" => %{"options" => ["half empty", "half full"], "expires_in" => 20} "poll" => %{"options" => ["half empty", "half full"], "expires_in" => 20}
}) })
@ -118,7 +105,6 @@ test "does not allow multiple choices on a single-choice question", %{conn: conn
object = Object.normalize(activity) object = Object.normalize(activity)
assert conn assert conn
|> assign(:user, other_user)
|> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1]}) |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1]})
|> json_response(422) == %{"error" => "Too many choices"} |> json_response(422) == %{"error" => "Too many choices"}
@ -130,42 +116,32 @@ test "does not allow multiple choices on a single-choice question", %{conn: conn
end end
test "does not allow choice index to be greater than options count", %{conn: conn} do test "does not allow choice index to be greater than options count", %{conn: conn} do
user = insert(:user)
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = {:ok, activity} =
CommonAPI.post(user, %{ CommonAPI.post(other_user, %{
"status" => "Am I cute?", "status" => "Am I cute?",
"poll" => %{"options" => ["Yes", "No"], "expires_in" => 20} "poll" => %{"options" => ["Yes", "No"], "expires_in" => 20}
}) })
object = Object.normalize(activity) object = Object.normalize(activity)
conn = conn = post(conn, "/api/v1/polls/#{object.id}/votes", %{"choices" => [2]})
conn
|> assign(:user, other_user)
|> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [2]})
assert json_response(conn, 422) == %{"error" => "Invalid indices"} assert json_response(conn, 422) == %{"error" => "Invalid indices"}
end end
test "returns 404 error when object is not exist", %{conn: conn} do test "returns 404 error when object is not exist", %{conn: conn} do
user = insert(:user) conn = post(conn, "/api/v1/polls/1/votes", %{"choices" => [0]})
conn =
conn
|> assign(:user, user)
|> post("/api/v1/polls/1/votes", %{"choices" => [0]})
assert json_response(conn, 404) == %{"error" => "Record not found"} assert json_response(conn, 404) == %{"error" => "Record not found"}
end end
test "returns 404 when poll is private and not available for user", %{conn: conn} do test "returns 404 when poll is private and not available for user", %{conn: conn} do
user = insert(:user)
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = {:ok, activity} =
CommonAPI.post(user, %{ CommonAPI.post(other_user, %{
"status" => "Am I cute?", "status" => "Am I cute?",
"poll" => %{"options" => ["Yes", "No"], "expires_in" => 20}, "poll" => %{"options" => ["Yes", "No"], "expires_in" => 20},
"visibility" => "private" "visibility" => "private"
@ -173,10 +149,7 @@ test "returns 404 when poll is private and not available for user", %{conn: conn
object = Object.normalize(activity) object = Object.normalize(activity)
conn = conn = post(conn, "/api/v1/polls/#{object.id}/votes", %{"choices" => [0]})
conn
|> assign(:user, other_user)
|> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0]})
assert json_response(conn, 404) == %{"error" => "Record not found"} assert json_response(conn, 404) == %{"error" => "Record not found"}
end end

View file

@ -9,32 +9,30 @@ defmodule Pleroma.Web.MastodonAPI.ReportControllerTest do
import Pleroma.Factory import Pleroma.Factory
setup do: oauth_access(["write:reports"])
setup do setup do
reporter = insert(:user)
target_user = insert(:user) target_user = insert(:user)
{:ok, activity} = CommonAPI.post(target_user, %{"status" => "foobar"}) {:ok, activity} = CommonAPI.post(target_user, %{"status" => "foobar"})
[reporter: reporter, target_user: target_user, activity: activity] [target_user: target_user, activity: activity]
end end
test "submit a basic report", %{conn: conn, reporter: reporter, target_user: target_user} do test "submit a basic report", %{conn: conn, target_user: target_user} do
assert %{"action_taken" => false, "id" => _} = assert %{"action_taken" => false, "id" => _} =
conn conn
|> assign(:user, reporter)
|> post("/api/v1/reports", %{"account_id" => target_user.id}) |> post("/api/v1/reports", %{"account_id" => target_user.id})
|> json_response(200) |> json_response(200)
end end
test "submit a report with statuses and comment", %{ test "submit a report with statuses and comment", %{
conn: conn, conn: conn,
reporter: reporter,
target_user: target_user, target_user: target_user,
activity: activity activity: activity
} do } do
assert %{"action_taken" => false, "id" => _} = assert %{"action_taken" => false, "id" => _} =
conn conn
|> assign(:user, reporter)
|> post("/api/v1/reports", %{ |> post("/api/v1/reports", %{
"account_id" => target_user.id, "account_id" => target_user.id,
"status_ids" => [activity.id], "status_ids" => [activity.id],
@ -46,19 +44,16 @@ test "submit a report with statuses and comment", %{
test "account_id is required", %{ test "account_id is required", %{
conn: conn, conn: conn,
reporter: reporter,
activity: activity activity: activity
} do } do
assert %{"error" => "Valid `account_id` required"} = assert %{"error" => "Valid `account_id` required"} =
conn conn
|> assign(:user, reporter)
|> post("/api/v1/reports", %{"status_ids" => [activity.id]}) |> post("/api/v1/reports", %{"status_ids" => [activity.id]})
|> json_response(400) |> json_response(400)
end end
test "comment must be up to the size specified in the config", %{ test "comment must be up to the size specified in the config", %{
conn: conn, conn: conn,
reporter: reporter,
target_user: target_user target_user: target_user
} do } do
max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000) max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
@ -68,20 +63,15 @@ test "comment must be up to the size specified in the config", %{
assert ^error = assert ^error =
conn conn
|> assign(:user, reporter)
|> post("/api/v1/reports", %{"account_id" => target_user.id, "comment" => comment}) |> post("/api/v1/reports", %{"account_id" => target_user.id, "comment" => comment})
|> json_response(400) |> json_response(400)
end end
test "returns error when account is not exist", %{ test "returns error when account is not exist", %{
conn: conn, conn: conn,
reporter: reporter,
activity: activity activity: activity
} do } do
conn = conn = post(conn, "/api/v1/reports", %{"status_ids" => [activity.id], "account_id" => "foo"})
conn
|> assign(:user, reporter)
|> post("/api/v1/reports", %{"status_ids" => [activity.id], "account_id" => "foo"})
assert json_response(conn, 400) == %{"error" => "Account not found"} assert json_response(conn, 400) == %{"error" => "Account not found"}
end end

View file

@ -10,89 +10,69 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityControllerTest do
import Pleroma.Factory import Pleroma.Factory
test "shows scheduled activities", %{conn: conn} do test "shows scheduled activities" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:statuses"])
scheduled_activity_id1 = insert(:scheduled_activity, user: user).id |> to_string() scheduled_activity_id1 = insert(:scheduled_activity, user: user).id |> to_string()
scheduled_activity_id2 = 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_id3 = insert(:scheduled_activity, user: user).id |> to_string()
scheduled_activity_id4 = 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 # min_id
conn_res = conn_res = get(conn, "/api/v1/scheduled_statuses?limit=2&min_id=#{scheduled_activity_id1}")
conn
|> get("/api/v1/scheduled_statuses?limit=2&min_id=#{scheduled_activity_id1}")
result = json_response(conn_res, 200) result = json_response(conn_res, 200)
assert [%{"id" => ^scheduled_activity_id3}, %{"id" => ^scheduled_activity_id2}] = result assert [%{"id" => ^scheduled_activity_id3}, %{"id" => ^scheduled_activity_id2}] = result
# since_id # since_id
conn_res = conn_res = get(conn, "/api/v1/scheduled_statuses?limit=2&since_id=#{scheduled_activity_id1}")
conn
|> get("/api/v1/scheduled_statuses?limit=2&since_id=#{scheduled_activity_id1}")
result = json_response(conn_res, 200) result = json_response(conn_res, 200)
assert [%{"id" => ^scheduled_activity_id4}, %{"id" => ^scheduled_activity_id3}] = result assert [%{"id" => ^scheduled_activity_id4}, %{"id" => ^scheduled_activity_id3}] = result
# max_id # max_id
conn_res = conn_res = get(conn, "/api/v1/scheduled_statuses?limit=2&max_id=#{scheduled_activity_id4}")
conn
|> get("/api/v1/scheduled_statuses?limit=2&max_id=#{scheduled_activity_id4}")
result = json_response(conn_res, 200) result = json_response(conn_res, 200)
assert [%{"id" => ^scheduled_activity_id3}, %{"id" => ^scheduled_activity_id2}] = result assert [%{"id" => ^scheduled_activity_id3}, %{"id" => ^scheduled_activity_id2}] = result
end end
test "shows a scheduled activity", %{conn: conn} do test "shows a scheduled activity" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:statuses"])
scheduled_activity = insert(:scheduled_activity, user: user) scheduled_activity = insert(:scheduled_activity, user: user)
res_conn = res_conn = get(conn, "/api/v1/scheduled_statuses/#{scheduled_activity.id}")
conn
|> assign(:user, user)
|> get("/api/v1/scheduled_statuses/#{scheduled_activity.id}")
assert %{"id" => scheduled_activity_id} = json_response(res_conn, 200) assert %{"id" => scheduled_activity_id} = json_response(res_conn, 200)
assert scheduled_activity_id == scheduled_activity.id |> to_string() assert scheduled_activity_id == scheduled_activity.id |> to_string()
res_conn = res_conn = get(conn, "/api/v1/scheduled_statuses/404")
conn
|> assign(:user, user)
|> get("/api/v1/scheduled_statuses/404")
assert %{"error" => "Record not found"} = json_response(res_conn, 404) assert %{"error" => "Record not found"} = json_response(res_conn, 404)
end end
test "updates a scheduled activity", %{conn: conn} do test "updates a scheduled activity" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:statuses"])
scheduled_activity = insert(:scheduled_activity, user: user) scheduled_activity = insert(:scheduled_activity, user: user)
new_scheduled_at = new_scheduled_at =
NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond) NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond)
res_conn = res_conn =
conn put(conn, "/api/v1/scheduled_statuses/#{scheduled_activity.id}", %{
|> assign(:user, user)
|> put("/api/v1/scheduled_statuses/#{scheduled_activity.id}", %{
scheduled_at: new_scheduled_at scheduled_at: new_scheduled_at
}) })
assert %{"scheduled_at" => expected_scheduled_at} = json_response(res_conn, 200) 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) assert expected_scheduled_at == Pleroma.Web.CommonAPI.Utils.to_masto_date(new_scheduled_at)
res_conn = res_conn = put(conn, "/api/v1/scheduled_statuses/404", %{scheduled_at: new_scheduled_at})
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) assert %{"error" => "Record not found"} = json_response(res_conn, 404)
end end
test "deletes a scheduled activity", %{conn: conn} do test "deletes a scheduled activity" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:statuses"])
scheduled_activity = insert(:scheduled_activity, user: user) scheduled_activity = insert(:scheduled_activity, user: user)
res_conn = res_conn =

View file

@ -77,13 +77,11 @@ test "search", %{conn: conn} do
describe ".account_search" do describe ".account_search" do
test "account search", %{conn: conn} do test "account search", %{conn: conn} do
user = insert(:user)
user_two = insert(:user, %{nickname: "shp@shitposter.club"}) user_two = insert(:user, %{nickname: "shp@shitposter.club"})
user_three = insert(:user, %{nickname: "shp@heldscal.la", name: "I love 2hu"}) user_three = insert(:user, %{nickname: "shp@heldscal.la", name: "I love 2hu"})
results = results =
conn conn
|> assign(:user, user)
|> get("/api/v1/accounts/search", %{"q" => "shp"}) |> get("/api/v1/accounts/search", %{"q" => "shp"})
|> json_response(200) |> json_response(200)
@ -94,7 +92,6 @@ test "account search", %{conn: conn} do
results = results =
conn conn
|> assign(:user, user)
|> get("/api/v1/accounts/search", %{"q" => "2hu"}) |> get("/api/v1/accounts/search", %{"q" => "2hu"})
|> json_response(200) |> json_response(200)
@ -104,11 +101,10 @@ test "account search", %{conn: conn} do
end end
test "returns account if query contains a space", %{conn: conn} do test "returns account if query contains a space", %{conn: conn} do
user = insert(:user, %{nickname: "shp@shitposter.club"}) insert(:user, %{nickname: "shp@shitposter.club"})
results = results =
conn conn
|> assign(:user, user)
|> get("/api/v1/accounts/search", %{"q" => "shp@shitposter.club xxx "}) |> get("/api/v1/accounts/search", %{"q" => "shp@shitposter.club xxx "})
|> json_response(200) |> json_response(200)
@ -209,6 +205,7 @@ test "search fetches remote accounts", %{conn: conn} do
conn = conn =
conn conn
|> assign(:user, user) |> assign(:user, user)
|> assign(:token, insert(:oauth_token, user: user, scopes: ["read"]))
|> get("/api/v1/search", %{"q" => "mike@osada.macgirvin.com", "resolve" => "true"}) |> get("/api/v1/search", %{"q" => "mike@osada.macgirvin.com", "resolve" => "true"})
assert results = json_response(conn, 200) assert results = json_response(conn, 200)

View file

@ -23,24 +23,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
clear_config([:instance, :allow_relay]) clear_config([:instance, :allow_relay])
describe "posting statuses" do describe "posting statuses" do
setup do setup do: oauth_access(["write:statuses"])
user = insert(:user)
conn =
build_conn()
|> assign(:user, user)
[conn: conn]
end
test "posting a status does not increment reblog_count when relaying", %{conn: conn} do test "posting a status does not increment reblog_count when relaying", %{conn: conn} do
Pleroma.Config.put([:instance, :federating], true) Pleroma.Config.put([:instance, :federating], true)
Pleroma.Config.get([:instance, :allow_relay], true) Pleroma.Config.get([:instance, :allow_relay], true)
user = insert(:user)
response = response =
conn conn
|> assign(:user, user)
|> post("api/v1/statuses", %{ |> post("api/v1/statuses", %{
"content_type" => "text/plain", "content_type" => "text/plain",
"source" => "Pleroma FE", "source" => "Pleroma FE",
@ -54,7 +44,6 @@ test "posting a status does not increment reblog_count when relaying", %{conn: c
response = response =
conn conn
|> assign(:user, user)
|> get("api/v1/statuses/#{response["id"]}", %{}) |> get("api/v1/statuses/#{response["id"]}", %{})
|> json_response(200) |> json_response(200)
@ -132,9 +121,7 @@ test "posting a status", %{conn: conn} do
NaiveDateTime.to_iso8601(expiration.scheduled_at) NaiveDateTime.to_iso8601(expiration.scheduled_at)
end end
test "posting an undefined status with an attachment", %{conn: conn} do test "posting an undefined status with an attachment", %{user: user, conn: conn} do
user = insert(:user)
file = %Plug.Upload{ file = %Plug.Upload{
content_type: "image/jpg", content_type: "image/jpg",
path: Path.absname("test/fixtures/image.jpg"), path: Path.absname("test/fixtures/image.jpg"),
@ -144,17 +131,14 @@ test "posting an undefined status with an attachment", %{conn: conn} do
{:ok, upload} = ActivityPub.upload(file, actor: user.ap_id) {:ok, upload} = ActivityPub.upload(file, actor: user.ap_id)
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"media_ids" => [to_string(upload.id)] "media_ids" => [to_string(upload.id)]
}) })
assert json_response(conn, 200) assert json_response(conn, 200)
end end
test "replying to a status", %{conn: conn} do test "replying to a status", %{user: user, conn: conn} do
user = insert(:user)
{:ok, replied_to} = CommonAPI.post(user, %{"status" => "cofe"}) {:ok, replied_to} = CommonAPI.post(user, %{"status" => "cofe"})
conn = conn =
@ -169,8 +153,10 @@ test "replying to a status", %{conn: conn} do
assert Activity.get_in_reply_to_activity(activity).id == replied_to.id assert Activity.get_in_reply_to_activity(activity).id == replied_to.id
end end
test "replying to a direct message with visibility other than direct", %{conn: conn} do test "replying to a direct message with visibility other than direct", %{
user = insert(:user) 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 -> Enum.each(["public", "private", "unlisted"], fn visibility ->
@ -187,18 +173,14 @@ test "replying to a direct message with visibility other than direct", %{conn: c
end end
test "posting a status with an invalid in_reply_to_id", %{conn: conn} do test "posting a status with an invalid in_reply_to_id", %{conn: conn} do
conn = conn = post(conn, "/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => ""})
conn
|> 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(conn, 200)
assert Activity.get_by_id(id) assert Activity.get_by_id(id)
end end
test "posting a sensitive status", %{conn: conn} do test "posting a sensitive status", %{conn: conn} do
conn = conn = post(conn, "/api/v1/statuses", %{"status" => "cofe", "sensitive" => true})
conn
|> post("/api/v1/statuses", %{"status" => "cofe", "sensitive" => true})
assert %{"content" => "cofe", "id" => id, "sensitive" => true} = json_response(conn, 200) assert %{"content" => "cofe", "id" => id, "sensitive" => true} = json_response(conn, 200)
assert Activity.get_by_id(id) assert Activity.get_by_id(id)
@ -206,8 +188,7 @@ test "posting a sensitive status", %{conn: conn} do
test "posting a fake status", %{conn: conn} do test "posting a fake status", %{conn: conn} do
real_conn = real_conn =
conn post(conn, "/api/v1/statuses", %{
|> post("/api/v1/statuses", %{
"status" => "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" "\"Tenshi Eating a Corndog\" is a much discussed concept on /jp/. The significance of it is disputed, so I will focus on one core concept: the symbolism behind it"
}) })
@ -226,8 +207,7 @@ test "posting a fake status", %{conn: conn} do
|> Kernel.put_in(["pleroma", "conversation_id"], nil) |> Kernel.put_in(["pleroma", "conversation_id"], nil)
fake_conn = fake_conn =
conn post(conn, "/api/v1/statuses", %{
|> post("/api/v1/statuses", %{
"status" => "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", "\"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 "preview" => true
@ -254,8 +234,7 @@ test "posting a status with OGP link preview", %{conn: conn} do
Config.put([:rich_media, :enabled], true) Config.put([:rich_media, :enabled], true)
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> post("/api/v1/statuses", %{
"status" => "https://example.com/ogp" "status" => "https://example.com/ogp"
}) })
@ -267,9 +246,7 @@ test "posting a direct status", %{conn: conn} do
user2 = insert(:user) user2 = insert(:user)
content = "direct cofe @#{user2.nickname}" content = "direct cofe @#{user2.nickname}"
conn = conn = post(conn, "api/v1/statuses", %{"status" => content, "visibility" => "direct"})
conn
|> post("api/v1/statuses", %{"status" => content, "visibility" => "direct"})
assert %{"id" => id} = response = json_response(conn, 200) assert %{"id" => id} = response = json_response(conn, 200)
assert response["visibility"] == "direct" assert response["visibility"] == "direct"
@ -282,14 +259,13 @@ test "posting a direct status", %{conn: conn} do
end end
describe "posting scheduled statuses" do describe "posting scheduled statuses" do
setup do: oauth_access(["write:statuses"])
test "creates a scheduled activity", %{conn: conn} do test "creates a scheduled activity", %{conn: conn} do
user = insert(:user)
scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond) scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond)
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "scheduled", "status" => "scheduled",
"scheduled_at" => scheduled_at "scheduled_at" => scheduled_at
}) })
@ -299,8 +275,7 @@ test "creates a scheduled activity", %{conn: conn} do
assert [] == Repo.all(Activity) assert [] == Repo.all(Activity)
end end
test "creates a scheduled activity with a media attachment", %{conn: conn} do test "creates a scheduled activity with a media attachment", %{user: user, conn: conn} do
user = insert(:user)
scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond) scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond)
file = %Plug.Upload{ file = %Plug.Upload{
@ -312,9 +287,7 @@ test "creates a scheduled activity with a media attachment", %{conn: conn} do
{:ok, upload} = ActivityPub.upload(file, actor: user.ap_id) {:ok, upload} = ActivityPub.upload(file, actor: user.ap_id)
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"media_ids" => [to_string(upload.id)], "media_ids" => [to_string(upload.id)],
"status" => "scheduled", "status" => "scheduled",
"scheduled_at" => scheduled_at "scheduled_at" => scheduled_at
@ -326,15 +299,11 @@ test "creates a scheduled activity with a media attachment", %{conn: conn} do
test "skips the scheduling and creates the activity if scheduled_at is earlier than 5 minutes from now", test "skips the scheduling and creates the activity if scheduled_at is earlier than 5 minutes from now",
%{conn: conn} do %{conn: conn} do
user = insert(:user)
scheduled_at = scheduled_at =
NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(5) - 1, :millisecond) NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(5) - 1, :millisecond)
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "not scheduled", "status" => "not scheduled",
"scheduled_at" => scheduled_at "scheduled_at" => scheduled_at
}) })
@ -343,9 +312,7 @@ test "skips the scheduling and creates the activity if scheduled_at is earlier t
assert [] == Repo.all(ScheduledActivity) assert [] == Repo.all(ScheduledActivity)
end end
test "returns error when daily user limit is exceeded", %{conn: conn} do test "returns error when daily user limit is exceeded", %{user: user, conn: conn} do
user = insert(:user)
today = today =
NaiveDateTime.utc_now() NaiveDateTime.utc_now()
|> NaiveDateTime.add(:timer.minutes(6), :millisecond) |> NaiveDateTime.add(:timer.minutes(6), :millisecond)
@ -355,17 +322,12 @@ test "returns error when daily user limit is exceeded", %{conn: conn} do
{:ok, _} = ScheduledActivity.create(user, attrs) {:ok, _} = ScheduledActivity.create(user, attrs)
{:ok, _} = ScheduledActivity.create(user, attrs) {:ok, _} = ScheduledActivity.create(user, attrs)
conn = conn = post(conn, "/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => today})
conn
|> assign(:user, user)
|> 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(conn, 422)
end end
test "returns error when total user limit is exceeded", %{conn: conn} do test "returns error when total user limit is exceeded", %{user: user, conn: conn} do
user = insert(:user)
today = today =
NaiveDateTime.utc_now() NaiveDateTime.utc_now()
|> NaiveDateTime.add(:timer.minutes(6), :millisecond) |> NaiveDateTime.add(:timer.minutes(6), :millisecond)
@ -382,23 +344,20 @@ test "returns error when total user limit is exceeded", %{conn: conn} do
{:ok, _} = ScheduledActivity.create(user, %{params: %{}, scheduled_at: tomorrow}) {:ok, _} = ScheduledActivity.create(user, %{params: %{}, scheduled_at: tomorrow})
conn = conn =
conn post(conn, "/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => tomorrow})
|> assign(:user, user)
|> 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(conn, 422)
end end
end end
describe "posting polls" do describe "posting polls" do
setup do: oauth_access(["write:statuses"])
test "posting a poll", %{conn: conn} do test "posting a poll", %{conn: conn} do
user = insert(:user)
time = NaiveDateTime.utc_now() time = NaiveDateTime.utc_now()
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "Who is the #bestgrill?", "status" => "Who is the #bestgrill?",
"poll" => %{"options" => ["Rei", "Asuka", "Misato"], "expires_in" => 420} "poll" => %{"options" => ["Rei", "Asuka", "Misato"], "expires_in" => 420}
}) })
@ -414,13 +373,10 @@ test "posting a poll", %{conn: conn} do
end end
test "option limit is enforced", %{conn: conn} do test "option limit is enforced", %{conn: conn} do
user = insert(:user)
limit = Config.get([:instance, :poll_limits, :max_options]) limit = Config.get([:instance, :poll_limits, :max_options])
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "desu~", "status" => "desu~",
"poll" => %{"options" => Enum.map(0..limit, fn _ -> "desu" end), "expires_in" => 1} "poll" => %{"options" => Enum.map(0..limit, fn _ -> "desu" end), "expires_in" => 1}
}) })
@ -430,13 +386,10 @@ test "option limit is enforced", %{conn: conn} do
end end
test "option character limit is enforced", %{conn: conn} do test "option character limit is enforced", %{conn: conn} do
user = insert(:user)
limit = Config.get([:instance, :poll_limits, :max_option_chars]) limit = Config.get([:instance, :poll_limits, :max_option_chars])
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "...", "status" => "...",
"poll" => %{ "poll" => %{
"options" => [Enum.reduce(0..limit, "", fn _, acc -> acc <> "." end)], "options" => [Enum.reduce(0..limit, "", fn _, acc -> acc <> "." end)],
@ -449,13 +402,10 @@ test "option character limit is enforced", %{conn: conn} do
end end
test "minimal date limit is enforced", %{conn: conn} do test "minimal date limit is enforced", %{conn: conn} do
user = insert(:user)
limit = Config.get([:instance, :poll_limits, :min_expiration]) limit = Config.get([:instance, :poll_limits, :min_expiration])
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "imagine arbitrary limits", "status" => "imagine arbitrary limits",
"poll" => %{ "poll" => %{
"options" => ["this post was made by pleroma gang"], "options" => ["this post was made by pleroma gang"],
@ -468,13 +418,10 @@ test "minimal date limit is enforced", %{conn: conn} do
end end
test "maximum date limit is enforced", %{conn: conn} do test "maximum date limit is enforced", %{conn: conn} do
user = insert(:user)
limit = Config.get([:instance, :poll_limits, :max_expiration]) limit = Config.get([:instance, :poll_limits, :max_expiration])
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "imagine arbitrary limits", "status" => "imagine arbitrary limits",
"poll" => %{ "poll" => %{
"options" => ["this post was made by pleroma gang"], "options" => ["this post was made by pleroma gang"],
@ -487,19 +434,18 @@ test "maximum date limit is enforced", %{conn: conn} do
end end
end end
test "get a status", %{conn: conn} do test "get a status" do
%{conn: conn} = oauth_access(["read:statuses"])
activity = insert(:note_activity) activity = insert(:note_activity)
conn = conn = get(conn, "/api/v1/statuses/#{activity.id}")
conn
|> get("/api/v1/statuses/#{activity.id}")
assert %{"id" => id} = json_response(conn, 200) assert %{"id" => id} = json_response(conn, 200)
assert id == to_string(activity.id) assert id == to_string(activity.id)
end end
test "get a direct status", %{conn: conn} do test "get a direct status" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:statuses"])
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = {:ok, activity} =
@ -516,7 +462,8 @@ test "get a direct status", %{conn: conn} do
assert res["pleroma"]["direct_conversation_id"] == participation.id assert res["pleroma"]["direct_conversation_id"] == participation.id
end end
test "get statuses by IDs", %{conn: conn} do test "get statuses by IDs" do
%{conn: conn} = oauth_access(["read:statuses"])
%{id: id1} = insert(:note_activity) %{id: id1} = insert(:note_activity)
%{id: id2} = insert(:note_activity) %{id: id2} = insert(:note_activity)
@ -527,9 +474,9 @@ test "get statuses by IDs", %{conn: conn} do
end end
describe "deleting a status" do describe "deleting a status" do
test "when you created it", %{conn: conn} do test "when you created it" do
activity = insert(:note_activity) %{user: author, conn: conn} = oauth_access(["write:statuses"])
author = User.get_cached_by_ap_id(activity.data["actor"]) activity = insert(:note_activity, user: author)
conn = conn =
conn conn
@ -541,14 +488,11 @@ test "when you created it", %{conn: conn} do
refute Activity.get_by_id(activity.id) refute Activity.get_by_id(activity.id)
end end
test "when you didn't create it", %{conn: conn} do test "when you didn't create it" do
%{conn: conn} = oauth_access(["write:statuses"])
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
conn = conn = delete(conn, "/api/v1/statuses/#{activity.id}")
conn
|> assign(:user, user)
|> delete("/api/v1/statuses/#{activity.id}")
assert %{"error" => _} = json_response(conn, 403) assert %{"error" => _} = json_response(conn, 403)
@ -564,6 +508,7 @@ test "when you're an admin or moderator", %{conn: conn} do
res_conn = res_conn =
conn conn
|> assign(:user, admin) |> assign(:user, admin)
|> assign(:token, insert(:oauth_token, user: admin, scopes: ["write:statuses"]))
|> delete("/api/v1/statuses/#{activity1.id}") |> delete("/api/v1/statuses/#{activity1.id}")
assert %{} = json_response(res_conn, 200) assert %{} = json_response(res_conn, 200)
@ -571,6 +516,7 @@ test "when you're an admin or moderator", %{conn: conn} do
res_conn = res_conn =
conn conn
|> assign(:user, moderator) |> assign(:user, moderator)
|> assign(:token, insert(:oauth_token, user: moderator, scopes: ["write:statuses"]))
|> delete("/api/v1/statuses/#{activity2.id}") |> delete("/api/v1/statuses/#{activity2.id}")
assert %{} = json_response(res_conn, 200) assert %{} = json_response(res_conn, 200)
@ -581,14 +527,12 @@ test "when you're an admin or moderator", %{conn: conn} do
end end
describe "reblogging" do describe "reblogging" do
setup do: oauth_access(["write:statuses"])
test "reblogs and returns the reblogged status", %{conn: conn} do test "reblogs and returns the reblogged status", %{conn: conn} do
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/reblog")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/reblog")
assert %{ assert %{
"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}, "reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1},
@ -600,12 +544,8 @@ test "reblogs and returns the reblogged status", %{conn: conn} do
test "reblogs privately and returns the reblogged status", %{conn: conn} do test "reblogs privately and returns the reblogged status", %{conn: conn} do
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/reblog", %{"visibility" => "private"})
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/reblog", %{"visibility" => "private"})
assert %{ assert %{
"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}, "reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1},
@ -616,7 +556,7 @@ test "reblogs privately and returns the reblogged status", %{conn: conn} do
assert to_string(activity.id) == id assert to_string(activity.id) == id
end end
test "reblogged status for another user", %{conn: conn} do test "reblogged status for another user" do
activity = insert(:note_activity) activity = insert(:note_activity)
user1 = insert(:user) user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
@ -627,8 +567,9 @@ test "reblogged status for another user", %{conn: conn} do
{:ok, _, _object} = CommonAPI.repeat(activity.id, user2) {:ok, _, _object} = CommonAPI.repeat(activity.id, user2)
conn_res = conn_res =
conn build_conn()
|> assign(:user, user3) |> assign(:user, user3)
|> assign(:token, insert(:oauth_token, user: user3, scopes: ["read:statuses"]))
|> get("/api/v1/statuses/#{reblog_activity1.id}") |> get("/api/v1/statuses/#{reblog_activity1.id}")
assert %{ assert %{
@ -639,8 +580,9 @@ test "reblogged status for another user", %{conn: conn} do
} = json_response(conn_res, 200) } = json_response(conn_res, 200)
conn_res = conn_res =
conn build_conn()
|> assign(:user, user2) |> assign(:user, user2)
|> assign(:token, insert(:oauth_token, user: user2, scopes: ["read:statuses"]))
|> get("/api/v1/statuses/#{reblog_activity1.id}") |> get("/api/v1/statuses/#{reblog_activity1.id}")
assert %{ assert %{
@ -654,28 +596,21 @@ test "reblogged status for another user", %{conn: conn} do
end end
test "returns 400 error when activity is not exist", %{conn: conn} do test "returns 400 error when activity is not exist", %{conn: conn} do
user = insert(:user) conn = post(conn, "/api/v1/statuses/foo/reblog")
conn =
conn
|> assign(:user, user)
|> post("/api/v1/statuses/foo/reblog")
assert json_response(conn, 400) == %{"error" => "Could not repeat"} assert json_response(conn, 400) == %{"error" => "Could not repeat"}
end end
end end
describe "unreblogging" do describe "unreblogging" do
test "unreblogs and returns the unreblogged status", %{conn: conn} do setup do: oauth_access(["write:statuses"])
test "unreblogs and returns the unreblogged status", %{user: user, conn: conn} do
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
{:ok, _, _} = CommonAPI.repeat(activity.id, user) {:ok, _, _} = CommonAPI.repeat(activity.id, user)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/unreblog")
conn
|> assign(:user, user)
|> 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(conn, 200)
@ -683,26 +618,19 @@ test "unreblogs and returns the unreblogged status", %{conn: conn} do
end end
test "returns 400 error when activity is not exist", %{conn: conn} do test "returns 400 error when activity is not exist", %{conn: conn} do
user = insert(:user) conn = post(conn, "/api/v1/statuses/foo/unreblog")
conn =
conn
|> assign(:user, user)
|> post("/api/v1/statuses/foo/unreblog")
assert json_response(conn, 400) == %{"error" => "Could not unrepeat"} assert json_response(conn, 400) == %{"error" => "Could not unrepeat"}
end end
end end
describe "favoriting" do describe "favoriting" do
setup do: oauth_access(["write:favourites"])
test "favs a status and returns it", %{conn: conn} do test "favs a status and returns it", %{conn: conn} do
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/favourite")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/favourite")
assert %{"id" => id, "favourites_count" => 1, "favourited" => true} = assert %{"id" => id, "favourites_count" => 1, "favourited" => true} =
json_response(conn, 200) json_response(conn, 200)
@ -711,28 +639,21 @@ test "favs a status and returns it", %{conn: conn} do
end end
test "returns 400 error for a wrong id", %{conn: conn} do test "returns 400 error for a wrong id", %{conn: conn} do
user = insert(:user) conn = post(conn, "/api/v1/statuses/1/favourite")
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 end
end end
describe "unfavoriting" do describe "unfavoriting" do
test "unfavorites a status and returns it", %{conn: conn} do setup do: oauth_access(["write:favourites"])
test "unfavorites a status and returns it", %{user: user, conn: conn} do
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
{:ok, _, _} = CommonAPI.favorite(activity.id, user) {:ok, _, _} = CommonAPI.favorite(activity.id, user)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/unfavourite")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/unfavourite")
assert %{"id" => id, "favourites_count" => 0, "favourited" => false} = assert %{"id" => id, "favourites_count" => 0, "favourited" => false} =
json_response(conn, 200) json_response(conn, 200)
@ -741,23 +662,19 @@ test "unfavorites a status and returns it", %{conn: conn} do
end end
test "returns 400 error for a wrong id", %{conn: conn} do test "returns 400 error for a wrong id", %{conn: conn} do
user = insert(:user) conn = post(conn, "/api/v1/statuses/1/unfavourite")
conn =
conn
|> assign(:user, user)
|> post("/api/v1/statuses/1/unfavourite")
assert json_response(conn, 400) == %{"error" => "Could not unfavorite"} assert json_response(conn, 400) == %{"error" => "Could not unfavorite"}
end end
end end
describe "pinned statuses" do describe "pinned statuses" do
setup do setup do: oauth_access(["write:accounts"])
user = insert(:user)
setup %{user: user} do
{:ok, activity} = CommonAPI.post(user, %{"status" => "HI!!!"}) {:ok, activity} = CommonAPI.post(user, %{"status" => "HI!!!"})
[user: user, activity: activity] %{activity: activity}
end end
clear_config([:instance, :max_pinned_statuses]) do clear_config([:instance, :max_pinned_statuses]) do
@ -769,13 +686,11 @@ test "pin status", %{conn: conn, user: user, activity: activity} do
assert %{"id" => ^id_str, "pinned" => true} = assert %{"id" => ^id_str, "pinned" => true} =
conn conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/pin") |> post("/api/v1/statuses/#{activity.id}/pin")
|> json_response(200) |> json_response(200)
assert [%{"id" => ^id_str, "pinned" => true}] = assert [%{"id" => ^id_str, "pinned" => true}] =
conn conn
|> assign(:user, user)
|> get("/api/v1/accounts/#{user.id}/statuses?pinned=true") |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true")
|> json_response(200) |> json_response(200)
end end
@ -783,19 +698,16 @@ test "pin status", %{conn: conn, user: user, activity: activity} do
test "/pin: returns 400 error when activity is not public", %{conn: conn, user: user} do test "/pin: returns 400 error when activity is not public", %{conn: conn, user: user} do
{:ok, dm} = CommonAPI.post(user, %{"status" => "test", "visibility" => "direct"}) {:ok, dm} = CommonAPI.post(user, %{"status" => "test", "visibility" => "direct"})
conn = conn = post(conn, "/api/v1/statuses/#{dm.id}/pin")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{dm.id}/pin")
assert json_response(conn, 400) == %{"error" => "Could not pin"} assert json_response(conn, 400) == %{"error" => "Could not pin"}
end end
test "unpin status", %{conn: conn, user: user, activity: activity} do test "unpin status", %{conn: conn, user: user, activity: activity} do
{:ok, _} = CommonAPI.pin(activity.id, user) {:ok, _} = CommonAPI.pin(activity.id, user)
user = refresh_record(user)
id_str = to_string(activity.id) id_str = to_string(activity.id)
user = refresh_record(user)
assert %{"id" => ^id_str, "pinned" => false} = assert %{"id" => ^id_str, "pinned" => false} =
conn conn
@ -805,16 +717,12 @@ test "unpin status", %{conn: conn, user: user, activity: activity} do
assert [] = assert [] =
conn conn
|> assign(:user, user)
|> get("/api/v1/accounts/#{user.id}/statuses?pinned=true") |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true")
|> json_response(200) |> json_response(200)
end end
test "/unpin: returns 400 error when activity is not exist", %{conn: conn, user: user} do test "/unpin: returns 400 error when activity is not exist", %{conn: conn} do
conn = conn = post(conn, "/api/v1/statuses/1/unpin")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/1/unpin")
assert json_response(conn, 400) == %{"error" => "Could not unpin"} assert json_response(conn, 400) == %{"error" => "Could not unpin"}
end end
@ -826,7 +734,6 @@ test "max pinned statuses", %{conn: conn, user: user, activity: activity_one} do
assert %{"id" => ^id_str_one, "pinned" => true} = assert %{"id" => ^id_str_one, "pinned" => true} =
conn conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{id_str_one}/pin") |> post("/api/v1/statuses/#{id_str_one}/pin")
|> json_response(200) |> json_response(200)
@ -844,8 +751,7 @@ test "max pinned statuses", %{conn: conn, user: user, activity: activity_one} do
setup do setup do
Config.put([:rich_media, :enabled], true) Config.put([:rich_media, :enabled], true)
user = insert(:user) oauth_access(["read:statuses"])
%{user: user}
end end
test "returns rich-media card", %{conn: conn, user: user} do test "returns rich-media card", %{conn: conn, user: user} do
@ -887,7 +793,6 @@ test "returns rich-media card", %{conn: conn, user: user} do
response_two = response_two =
conn conn
|> assign(:user, user)
|> get("/api/v1/statuses/#{activity.id}/card") |> get("/api/v1/statuses/#{activity.id}/card")
|> json_response(200) |> json_response(200)
@ -925,72 +830,55 @@ test "replaces missing description with an empty string", %{conn: conn, user: us
end end
test "bookmarks" do test "bookmarks" do
user = insert(:user) %{conn: conn} = oauth_access(["write:bookmarks", "read:bookmarks"])
for_user = insert(:user) author = insert(:user)
{:ok, activity1} = {:ok, activity1} =
CommonAPI.post(user, %{ CommonAPI.post(author, %{
"status" => "heweoo?" "status" => "heweoo?"
}) })
{:ok, activity2} = {:ok, activity2} =
CommonAPI.post(user, %{ CommonAPI.post(author, %{
"status" => "heweoo!" "status" => "heweoo!"
}) })
response1 = response1 = post(conn, "/api/v1/statuses/#{activity1.id}/bookmark")
build_conn()
|> assign(:user, for_user)
|> post("/api/v1/statuses/#{activity1.id}/bookmark")
assert json_response(response1, 200)["bookmarked"] == true assert json_response(response1, 200)["bookmarked"] == true
response2 = response2 = post(conn, "/api/v1/statuses/#{activity2.id}/bookmark")
build_conn()
|> assign(:user, for_user)
|> post("/api/v1/statuses/#{activity2.id}/bookmark")
assert json_response(response2, 200)["bookmarked"] == true assert json_response(response2, 200)["bookmarked"] == true
bookmarks = bookmarks = get(conn, "/api/v1/bookmarks")
build_conn()
|> assign(:user, for_user)
|> get("/api/v1/bookmarks")
assert [json_response(response2, 200), json_response(response1, 200)] == assert [json_response(response2, 200), json_response(response1, 200)] ==
json_response(bookmarks, 200) json_response(bookmarks, 200)
response1 = response1 = post(conn, "/api/v1/statuses/#{activity1.id}/unbookmark")
build_conn()
|> assign(:user, for_user)
|> post("/api/v1/statuses/#{activity1.id}/unbookmark")
assert json_response(response1, 200)["bookmarked"] == false assert json_response(response1, 200)["bookmarked"] == false
bookmarks = bookmarks = get(conn, "/api/v1/bookmarks")
build_conn()
|> assign(:user, for_user)
|> get("/api/v1/bookmarks")
assert [json_response(response2, 200)] == json_response(bookmarks, 200) assert [json_response(response2, 200)] == json_response(bookmarks, 200)
end end
describe "conversation muting" do describe "conversation muting" do
setup do: oauth_access(["write:mutes"])
setup do setup do
post_user = insert(:user) post_user = insert(:user)
user = insert(:user)
{:ok, activity} = CommonAPI.post(post_user, %{"status" => "HIE"}) {:ok, activity} = CommonAPI.post(post_user, %{"status" => "HIE"})
%{activity: activity}
[user: user, activity: activity]
end end
test "mute conversation", %{conn: conn, user: user, activity: activity} do test "mute conversation", %{conn: conn, activity: activity} do
id_str = to_string(activity.id) id_str = to_string(activity.id)
assert %{"id" => ^id_str, "muted" => true} = assert %{"id" => ^id_str, "muted" => true} =
conn conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/mute") |> post("/api/v1/statuses/#{activity.id}/mute")
|> json_response(200) |> json_response(200)
end end
@ -998,10 +886,7 @@ test "mute conversation", %{conn: conn, user: user, activity: activity} do
test "cannot mute already muted conversation", %{conn: conn, user: user, activity: activity} do test "cannot mute already muted conversation", %{conn: conn, user: user, activity: activity} do
{:ok, _} = CommonAPI.add_mute(user, activity) {:ok, _} = CommonAPI.add_mute(user, activity)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/mute")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/mute")
assert json_response(conn, 400) == %{"error" => "conversation is already muted"} assert json_response(conn, 400) == %{"error" => "conversation is already muted"}
end end
@ -1010,11 +895,10 @@ test "unmute conversation", %{conn: conn, user: user, activity: activity} do
{:ok, _} = CommonAPI.add_mute(user, activity) {:ok, _} = CommonAPI.add_mute(user, activity)
id_str = to_string(activity.id) id_str = to_string(activity.id)
user = refresh_record(user)
assert %{"id" => ^id_str, "muted" => false} = assert %{"id" => ^id_str, "muted" => false} =
conn conn
|> assign(:user, user) # |> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/unmute") |> post("/api/v1/statuses/#{activity.id}/unmute")
|> json_response(200) |> json_response(200)
end end
@ -1031,6 +915,7 @@ test "Repeated posts that are replies incorrectly have in_reply_to_id null", %{c
conn1 = conn1 =
conn conn
|> assign(:user, user2) |> assign(:user, user2)
|> assign(:token, insert(:oauth_token, user: user2, scopes: ["write:statuses"]))
|> post("/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => replied_to.id}) |> 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(conn1, 200)
@ -1044,6 +929,7 @@ test "Repeated posts that are replies incorrectly have in_reply_to_id null", %{c
conn2 = conn2 =
conn conn
|> assign(:user, user3) |> assign(:user, user3)
|> assign(:token, insert(:oauth_token, user: user3, scopes: ["write:statuses"]))
|> post("/api/v1/statuses/#{activity.id}/reblog") |> post("/api/v1/statuses/#{activity.id}/reblog")
assert %{"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}} = assert %{"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}} =
@ -1055,6 +941,7 @@ test "Repeated posts that are replies incorrectly have in_reply_to_id null", %{c
conn3 = conn3 =
conn conn
|> assign(:user, user3) |> assign(:user, user3)
|> assign(:token, insert(:oauth_token, user: user3, scopes: ["read:statuses"]))
|> get("api/v1/timelines/home") |> get("api/v1/timelines/home")
[reblogged_activity] = json_response(conn3, 200) [reblogged_activity] = json_response(conn3, 200)
@ -1066,15 +953,12 @@ test "Repeated posts that are replies incorrectly have in_reply_to_id null", %{c
end end
describe "GET /api/v1/statuses/:id/favourited_by" do describe "GET /api/v1/statuses/:id/favourited_by" do
setup do setup do: oauth_access(["read:accounts"])
user = insert(:user)
setup %{user: user} do
{:ok, activity} = CommonAPI.post(user, %{"status" => "test"}) {:ok, activity} = CommonAPI.post(user, %{"status" => "test"})
conn = %{activity: activity}
build_conn()
|> assign(:user, user)
[conn: conn, activity: activity, user: user]
end end
test "returns users who have favorited the status", %{conn: conn, activity: activity} do test "returns users who have favorited the status", %{conn: conn, activity: activity} do
@ -1114,20 +998,18 @@ test "does not return users who have favorited the status but are blocked", %{
response = response =
conn conn
|> assign(:user, user)
|> get("/api/v1/statuses/#{activity.id}/favourited_by") |> get("/api/v1/statuses/#{activity.id}/favourited_by")
|> json_response(:ok) |> json_response(:ok)
assert Enum.empty?(response) assert Enum.empty?(response)
end end
test "does not fail on an unauthenticated request", %{conn: conn, activity: activity} do test "does not fail on an unauthenticated request", %{activity: activity} do
other_user = insert(:user) other_user = insert(:user)
{:ok, _, _} = CommonAPI.favorite(activity.id, other_user) {:ok, _, _} = CommonAPI.favorite(activity.id, other_user)
response = response =
conn build_conn()
|> assign(:user, nil)
|> get("/api/v1/statuses/#{activity.id}/favourited_by") |> get("/api/v1/statuses/#{activity.id}/favourited_by")
|> json_response(:ok) |> json_response(:ok)
@ -1135,7 +1017,7 @@ test "does not fail on an unauthenticated request", %{conn: conn, activity: acti
assert id == other_user.id assert id == other_user.id
end end
test "requires authentification for private posts", %{conn: conn, user: user} do test "requires authentication for private posts", %{user: user} do
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = {:ok, activity} =
@ -1146,15 +1028,25 @@ test "requires authentification for private posts", %{conn: conn, user: user} do
{:ok, _, _} = CommonAPI.favorite(activity.id, other_user) {:ok, _, _} = CommonAPI.favorite(activity.id, other_user)
favourited_by_url = "/api/v1/statuses/#{activity.id}/favourited_by"
build_conn()
|> get(favourited_by_url)
|> json_response(404)
conn =
build_conn()
|> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"]))
conn conn
|> assign(:user, nil) |> assign(:token, nil)
|> get("/api/v1/statuses/#{activity.id}/favourited_by") |> get(favourited_by_url)
|> json_response(404) |> json_response(404)
response = response =
build_conn() conn
|> assign(:user, other_user) |> get(favourited_by_url)
|> get("/api/v1/statuses/#{activity.id}/favourited_by")
|> json_response(200) |> json_response(200)
[%{"id" => id}] = response [%{"id" => id}] = response
@ -1163,15 +1055,12 @@ test "requires authentification for private posts", %{conn: conn, user: user} do
end end
describe "GET /api/v1/statuses/:id/reblogged_by" do describe "GET /api/v1/statuses/:id/reblogged_by" do
setup do setup do: oauth_access(["read:accounts"])
user = insert(:user)
setup %{user: user} do
{:ok, activity} = CommonAPI.post(user, %{"status" => "test"}) {:ok, activity} = CommonAPI.post(user, %{"status" => "test"})
conn = %{activity: activity}
build_conn()
|> assign(:user, user)
[conn: conn, activity: activity, user: user]
end end
test "returns users who have reblogged the status", %{conn: conn, activity: activity} do test "returns users who have reblogged the status", %{conn: conn, activity: activity} do
@ -1211,7 +1100,6 @@ test "does not return users who have reblogged the status but are blocked", %{
response = response =
conn conn
|> assign(:user, user)
|> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> get("/api/v1/statuses/#{activity.id}/reblogged_by")
|> json_response(:ok) |> json_response(:ok)
@ -1219,7 +1107,7 @@ test "does not return users who have reblogged the status but are blocked", %{
end end
test "does not return users who have reblogged the status privately", %{ test "does not return users who have reblogged the status privately", %{
conn: %{assigns: %{user: user}} = conn, conn: conn,
activity: activity activity: activity
} do } do
other_user = insert(:user) other_user = insert(:user)
@ -1228,20 +1116,18 @@ test "does not return users who have reblogged the status privately", %{
response = response =
conn conn
|> assign(:user, user)
|> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> get("/api/v1/statuses/#{activity.id}/reblogged_by")
|> json_response(:ok) |> json_response(:ok)
assert Enum.empty?(response) assert Enum.empty?(response)
end end
test "does not fail on an unauthenticated request", %{conn: conn, activity: activity} do test "does not fail on an unauthenticated request", %{activity: activity} do
other_user = insert(:user) other_user = insert(:user)
{:ok, _, _} = CommonAPI.repeat(activity.id, other_user) {:ok, _, _} = CommonAPI.repeat(activity.id, other_user)
response = response =
conn build_conn()
|> assign(:user, nil)
|> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> get("/api/v1/statuses/#{activity.id}/reblogged_by")
|> json_response(:ok) |> json_response(:ok)
@ -1249,7 +1135,7 @@ test "does not fail on an unauthenticated request", %{conn: conn, activity: acti
assert id == other_user.id assert id == other_user.id
end end
test "requires authentification for private posts", %{conn: conn, user: user} do test "requires authentication for private posts", %{user: user} do
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = {:ok, activity} =
@ -1258,14 +1144,14 @@ test "requires authentification for private posts", %{conn: conn, user: user} do
"visibility" => "direct" "visibility" => "direct"
}) })
conn build_conn()
|> assign(:user, nil)
|> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> get("/api/v1/statuses/#{activity.id}/reblogged_by")
|> json_response(404) |> json_response(404)
response = response =
build_conn() build_conn()
|> assign(:user, other_user) |> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"]))
|> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> get("/api/v1/statuses/#{activity.id}/reblogged_by")
|> json_response(200) |> json_response(200)
@ -1284,7 +1170,6 @@ test "context" do
response = response =
build_conn() build_conn()
|> assign(:user, nil)
|> get("/api/v1/statuses/#{id3}/context") |> get("/api/v1/statuses/#{id3}/context")
|> json_response(:ok) |> json_response(:ok)
@ -1294,8 +1179,8 @@ test "context" do
} = response } = response
end end
test "returns the favorites of a user", %{conn: conn} do test "returns the favorites of a user" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:favourites"])
other_user = insert(:user) other_user = insert(:user)
{:ok, _} = CommonAPI.post(other_user, %{"status" => "bla"}) {:ok, _} = CommonAPI.post(other_user, %{"status" => "bla"})
@ -1303,10 +1188,7 @@ test "returns the favorites of a user", %{conn: conn} do
{:ok, _, _} = CommonAPI.favorite(activity.id, user) {:ok, _, _} = CommonAPI.favorite(activity.id, user)
first_conn = first_conn = get(conn, "/api/v1/favourites")
conn
|> assign(:user, user)
|> get("/api/v1/favourites")
assert [status] = json_response(first_conn, 200) assert [status] = json_response(first_conn, 200)
assert status["id"] == to_string(activity.id) assert status["id"] == to_string(activity.id)
@ -1325,18 +1207,12 @@ test "returns the favorites of a user", %{conn: conn} do
last_like = status["id"] last_like = status["id"]
second_conn = second_conn = get(conn, "/api/v1/favourites?since_id=#{last_like}")
conn
|> assign(:user, user)
|> get("/api/v1/favourites?since_id=#{last_like}")
assert [second_status] = json_response(second_conn, 200) assert [second_status] = json_response(second_conn, 200)
assert second_status["id"] == to_string(second_activity.id) assert second_status["id"] == to_string(second_activity.id)
third_conn = third_conn = get(conn, "/api/v1/favourites?limit=0")
conn
|> assign(:user, user)
|> get("/api/v1/favourites?limit=0")
assert [] = json_response(third_conn, 200) assert [] = json_response(third_conn, 200)
end end

View file

@ -11,8 +11,9 @@ defmodule Pleroma.Web.MastodonAPI.SuggestionControllerTest do
import Pleroma.Factory import Pleroma.Factory
import Tesla.Mock import Tesla.Mock
setup do setup do: oauth_access(["read"])
user = insert(:user)
setup %{user: user} do
other_user = insert(:user) other_user = insert(:user)
host = Config.get([Pleroma.Web.Endpoint, :url, :host]) host = Config.get([Pleroma.Web.Endpoint, :url, :host])
url500 = "http://test500?#{host}&#{user.nickname}" url500 = "http://test500?#{host}&#{user.nickname}"
@ -32,31 +33,29 @@ defmodule Pleroma.Web.MastodonAPI.SuggestionControllerTest do
} }
end) end)
[user: user, other_user: other_user] [other_user: other_user]
end end
clear_config(:suggestions) clear_config(:suggestions)
test "returns empty result when suggestions disabled", %{conn: conn, user: user} do test "returns empty result when suggestions disabled", %{conn: conn} do
Config.put([:suggestions, :enabled], false) Config.put([:suggestions, :enabled], false)
res = res =
conn conn
|> assign(:user, user)
|> get("/api/v1/suggestions") |> get("/api/v1/suggestions")
|> json_response(200) |> json_response(200)
assert res == [] assert res == []
end end
test "returns error", %{conn: conn, user: user} do test "returns error", %{conn: conn} do
Config.put([:suggestions, :enabled], true) Config.put([:suggestions, :enabled], true)
Config.put([:suggestions, :third_party_engine], "http://test500?{{host}}&{{user}}") Config.put([:suggestions, :third_party_engine], "http://test500?{{host}}&{{user}}")
assert capture_log(fn -> assert capture_log(fn ->
res = res =
conn conn
|> assign(:user, user)
|> get("/api/v1/suggestions") |> get("/api/v1/suggestions")
|> json_response(500) |> json_response(500)
@ -64,13 +63,12 @@ test "returns error", %{conn: conn, user: user} do
end) =~ "Could not retrieve suggestions" end) =~ "Could not retrieve suggestions"
end end
test "returns suggestions", %{conn: conn, user: user, other_user: other_user} do test "returns suggestions", %{conn: conn, other_user: other_user} do
Config.put([:suggestions, :enabled], true) Config.put([:suggestions, :enabled], true)
Config.put([:suggestions, :third_party_engine], "http://test200?{{host}}&{{user}}") Config.put([:suggestions, :third_party_engine], "http://test200?{{host}}&{{user}}")
res = res =
conn conn
|> assign(:user, user)
|> get("/api/v1/suggestions") |> get("/api/v1/suggestions")
|> json_response(200) |> json_response(200)

View file

@ -20,31 +20,25 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do
end end
describe "home" do describe "home" do
test "the home timeline", %{conn: conn} do setup do: oauth_access(["read:statuses"])
user = insert(:user)
test "the home timeline", %{user: user, conn: conn} do
following = insert(:user) following = insert(:user)
{:ok, _activity} = CommonAPI.post(following, %{"status" => "test"}) {:ok, _activity} = CommonAPI.post(following, %{"status" => "test"})
conn = ret_conn = get(conn, "/api/v1/timelines/home")
conn
|> assign(:user, user)
|> get("/api/v1/timelines/home")
assert Enum.empty?(json_response(conn, :ok)) assert Enum.empty?(json_response(ret_conn, :ok))
{:ok, user} = User.follow(user, following) {:ok, _user} = User.follow(user, following)
conn = conn = get(conn, "/api/v1/timelines/home")
build_conn()
|> assign(:user, user)
|> get("/api/v1/timelines/home")
assert [%{"content" => "test"}] = json_response(conn, :ok) assert [%{"content" => "test"}] = json_response(conn, :ok)
end end
test "the home timeline when the direct messages are excluded", %{conn: conn} do test "the home timeline when the direct messages are excluded", %{user: user, conn: conn} 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"})
@ -54,10 +48,7 @@ test "the home timeline when the direct messages are excluded", %{conn: conn} do
{:ok, private_activity} = {:ok, private_activity} =
CommonAPI.post(user, %{"status" => ".", "visibility" => "private"}) CommonAPI.post(user, %{"status" => ".", "visibility" => "private"})
conn = conn = get(conn, "/api/v1/timelines/home", %{"exclude_visibilities" => ["direct"]})
conn
|> assign(:user, user)
|> get("/api/v1/timelines/home", %{"exclude_visibilities" => ["direct"]})
assert status_ids = json_response(conn, :ok) |> Enum.map(& &1["id"]) assert status_ids = json_response(conn, :ok) |> Enum.map(& &1["id"])
assert public_activity.id in status_ids assert public_activity.id in status_ids
@ -99,11 +90,7 @@ test "the public timeline when public is set to false", %{conn: conn} do
end end
test "the public timeline includes only public statuses for an authenticated user" do test "the public timeline includes only public statuses for an authenticated user" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:statuses"])
conn =
build_conn()
|> assign(:user, user)
{:ok, _activity} = CommonAPI.post(user, %{"status" => "test"}) {:ok, _activity} = CommonAPI.post(user, %{"status" => "test"})
{:ok, _activity} = CommonAPI.post(user, %{"status" => "test", "visibility" => "private"}) {:ok, _activity} = CommonAPI.post(user, %{"status" => "test", "visibility" => "private"})
@ -134,11 +121,13 @@ test "direct timeline", %{conn: conn} do
"visibility" => "private" "visibility" => "private"
}) })
# Only direct should be visible here conn_user_two =
res_conn =
conn conn
|> assign(:user, user_two) |> assign(:user, user_two)
|> get("api/v1/timelines/direct") |> assign(:token, insert(:oauth_token, user: user_two, scopes: ["read:statuses"]))
# Only direct should be visible here
res_conn = get(conn_user_two, "api/v1/timelines/direct")
[status] = json_response(res_conn, :ok) [status] = json_response(res_conn, :ok)
@ -149,6 +138,7 @@ test "direct timeline", %{conn: conn} do
res_conn = res_conn =
build_conn() build_conn()
|> assign(:user, user_one) |> assign(:user, user_one)
|> assign(:token, insert(:oauth_token, user: user_one, scopes: ["read:statuses"]))
|> get("api/v1/timelines/direct") |> get("api/v1/timelines/direct")
[status] = json_response(res_conn, :ok) [status] = json_response(res_conn, :ok)
@ -156,10 +146,7 @@ test "direct timeline", %{conn: conn} do
assert %{"visibility" => "direct"} = status assert %{"visibility" => "direct"} = status
# Both should be visible here # Both should be visible here
res_conn = res_conn = get(conn_user_two, "api/v1/timelines/home")
conn
|> assign(:user, user_two)
|> get("api/v1/timelines/home")
[_s1, _s2] = json_response(res_conn, :ok) [_s1, _s2] = json_response(res_conn, :ok)
@ -172,28 +159,23 @@ test "direct timeline", %{conn: conn} do
}) })
end) end)
res_conn = res_conn = get(conn_user_two, "api/v1/timelines/direct")
conn
|> assign(:user, user_two)
|> get("api/v1/timelines/direct")
statuses = json_response(res_conn, :ok) statuses = json_response(res_conn, :ok)
assert length(statuses) == 20 assert length(statuses) == 20
res_conn = res_conn =
conn get(conn_user_two, "api/v1/timelines/direct", %{max_id: List.last(statuses)["id"]})
|> assign(:user, user_two)
|> get("api/v1/timelines/direct", %{max_id: List.last(statuses)["id"]})
[status] = json_response(res_conn, :ok) [status] = json_response(res_conn, :ok)
assert status["url"] != direct.data["id"] assert status["url"] != direct.data["id"]
end end
test "doesn't include DMs from blocked users", %{conn: conn} do test "doesn't include DMs from blocked users" do
blocker = insert(:user) %{user: blocker, conn: conn} = oauth_access(["read:statuses"])
blocked = insert(:user) blocked = insert(:user)
user = insert(:user) other_user = insert(:user)
{:ok, _user_relationship} = User.block(blocker, blocked) {:ok, _user_relationship} = User.block(blocker, blocked)
{:ok, _blocked_direct} = {:ok, _blocked_direct} =
@ -203,15 +185,12 @@ test "doesn't include DMs from blocked users", %{conn: conn} do
}) })
{:ok, direct} = {:ok, direct} =
CommonAPI.post(user, %{ CommonAPI.post(other_user, %{
"status" => "Hi @#{blocker.nickname}!", "status" => "Hi @#{blocker.nickname}!",
"visibility" => "direct" "visibility" => "direct"
}) })
res_conn = res_conn = get(conn, "api/v1/timelines/direct")
conn
|> assign(:user, user)
|> get("api/v1/timelines/direct")
[status] = json_response(res_conn, :ok) [status] = json_response(res_conn, :ok)
assert status["id"] == direct.id assert status["id"] == direct.id
@ -219,26 +198,26 @@ test "doesn't include DMs from blocked users", %{conn: conn} do
end end
describe "list" do describe "list" do
test "list timeline", %{conn: conn} do setup do: oauth_access(["read:lists"])
user = insert(:user)
test "list timeline", %{user: user, conn: conn} do
other_user = insert(:user) other_user = insert(:user)
{:ok, _activity_one} = CommonAPI.post(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, activity_two} = CommonAPI.post(other_user, %{"status" => "Marisa is cute."})
{:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.create("name", user)
{:ok, list} = Pleroma.List.follow(list, other_user) {:ok, list} = Pleroma.List.follow(list, other_user)
conn = conn = get(conn, "/api/v1/timelines/list/#{list.id}")
conn
|> assign(:user, user)
|> get("/api/v1/timelines/list/#{list.id}")
assert [%{"id" => id}] = json_response(conn, :ok) assert [%{"id" => id}] = json_response(conn, :ok)
assert id == to_string(activity_two.id) assert id == to_string(activity_two.id)
end end
test "list timeline does not leak non-public statuses for unfollowed users", %{conn: conn} do test "list timeline does not leak non-public statuses for unfollowed users", %{
user = insert(:user) user: user,
conn: conn
} do
other_user = insert(:user) 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."})
@ -251,10 +230,7 @@ test "list timeline does not leak non-public statuses for unfollowed users", %{c
{:ok, list} = Pleroma.List.create("name", user) {:ok, list} = Pleroma.List.create("name", user)
{:ok, list} = Pleroma.List.follow(list, other_user) {:ok, list} = Pleroma.List.follow(list, other_user)
conn = conn = get(conn, "/api/v1/timelines/list/#{list.id}")
conn
|> assign(:user, user)
|> get("/api/v1/timelines/list/#{list.id}")
assert [%{"id" => id}] = json_response(conn, :ok) assert [%{"id" => id}] = json_response(conn, :ok)
@ -263,6 +239,8 @@ test "list timeline does not leak non-public statuses for unfollowed users", %{c
end end
describe "hashtag" do describe "hashtag" do
setup do: oauth_access(["n/a"])
@tag capture_log: true @tag capture_log: true
test "hashtag timeline", %{conn: conn} do test "hashtag timeline", %{conn: conn} do
following = insert(:user) following = insert(:user)

View file

@ -5,69 +5,9 @@
defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do
use Pleroma.Web.ConnCase use Pleroma.Web.ConnCase
alias Pleroma.Notification describe "empty_array/2 (stubs)" do
alias Pleroma.Repo test "GET /api/v1/accounts/:id/identity_proofs" do
alias Pleroma.Web.CommonAPI %{user: user, conn: conn} = oauth_access(["n/a"])
import Pleroma.Factory
import Tesla.Mock
setup do
mock(fn env -> apply(HttpRequestMock, :request, [env]) end)
:ok
end
clear_config([:rich_media, :enabled])
test "unimplemented follow_requests, blocks, domain blocks" do
user = insert(:user)
["blocks", "domain_blocks", "follow_requests"]
|> Enum.each(fn endpoint ->
conn =
build_conn()
|> assign(:user, user)
|> get("/api/v1/#{endpoint}")
assert [] = json_response(conn, 200)
end)
end
describe "link headers" do
test "preserves parameters in link headers", %{conn: conn} do
user = insert(:user)
other_user = insert(:user)
{:ok, activity1} =
CommonAPI.post(other_user, %{
"status" => "hi @#{user.nickname}",
"visibility" => "public"
})
{:ok, activity2} =
CommonAPI.post(other_user, %{
"status" => "hi @#{user.nickname}",
"visibility" => "public"
})
notification1 = Repo.get_by(Notification, activity_id: activity1.id)
notification2 = Repo.get_by(Notification, activity_id: activity2.id)
conn =
conn
|> assign(:user, user)
|> get("/api/v1/notifications", %{media_only: true})
assert [link_header] = get_resp_header(conn, "link")
assert link_header =~ ~r/media_only=true/
assert link_header =~ ~r/min_id=#{notification2.id}/
assert link_header =~ ~r/max_id=#{notification1.id}/
end
end
describe "empty_array, stubs for mastodon api" do
test "GET /api/v1/accounts/:id/identity_proofs", %{conn: conn} do
user = insert(:user)
res = res =
conn conn
@ -78,12 +18,11 @@ test "GET /api/v1/accounts/:id/identity_proofs", %{conn: conn} do
assert res == [] assert res == []
end end
test "GET /api/v1/endorsements", %{conn: conn} do test "GET /api/v1/endorsements" do
user = insert(:user) %{conn: conn} = oauth_access(["read:accounts"])
res = res =
conn conn
|> assign(:user, user)
|> get("/api/v1/endorsements") |> get("/api/v1/endorsements")
|> json_response(200) |> json_response(200)
@ -91,11 +30,8 @@ test "GET /api/v1/endorsements", %{conn: conn} do
end end
test "GET /api/v1/trends", %{conn: conn} do test "GET /api/v1/trends", %{conn: conn} do
user = insert(:user)
res = res =
conn conn
|> assign(:user, user)
|> get("/api/v1/trends") |> get("/api/v1/trends")
|> json_response(200) |> json_response(200)

View file

@ -450,7 +450,7 @@ test "properly handles internal calls with `authorization`-wrapped params", %{
test "renders authentication page if user is already authenticated but `force_login` is tru-ish", test "renders authentication page if user is already authenticated but `force_login` is tru-ish",
%{app: app, conn: conn} do %{app: app, conn: conn} do
token = insert(:oauth_token, app_id: app.id) token = insert(:oauth_token, app: app)
conn = conn =
conn conn
@ -474,7 +474,7 @@ test "renders authentication page if user is already authenticated but user requ
app: app, app: app,
conn: conn conn: conn
} do } do
token = insert(:oauth_token, app_id: app.id) token = insert(:oauth_token, app: app)
conn = conn =
conn conn
@ -497,7 +497,7 @@ test "with existing authentication and non-OOB `redirect_uri`, redirects to app
app: app, app: app,
conn: conn conn: conn
} do } do
token = insert(:oauth_token, app_id: app.id) token = insert(:oauth_token, app: app)
conn = conn =
conn conn
@ -523,7 +523,7 @@ test "with existing authentication and unlisted non-OOB `redirect_uri`, redirect
conn: conn conn: conn
} do } do
unlisted_redirect_uri = "http://cross-site-request.com" unlisted_redirect_uri = "http://cross-site-request.com"
token = insert(:oauth_token, app_id: app.id) token = insert(:oauth_token, app: app)
conn = conn =
conn conn
@ -547,7 +547,7 @@ test "with existing authentication and OOB `redirect_uri`, redirects to app with
app: app, app: app,
conn: conn conn: conn
} do } do
token = insert(:oauth_token, app_id: app.id) token = insert(:oauth_token, app: app)
conn = conn =
conn conn

View file

@ -33,7 +33,6 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do
test "resend account confirmation email", %{conn: conn, user: user} do test "resend account confirmation email", %{conn: conn, user: user} do
conn conn
|> assign(:user, user)
|> post("/api/v1/pleroma/accounts/confirmation_resend?email=#{user.email}") |> post("/api/v1/pleroma/accounts/confirmation_resend?email=#{user.email}")
|> json_response(:no_content) |> json_response(:no_content)
@ -52,14 +51,12 @@ test "resend account confirmation email", %{conn: conn, user: user} do
end end
describe "PATCH /api/v1/pleroma/accounts/update_avatar" do describe "PATCH /api/v1/pleroma/accounts/update_avatar" do
test "user avatar can be set", %{conn: conn} do setup do: oauth_access(["write:accounts"])
user = insert(:user)
test "user avatar can be set", %{user: user, conn: conn} do
avatar_image = File.read!("test/fixtures/avatar_data_uri") avatar_image = File.read!("test/fixtures/avatar_data_uri")
conn = conn = patch(conn, "/api/v1/pleroma/accounts/update_avatar", %{img: avatar_image})
conn
|> assign(:user, user)
|> patch("/api/v1/pleroma/accounts/update_avatar", %{img: avatar_image})
user = refresh_record(user) user = refresh_record(user)
@ -78,13 +75,8 @@ test "user avatar can be set", %{conn: conn} do
assert %{"url" => _} = json_response(conn, 200) assert %{"url" => _} = json_response(conn, 200)
end end
test "user avatar can be reset", %{conn: conn} do test "user avatar can be reset", %{user: user, conn: conn} do
user = insert(:user) conn = patch(conn, "/api/v1/pleroma/accounts/update_avatar", %{img: ""})
conn =
conn
|> assign(:user, user)
|> patch("/api/v1/pleroma/accounts/update_avatar", %{img: ""})
user = User.get_cached_by_id(user.id) user = User.get_cached_by_id(user.id)
@ -95,13 +87,10 @@ test "user avatar can be reset", %{conn: conn} do
end end
describe "PATCH /api/v1/pleroma/accounts/update_banner" do describe "PATCH /api/v1/pleroma/accounts/update_banner" do
test "can set profile banner", %{conn: conn} do setup do: oauth_access(["write:accounts"])
user = insert(:user)
conn = test "can set profile banner", %{user: user, conn: conn} do
conn conn = patch(conn, "/api/v1/pleroma/accounts/update_banner", %{"banner" => @image})
|> assign(:user, user)
|> patch("/api/v1/pleroma/accounts/update_banner", %{"banner" => @image})
user = refresh_record(user) user = refresh_record(user)
assert user.banner["type"] == "Image" assert user.banner["type"] == "Image"
@ -109,13 +98,8 @@ test "can set profile banner", %{conn: conn} do
assert %{"url" => _} = json_response(conn, 200) assert %{"url" => _} = json_response(conn, 200)
end end
test "can reset profile banner", %{conn: conn} do test "can reset profile banner", %{user: user, conn: conn} do
user = insert(:user) conn = patch(conn, "/api/v1/pleroma/accounts/update_banner", %{"banner" => ""})
conn =
conn
|> assign(:user, user)
|> patch("/api/v1/pleroma/accounts/update_banner", %{"banner" => ""})
user = refresh_record(user) user = refresh_record(user)
assert user.banner == %{} assert user.banner == %{}
@ -125,26 +109,18 @@ test "can reset profile banner", %{conn: conn} do
end end
describe "PATCH /api/v1/pleroma/accounts/update_background" do describe "PATCH /api/v1/pleroma/accounts/update_background" do
test "background image can be set", %{conn: conn} do setup do: oauth_access(["write:accounts"])
user = insert(:user)
conn = test "background image can be set", %{user: user, conn: conn} do
conn conn = patch(conn, "/api/v1/pleroma/accounts/update_background", %{"img" => @image})
|> assign(:user, user)
|> patch("/api/v1/pleroma/accounts/update_background", %{"img" => @image})
user = refresh_record(user) user = refresh_record(user)
assert user.background["type"] == "Image" assert user.background["type"] == "Image"
assert %{"url" => _} = json_response(conn, 200) assert %{"url" => _} = json_response(conn, 200)
end end
test "background image can be reset", %{conn: conn} do test "background image can be reset", %{user: user, conn: conn} do
user = insert(:user) conn = patch(conn, "/api/v1/pleroma/accounts/update_background", %{"img" => ""})
conn =
conn
|> assign(:user, user)
|> patch("/api/v1/pleroma/accounts/update_background", %{"img" => ""})
user = refresh_record(user) user = refresh_record(user)
assert user.background == %{} assert user.background == %{}
@ -155,12 +131,12 @@ test "background image can be reset", %{conn: conn} do
describe "getting favorites timeline of specified user" do describe "getting favorites timeline of specified user" do
setup do setup do
[current_user, user] = insert_pair(:user, hide_favorites: false) [current_user, user] = insert_pair(:user, hide_favorites: false)
[current_user: current_user, user: user] %{user: current_user, conn: conn} = oauth_access(["read:favourites"], user: current_user)
[current_user: current_user, user: user, conn: conn]
end end
test "returns list of statuses favorited by specified user", %{ test "returns list of statuses favorited by specified user", %{
conn: conn, conn: conn,
current_user: current_user,
user: user user: user
} do } do
[activity | _] = insert_pair(:note_activity) [activity | _] = insert_pair(:note_activity)
@ -168,7 +144,6 @@ test "returns list of statuses favorited by specified user", %{
response = response =
conn conn
|> assign(:user, current_user)
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites") |> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
|> json_response(:ok) |> json_response(:ok)
@ -178,23 +153,18 @@ test "returns list of statuses favorited by specified user", %{
assert like["id"] == activity.id assert like["id"] == activity.id
end end
test "returns favorites for specified user_id when user is not logged in", %{ test "does not return favorites for specified user_id when user is not logged in", %{
conn: conn,
user: user user: user
} do } do
activity = insert(:note_activity) activity = insert(:note_activity)
CommonAPI.favorite(activity.id, user) CommonAPI.favorite(activity.id, user)
response = build_conn()
conn
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites") |> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
|> json_response(:ok) |> json_response(403)
assert length(response) == 1
end end
test "returns favorited DM only when user is logged in and he is one of recipients", %{ test "returns favorited DM only when user is logged in and he is one of recipients", %{
conn: conn,
current_user: current_user, current_user: current_user,
user: user user: user
} do } do
@ -206,25 +176,24 @@ test "returns favorited DM only when user is logged in and he is one of recipien
CommonAPI.favorite(direct.id, user) CommonAPI.favorite(direct.id, user)
for u <- [user, current_user] do
response = response =
conn build_conn()
|> assign(:user, current_user) |> assign(:user, u)
|> assign(:token, insert(:oauth_token, user: u, scopes: ["read:favourites"]))
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites") |> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
|> json_response(:ok) |> json_response(:ok)
assert length(response) == 1 assert length(response) == 1
end
anonymous_response = build_conn()
conn
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites") |> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
|> json_response(:ok) |> json_response(403)
assert Enum.empty?(anonymous_response)
end end
test "does not return others' favorited DM when user is not one of recipients", %{ test "does not return others' favorited DM when user is not one of recipients", %{
conn: conn, conn: conn,
current_user: current_user,
user: user user: user
} do } do
user_two = insert(:user) user_two = insert(:user)
@ -239,7 +208,6 @@ test "does not return others' favorited DM when user is not one of recipients",
response = response =
conn conn
|> assign(:user, current_user)
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites") |> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
|> json_response(:ok) |> json_response(:ok)
@ -248,7 +216,6 @@ test "does not return others' favorited DM when user is not one of recipients",
test "paginates favorites using since_id and max_id", %{ test "paginates favorites using since_id and max_id", %{
conn: conn, conn: conn,
current_user: current_user,
user: user user: user
} do } do
activities = insert_list(10, :note_activity) activities = insert_list(10, :note_activity)
@ -262,7 +229,6 @@ test "paginates favorites using since_id and max_id", %{
response = response =
conn conn
|> assign(:user, current_user)
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites", %{ |> get("/api/v1/pleroma/accounts/#{user.id}/favourites", %{
since_id: third_activity.id, since_id: third_activity.id,
max_id: seventh_activity.id max_id: seventh_activity.id
@ -276,7 +242,6 @@ test "paginates favorites using since_id and max_id", %{
test "limits favorites using limit parameter", %{ test "limits favorites using limit parameter", %{
conn: conn, conn: conn,
current_user: current_user,
user: user user: user
} do } do
7 7
@ -287,7 +252,6 @@ test "limits favorites using limit parameter", %{
response = response =
conn conn
|> assign(:user, current_user)
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites", %{limit: "3"}) |> get("/api/v1/pleroma/accounts/#{user.id}/favourites", %{limit: "3"})
|> json_response(:ok) |> json_response(:ok)
@ -296,12 +260,10 @@ test "limits favorites using limit parameter", %{
test "returns empty response when user does not have any favorited statuses", %{ test "returns empty response when user does not have any favorited statuses", %{
conn: conn, conn: conn,
current_user: current_user,
user: user user: user
} do } do
response = response =
conn conn
|> assign(:user, current_user)
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites") |> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
|> json_response(:ok) |> json_response(:ok)
@ -314,79 +276,61 @@ test "returns 404 error when specified user is not exist", %{conn: conn} do
assert json_response(conn, 404) == %{"error" => "Record not found"} assert json_response(conn, 404) == %{"error" => "Record not found"}
end end
test "returns 403 error when user has hidden own favorites", %{ test "returns 403 error when user has hidden own favorites", %{conn: conn} do
conn: conn,
current_user: current_user
} do
user = insert(:user, hide_favorites: true) user = insert(:user, hide_favorites: true)
activity = insert(:note_activity) activity = insert(:note_activity)
CommonAPI.favorite(activity.id, user) CommonAPI.favorite(activity.id, user)
conn = conn = get(conn, "/api/v1/pleroma/accounts/#{user.id}/favourites")
conn
|> assign(:user, current_user)
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
assert json_response(conn, 403) == %{"error" => "Can't get favorites"} assert json_response(conn, 403) == %{"error" => "Can't get favorites"}
end end
test "hides favorites for new users by default", %{conn: conn, current_user: current_user} do test "hides favorites for new users by default", %{conn: conn} do
user = insert(:user) user = insert(:user)
activity = insert(:note_activity) activity = insert(:note_activity)
CommonAPI.favorite(activity.id, user) CommonAPI.favorite(activity.id, user)
conn =
conn
|> assign(:user, current_user)
|> get("/api/v1/pleroma/accounts/#{user.id}/favourites")
assert user.hide_favorites 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(conn, 403) == %{"error" => "Can't get favorites"}
end end
end end
describe "subscribing / unsubscribing" do describe "subscribing / unsubscribing" do
test "subscribing / unsubscribing to a user", %{conn: conn} do test "subscribing / unsubscribing to a user" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["follow"])
subscription_target = insert(:user) subscription_target = insert(:user)
conn = ret_conn =
conn conn
|> assign(:user, user) |> assign(:user, user)
|> post("/api/v1/pleroma/accounts/#{subscription_target.id}/subscribe") |> post("/api/v1/pleroma/accounts/#{subscription_target.id}/subscribe")
assert %{"id" => _id, "subscribing" => true} = json_response(conn, 200) assert %{"id" => _id, "subscribing" => true} = json_response(ret_conn, 200)
conn = conn = post(conn, "/api/v1/pleroma/accounts/#{subscription_target.id}/unsubscribe")
build_conn()
|> assign(:user, user)
|> post("/api/v1/pleroma/accounts/#{subscription_target.id}/unsubscribe")
assert %{"id" => _id, "subscribing" => false} = json_response(conn, 200) assert %{"id" => _id, "subscribing" => false} = json_response(conn, 200)
end end
end end
describe "subscribing" do describe "subscribing" do
test "returns 404 when subscription_target not found", %{conn: conn} do test "returns 404 when subscription_target not found" do
user = insert(:user) %{conn: conn} = oauth_access(["write:follows"])
conn = conn = post(conn, "/api/v1/pleroma/accounts/target_id/subscribe")
conn
|> assign(:user, user)
|> post("/api/v1/pleroma/accounts/target_id/subscribe")
assert %{"error" => "Record not found"} = json_response(conn, 404) assert %{"error" => "Record not found"} = json_response(conn, 404)
end end
end end
describe "unsubscribing" do describe "unsubscribing" do
test "returns 404 when subscription_target not found", %{conn: conn} do test "returns 404 when subscription_target not found" do
user = insert(:user) %{conn: conn} = oauth_access(["follow"])
conn = conn = post(conn, "/api/v1/pleroma/accounts/target_id/unsubscribe")
conn
|> assign(:user, user)
|> post("/api/v1/pleroma/accounts/target_id/unsubscribe")
assert %{"error" => "Record not found"} = json_response(conn, 404) assert %{"error" => "Record not found"} = json_response(conn, 404)
end end

View file

@ -39,9 +39,12 @@ test "shared & non-shared pack information in list_packs is ok" do
test "listing remote packs" do test "listing remote packs" do
admin = insert(:user, is_admin: true) admin = insert(:user, is_admin: true)
conn = build_conn() |> assign(:user, admin) %{conn: conn} = oauth_access(["admin:write"], user: admin)
resp = conn |> get(emoji_api_path(conn, :list_packs)) |> json_response(200) resp =
build_conn()
|> get(emoji_api_path(conn, :list_packs))
|> json_response(200)
mock(fn mock(fn
%{method: :get, url: "https://example.com/.well-known/nodeinfo"} -> %{method: :get, url: "https://example.com/.well-known/nodeinfo"} ->
@ -123,7 +126,10 @@ test "downloading shared & unshared packs from another instance via download_fro
admin = insert(:user, is_admin: true) admin = insert(:user, is_admin: true)
conn = build_conn() |> assign(:user, admin) conn =
build_conn()
|> assign(:user, admin)
|> assign(:token, insert(:oauth_admin_token, user: admin, scopes: ["admin:write"]))
assert (conn assert (conn
|> put_req_header("content-type", "application/json") |> put_req_header("content-type", "application/json")
@ -168,8 +174,6 @@ test "downloading shared & unshared packs from another instance via download_fro
# non-shared, downloaded from the fallback URL # non-shared, downloaded from the fallback URL
conn = build_conn() |> assign(:user, admin)
assert conn assert conn
|> put_req_header("content-type", "application/json") |> put_req_header("content-type", "application/json")
|> post( |> post(
@ -205,8 +209,12 @@ test "downloading shared & unshared packs from another instance via download_fro
File.write!(pack_file, original_content) File.write!(pack_file, original_content)
end) end)
admin = insert(:user, is_admin: true)
%{conn: conn} = oauth_access(["admin:write"], user: admin)
{:ok, {:ok,
admin: insert(:user, is_admin: true), admin: admin,
conn: conn,
pack_file: pack_file, pack_file: pack_file,
new_data: %{ new_data: %{
"license" => "Test license changed", "license" => "Test license changed",
@ -217,10 +225,9 @@ test "downloading shared & unshared packs from another instance via download_fro
end end
test "for a pack without a fallback source", ctx do test "for a pack without a fallback source", ctx do
conn = build_conn() conn = ctx[:conn]
assert conn assert conn
|> assign(:user, ctx[:admin])
|> post( |> post(
emoji_api_path(conn, :update_metadata, "test_pack"), emoji_api_path(conn, :update_metadata, "test_pack"),
%{ %{
@ -250,10 +257,9 @@ test "for a pack with a fallback source", ctx do
"74409E2674DAA06C072729C6C8426C4CB3B7E0B85ED77792DB7A436E11D76DAF" "74409E2674DAA06C072729C6C8426C4CB3B7E0B85ED77792DB7A436E11D76DAF"
) )
conn = build_conn() conn = ctx[:conn]
assert conn assert conn
|> assign(:user, ctx[:admin])
|> post( |> post(
emoji_api_path(conn, :update_metadata, "test_pack"), emoji_api_path(conn, :update_metadata, "test_pack"),
%{ %{
@ -277,10 +283,9 @@ test "when the fallback source doesn't have all the files", ctx do
new_data = Map.put(ctx[:new_data], "fallback-src", "https://nonshared-pack") new_data = Map.put(ctx[:new_data], "fallback-src", "https://nonshared-pack")
conn = build_conn() conn = ctx[:conn]
assert (conn assert (conn
|> assign(:user, ctx[:admin])
|> post( |> post(
emoji_api_path(conn, :update_metadata, "test_pack"), emoji_api_path(conn, :update_metadata, "test_pack"),
%{ %{
@ -304,8 +309,7 @@ test "updating pack files" do
end) end)
admin = insert(:user, is_admin: true) admin = insert(:user, is_admin: true)
%{conn: conn} = oauth_access(["admin:write"], user: admin)
conn = build_conn()
same_name = %{ same_name = %{
"action" => "add", "action" => "add",
@ -319,8 +323,6 @@ test "updating pack files" do
different_name = %{same_name | "shortcode" => "blank_2"} different_name = %{same_name | "shortcode" => "blank_2"}
conn = conn |> assign(:user, admin)
assert (conn assert (conn
|> post(emoji_api_path(conn, :update_file, "test_pack"), same_name) |> post(emoji_api_path(conn, :update_file, "test_pack"), same_name)
|> json_response(:conflict))["error"] =~ "already exists" |> json_response(:conflict))["error"] =~ "already exists"
@ -392,8 +394,7 @@ test "creating and deleting a pack" do
end) end)
admin = insert(:user, is_admin: true) admin = insert(:user, is_admin: true)
%{conn: conn} = oauth_access(["admin:write"], user: admin)
conn = build_conn() |> assign(:user, admin)
assert conn assert conn
|> put_req_header("content-type", "application/json") |> put_req_header("content-type", "application/json")
@ -432,9 +433,9 @@ test "filesystem import" do
refute Map.has_key?(resp, "test_pack_for_import") refute Map.has_key?(resp, "test_pack_for_import")
admin = insert(:user, is_admin: true) admin = insert(:user, is_admin: true)
%{conn: conn} = oauth_access(["admin:write"], user: admin)
assert conn assert conn
|> assign(:user, admin)
|> post(emoji_api_path(conn, :import_from_fs)) |> post(emoji_api_path(conn, :import_from_fs))
|> json_response(200) == ["test_pack_for_import"] |> json_response(200) == ["test_pack_for_import"]
@ -449,11 +450,10 @@ test "filesystem import" do
File.write!("#{@emoji_dir_path}/test_pack_for_import/emoji.txt", emoji_txt_content) File.write!("#{@emoji_dir_path}/test_pack_for_import/emoji.txt", emoji_txt_content)
assert conn assert conn
|> assign(:user, admin)
|> post(emoji_api_path(conn, :import_from_fs)) |> post(emoji_api_path(conn, :import_from_fs))
|> json_response(200) == ["test_pack_for_import"] |> json_response(200) == ["test_pack_for_import"]
resp = conn |> get(emoji_api_path(conn, :list_packs)) |> json_response(200) resp = build_conn() |> get(emoji_api_path(conn, :list_packs)) |> json_response(200)
assert resp["test_pack_for_import"]["files"] == %{ assert resp["test_pack_for_import"]["files"] == %{
"blank" => "blank.png", "blank" => "blank.png",

View file

@ -7,10 +7,8 @@ defmodule Pleroma.Web.PleromaAPI.MascotControllerTest do
alias Pleroma.User alias Pleroma.User
import Pleroma.Factory test "mascot upload" do
%{conn: conn} = oauth_access(["write:accounts"])
test "mascot upload", %{conn: conn} do
user = insert(:user)
non_image_file = %Plug.Upload{ non_image_file = %Plug.Upload{
content_type: "audio/mpeg", content_type: "audio/mpeg",
@ -18,12 +16,9 @@ test "mascot upload", %{conn: conn} do
filename: "sound.mp3" filename: "sound.mp3"
} }
conn = ret_conn = put(conn, "/api/v1/pleroma/mascot", %{"file" => non_image_file})
conn
|> assign(:user, user)
|> put("/api/v1/pleroma/mascot", %{"file" => non_image_file})
assert json_response(conn, 415) assert json_response(ret_conn, 415)
file = %Plug.Upload{ file = %Plug.Upload{
content_type: "image/jpg", content_type: "image/jpg",
@ -31,23 +26,18 @@ test "mascot upload", %{conn: conn} do
filename: "an_image.jpg" filename: "an_image.jpg"
} }
conn = conn = put(conn, "/api/v1/pleroma/mascot", %{"file" => file})
build_conn()
|> assign(:user, user)
|> put("/api/v1/pleroma/mascot", %{"file" => file})
assert %{"id" => _, "type" => image} = json_response(conn, 200) assert %{"id" => _, "type" => image} = json_response(conn, 200)
end end
test "mascot retrieving", %{conn: conn} do test "mascot retrieving" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:accounts", "write:accounts"])
# When user hasn't set a mascot, we should just get pleroma tan back
conn =
conn
|> assign(:user, user)
|> get("/api/v1/pleroma/mascot")
assert %{"url" => url} = json_response(conn, 200) # 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 =~ "pleroma-fox-tan-smol" assert url =~ "pleroma-fox-tan-smol"
# When a user sets their mascot, we should get that back # When a user sets their mascot, we should get that back
@ -57,17 +47,14 @@ test "mascot retrieving", %{conn: conn} do
filename: "an_image.jpg" filename: "an_image.jpg"
} }
conn = ret_conn = put(conn, "/api/v1/pleroma/mascot", %{"file" => file})
build_conn()
|> assign(:user, user)
|> put("/api/v1/pleroma/mascot", %{"file" => file})
assert json_response(conn, 200) assert json_response(ret_conn, 200)
user = User.get_cached_by_id(user.id) user = User.get_cached_by_id(user.id)
conn = conn =
build_conn() conn
|> assign(:user, user) |> assign(:user, user)
|> get("/api/v1/pleroma/mascot") |> get("/api/v1/pleroma/mascot")

View file

@ -23,6 +23,7 @@ test "POST /api/v1/pleroma/statuses/:id/react_with_emoji", %{conn: conn} do
result = result =
conn conn
|> assign(:user, other_user) |> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"]))
|> post("/api/v1/pleroma/statuses/#{activity.id}/react_with_emoji", %{"emoji" => ""}) |> post("/api/v1/pleroma/statuses/#{activity.id}/react_with_emoji", %{"emoji" => ""})
assert %{"id" => id} = json_response(result, 200) assert %{"id" => id} = json_response(result, 200)
@ -39,6 +40,7 @@ test "POST /api/v1/pleroma/statuses/:id/unreact_with_emoji", %{conn: conn} do
result = result =
conn conn
|> assign(:user, other_user) |> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"]))
|> post("/api/v1/pleroma/statuses/#{activity.id}/unreact_with_emoji", %{"emoji" => ""}) |> post("/api/v1/pleroma/statuses/#{activity.id}/unreact_with_emoji", %{"emoji" => ""})
assert %{"id" => id} = json_response(result, 200) assert %{"id" => id} = json_response(result, 200)
@ -55,6 +57,11 @@ test "GET /api/v1/pleroma/statuses/:id/emoji_reactions_by", %{conn: conn} do
{:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"}) {:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
conn =
conn
|> assign(:user, user)
|> assign(:token, insert(:oauth_token, user: user, scopes: ["read:statuses"]))
result = result =
conn conn
|> get("/api/v1/pleroma/statuses/#{activity.id}/emoji_reactions_by") |> get("/api/v1/pleroma/statuses/#{activity.id}/emoji_reactions_by")
@ -73,9 +80,9 @@ test "GET /api/v1/pleroma/statuses/:id/emoji_reactions_by", %{conn: conn} do
assert represented_user["id"] == other_user.id assert represented_user["id"] == other_user.id
end end
test "/api/v1/pleroma/conversations/:id", %{conn: conn} do test "/api/v1/pleroma/conversations/:id" do
user = insert(:user) user = insert(:user)
other_user = insert(:user) %{user: other_user, conn: conn} = oauth_access(["read:statuses"])
{:ok, _activity} = {:ok, _activity} =
CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}!", "visibility" => "direct"}) CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}!", "visibility" => "direct"})
@ -84,16 +91,15 @@ test "/api/v1/pleroma/conversations/:id", %{conn: conn} do
result = result =
conn conn
|> assign(:user, other_user)
|> get("/api/v1/pleroma/conversations/#{participation.id}") |> get("/api/v1/pleroma/conversations/#{participation.id}")
|> json_response(200) |> json_response(200)
assert result["id"] == participation.id |> to_string() assert result["id"] == participation.id |> to_string()
end end
test "/api/v1/pleroma/conversations/:id/statuses", %{conn: conn} do test "/api/v1/pleroma/conversations/:id/statuses" do
user = insert(:user) user = insert(:user)
other_user = insert(:user) %{user: other_user, conn: conn} = oauth_access(["read:statuses"])
third_user = insert(:user) third_user = insert(:user)
{:ok, _activity} = {:ok, _activity} =
@ -113,7 +119,6 @@ test "/api/v1/pleroma/conversations/:id/statuses", %{conn: conn} do
result = result =
conn conn
|> assign(:user, other_user)
|> get("/api/v1/pleroma/conversations/#{participation.id}/statuses") |> get("/api/v1/pleroma/conversations/#{participation.id}/statuses")
|> json_response(200) |> json_response(200)
@ -124,8 +129,8 @@ test "/api/v1/pleroma/conversations/:id/statuses", %{conn: conn} do
assert [%{"id" => ^id_one}, %{"id" => ^id_two}] = result assert [%{"id" => ^id_one}, %{"id" => ^id_two}] = result
end end
test "PATCH /api/v1/pleroma/conversations/:id", %{conn: conn} do test "PATCH /api/v1/pleroma/conversations/:id" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:conversations"])
other_user = insert(:user) other_user = insert(:user)
{:ok, _activity} = CommonAPI.post(user, %{"status" => "Hi", "visibility" => "direct"}) {:ok, _activity} = CommonAPI.post(user, %{"status" => "Hi", "visibility" => "direct"})
@ -140,7 +145,6 @@ test "PATCH /api/v1/pleroma/conversations/:id", %{conn: conn} do
result = result =
conn conn
|> assign(:user, user)
|> patch("/api/v1/pleroma/conversations/#{participation.id}", %{ |> patch("/api/v1/pleroma/conversations/#{participation.id}", %{
"recipients" => [user.id, other_user.id] "recipients" => [user.id, other_user.id]
}) })
@ -155,9 +159,9 @@ test "PATCH /api/v1/pleroma/conversations/:id", %{conn: conn} do
assert other_user in participation.recipients assert other_user in participation.recipients
end end
test "POST /api/v1/pleroma/conversations/read", %{conn: conn} do test "POST /api/v1/pleroma/conversations/read" do
user = insert(:user) user = insert(:user)
other_user = insert(:user) %{user: other_user, conn: conn} = oauth_access(["write:notifications"])
{:ok, _activity} = {:ok, _activity} =
CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}", "visibility" => "direct"}) CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}", "visibility" => "direct"})
@ -172,7 +176,6 @@ test "POST /api/v1/pleroma/conversations/read", %{conn: conn} do
[%{"unread" => false}, %{"unread" => false}] = [%{"unread" => false}, %{"unread" => false}] =
conn conn
|> assign(:user, other_user)
|> post("/api/v1/pleroma/conversations/read", %{}) |> post("/api/v1/pleroma/conversations/read", %{})
|> json_response(200) |> json_response(200)
@ -183,8 +186,9 @@ test "POST /api/v1/pleroma/conversations/read", %{conn: conn} do
end end
describe "POST /api/v1/pleroma/notifications/read" do describe "POST /api/v1/pleroma/notifications/read" do
test "it marks a single notification as read", %{conn: conn} do setup do: oauth_access(["write:notifications"])
user1 = insert(:user)
test "it marks a single notification as read", %{user: user1, conn: conn} do
user2 = insert(:user) user2 = insert(:user)
{:ok, activity1} = 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, activity2} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"})
@ -193,7 +197,6 @@ test "it marks a single notification as read", %{conn: conn} do
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/v1/pleroma/notifications/read", %{"id" => "#{notification1.id}"}) |> post("/api/v1/pleroma/notifications/read", %{"id" => "#{notification1.id}"})
|> json_response(:ok) |> json_response(:ok)
@ -202,8 +205,7 @@ test "it marks a single notification as read", %{conn: conn} do
refute Repo.get(Notification, notification2.id).seen refute Repo.get(Notification, notification2.id).seen
end end
test "it marks multiple notifications as read", %{conn: conn} do test "it marks multiple notifications as read", %{user: user1, conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
{:ok, _activity1} = 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, _activity2} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"})
@ -213,7 +215,6 @@ test "it marks multiple notifications as read", %{conn: conn} do
[response1, response2] = [response1, response2] =
conn conn
|> assign(:user, user1)
|> post("/api/v1/pleroma/notifications/read", %{"max_id" => "#{notification2.id}"}) |> post("/api/v1/pleroma/notifications/read", %{"max_id" => "#{notification2.id}"})
|> json_response(:ok) |> json_response(:ok)
@ -225,11 +226,8 @@ test "it marks multiple notifications as read", %{conn: conn} do
end end
test "it returns error when notification not found", %{conn: conn} do test "it returns error when notification not found", %{conn: conn} do
user1 = insert(:user)
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/v1/pleroma/notifications/read", %{"id" => "22222222222222"}) |> post("/api/v1/pleroma/notifications/read", %{"id" => "22222222222222"})
|> json_response(:bad_request) |> json_response(:bad_request)

View file

@ -6,16 +6,13 @@ defmodule Pleroma.Web.PleromaAPI.ScrobbleControllerTest do
use Pleroma.Web.ConnCase use Pleroma.Web.ConnCase
alias Pleroma.Web.CommonAPI alias Pleroma.Web.CommonAPI
import Pleroma.Factory
describe "POST /api/v1/pleroma/scrobble" do describe "POST /api/v1/pleroma/scrobble" do
test "works correctly", %{conn: conn} do test "works correctly" do
user = insert(:user) %{conn: conn} = oauth_access(["write"])
conn = conn =
conn post(conn, "/api/v1/pleroma/scrobble", %{
|> assign(:user, user)
|> post("/api/v1/pleroma/scrobble", %{
"title" => "lain radio episode 1", "title" => "lain radio episode 1",
"artist" => "lain", "artist" => "lain",
"album" => "lain radio", "album" => "lain radio",
@ -27,8 +24,8 @@ test "works correctly", %{conn: conn} do
end end
describe "GET /api/v1/pleroma/accounts/:id/scrobbles" do describe "GET /api/v1/pleroma/accounts/:id/scrobbles" do
test "works correctly", %{conn: conn} do test "works correctly" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read"])
{:ok, _activity} = {:ok, _activity} =
CommonAPI.listen(user, %{ CommonAPI.listen(user, %{
@ -51,9 +48,7 @@ test "works correctly", %{conn: conn} do
"album" => "lain radio" "album" => "lain radio"
}) })
conn = conn = get(conn, "/api/v1/pleroma/accounts/#{user.id}/scrobbles")
conn
|> get("/api/v1/pleroma/accounts/#{user.id}/scrobbles")
result = json_response(conn, 200) result = json_response(conn, 200)

View file

@ -6,10 +6,10 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do
use Pleroma.Web.ConnCase use Pleroma.Web.ConnCase
use Oban.Testing, repo: Pleroma.Repo use Oban.Testing, repo: Pleroma.Repo
alias Pleroma.Repo
alias Pleroma.Tests.ObanHelpers alias Pleroma.Tests.ObanHelpers
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.CommonAPI alias Pleroma.Web.CommonAPI
import ExUnit.CaptureLog import ExUnit.CaptureLog
import Pleroma.Factory import Pleroma.Factory
import Mock import Mock
@ -24,21 +24,20 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do
clear_config([:user, :deny_follow_blocked]) clear_config([:user, :deny_follow_blocked])
describe "POST /api/pleroma/follow_import" do describe "POST /api/pleroma/follow_import" do
setup do: oauth_access(["follow"])
test "it returns HTTP 200", %{conn: conn} do test "it returns HTTP 200", %{conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/pleroma/follow_import", %{"list" => "#{user2.ap_id}"}) |> post("/api/pleroma/follow_import", %{"list" => "#{user2.ap_id}"})
|> json_response(:ok) |> json_response(:ok)
assert response == "job started" assert response == "job started"
end end
test "it imports follow lists from file", %{conn: conn} do test "it imports follow lists from file", %{user: user1, conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
with_mocks([ with_mocks([
@ -49,7 +48,6 @@ test "it imports follow lists from file", %{conn: conn} do
]) do ]) do
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/pleroma/follow_import", %{"list" => %Plug.Upload{path: "follow_list.txt"}}) |> post("/api/pleroma/follow_import", %{"list" => %Plug.Upload{path: "follow_list.txt"}})
|> json_response(:ok) |> json_response(:ok)
@ -67,12 +65,10 @@ test "it imports follow lists from file", %{conn: conn} do
end end
test "it imports new-style mastodon follow lists", %{conn: conn} do test "it imports new-style mastodon follow lists", %{conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/pleroma/follow_import", %{ |> post("/api/pleroma/follow_import", %{
"list" => "Account address,Show boosts\n#{user2.ap_id},true" "list" => "Account address,Show boosts\n#{user2.ap_id},true"
}) })
@ -81,7 +77,7 @@ test "it imports new-style mastodon follow lists", %{conn: conn} do
assert response == "job started" assert response == "job started"
end end
test "requires 'follow' or 'write:follows' permissions", %{conn: conn} do test "requires 'follow' or 'write:follows' permissions" do
token1 = insert(:oauth_token, scopes: ["read", "write"]) token1 = insert(:oauth_token, scopes: ["read", "write"])
token2 = insert(:oauth_token, scopes: ["follow"]) token2 = insert(:oauth_token, scopes: ["follow"])
token3 = insert(:oauth_token, scopes: ["something"]) token3 = insert(:oauth_token, scopes: ["something"])
@ -89,7 +85,7 @@ test "requires 'follow' or 'write:follows' permissions", %{conn: conn} do
for token <- [token1, token2, token3] do for token <- [token1, token2, token3] do
conn = conn =
conn build_conn()
|> put_req_header("authorization", "Bearer #{token.token}") |> put_req_header("authorization", "Bearer #{token.token}")
|> post("/api/pleroma/follow_import", %{"list" => "#{another_user.ap_id}"}) |> post("/api/pleroma/follow_import", %{"list" => "#{another_user.ap_id}"})
@ -104,21 +100,21 @@ test "requires 'follow' or 'write:follows' permissions", %{conn: conn} do
end end
describe "POST /api/pleroma/blocks_import" do describe "POST /api/pleroma/blocks_import" do
# Note: "follow" or "write:blocks" permission is required
setup do: oauth_access(["write:blocks"])
test "it returns HTTP 200", %{conn: conn} do test "it returns HTTP 200", %{conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/pleroma/blocks_import", %{"list" => "#{user2.ap_id}"}) |> post("/api/pleroma/blocks_import", %{"list" => "#{user2.ap_id}"})
|> json_response(:ok) |> json_response(:ok)
assert response == "job started" assert response == "job started"
end end
test "it imports blocks users from file", %{conn: conn} do test "it imports blocks users from file", %{user: user1, conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
user3 = insert(:user) user3 = insert(:user)
@ -127,7 +123,6 @@ test "it imports blocks users from file", %{conn: conn} do
]) do ]) do
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/pleroma/blocks_import", %{"list" => %Plug.Upload{path: "blocks_list.txt"}}) |> post("/api/pleroma/blocks_import", %{"list" => %Plug.Upload{path: "blocks_list.txt"}})
|> json_response(:ok) |> json_response(:ok)
@ -146,18 +141,17 @@ test "it imports blocks users from file", %{conn: conn} do
end end
describe "PUT /api/pleroma/notification_settings" do describe "PUT /api/pleroma/notification_settings" do
test "it updates notification settings", %{conn: conn} do setup do: oauth_access(["write:accounts"])
user = insert(:user)
test "it updates notification settings", %{user: user, conn: conn} do
conn conn
|> assign(:user, user)
|> put("/api/pleroma/notification_settings", %{ |> put("/api/pleroma/notification_settings", %{
"followers" => false, "followers" => false,
"bar" => 1 "bar" => 1
}) })
|> json_response(:ok) |> json_response(:ok)
user = Repo.get(User, user.id) user = refresh_record(user)
assert %Pleroma.User.NotificationSetting{ assert %Pleroma.User.NotificationSetting{
followers: false, followers: false,
@ -168,11 +162,8 @@ test "it updates notification settings", %{conn: conn} do
} == user.notification_settings } == user.notification_settings
end end
test "it update notificatin privacy option", %{conn: conn} do test "it updates notification privacy option", %{user: user, conn: conn} do
user = insert(:user)
conn conn
|> assign(:user, user)
|> put("/api/pleroma/notification_settings", %{"privacy_option" => "1"}) |> put("/api/pleroma/notification_settings", %{"privacy_option" => "1"})
|> json_response(:ok) |> json_response(:ok)
@ -374,14 +365,14 @@ test "show follow page with error when user cannot fecth by `acct` link", %{conn
end end
end end
describe "POST /ostatus_subscribe - do_remote_follow/2 with assigned user " do describe "POST /ostatus_subscribe - do_remote_follow/2 with assigned user" do
test "follows user", %{conn: conn} do setup do: oauth_access(["follow"])
user = insert(:user)
test "follows user", %{user: user, conn: conn} do
user2 = insert(:user) user2 = insert(:user)
response = response =
conn conn
|> assign(:user, user)
|> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}})
|> response(200) |> response(200)
@ -389,55 +380,63 @@ test "follows user", %{conn: conn} do
assert user2.follower_address in User.following(user) assert user2.follower_address in User.following(user)
end end
test "returns error when user is deactivated", %{conn: conn} do test "returns error when user is deactivated" do
user = insert(:user, deactivated: true) user = insert(:user, deactivated: true)
user2 = insert(:user) user2 = insert(:user)
response = response =
conn build_conn()
|> assign(:user, user) |> assign(:user, user)
|> assign(:token, insert(:oauth_token, user: user, scopes: ["follow"]))
|> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}})
|> response(200) |> response(200)
assert response =~ "Error following account" assert response =~ "Error following account"
end end
test "returns error when user is blocked", %{conn: conn} do test "returns error when user is blocked", %{user: user, conn: conn} do
Pleroma.Config.put([:user, :deny_follow_blocked], true) Pleroma.Config.put([:user, :deny_follow_blocked], true)
user = insert(:user)
user2 = insert(:user) user2 = insert(:user)
{:ok, _user_block} = Pleroma.User.block(user2, user) {:ok, _user_block} = Pleroma.User.block(user2, user)
response = response =
conn conn
|> assign(:user, user)
|> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}})
|> response(200) |> response(200)
assert response =~ "Error following account" assert response =~ "Error following account"
end end
test "returns error when followee not found", %{conn: conn} do test "returns error on insufficient permissions", %{user: user, conn: conn} do
user = insert(:user) user2 = insert(:user)
for token <- [nil, insert(:oauth_token, user: user, scopes: ["read"])] do
response =
conn
|> assign(:token, token)
|> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}})
|> response(200)
assert response =~ "Error following account"
end
end
test "returns error when followee not found", %{conn: conn} do
response = response =
conn conn
|> assign(:user, user)
|> post("/ostatus_subscribe", %{"user" => %{"id" => "jimm"}}) |> post("/ostatus_subscribe", %{"user" => %{"id" => "jimm"}})
|> response(200) |> response(200)
assert response =~ "Error following account" assert response =~ "Error following account"
end end
test "returns success result when user already in followers", %{conn: conn} do test "returns success result when user already in followers", %{user: user, conn: conn} do
user = insert(:user)
user2 = insert(:user) user2 = insert(:user)
{:ok, _, _, _} = CommonAPI.follow(user, user2) {:ok, _, _, _} = CommonAPI.follow(user, user2)
response = response =
conn conn
|> assign(:user, refresh_record(user))
|> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}})
|> response(200) |> response(200)
@ -445,7 +444,7 @@ test "returns success result when user already in followers", %{conn: conn} do
end end
end end
describe "POST /ostatus_subscribe - do_remote_follow/2 without assigned user " do describe "POST /ostatus_subscribe - do_remote_follow/2 without assigned user" do
test "follows", %{conn: conn} do test "follows", %{conn: conn} do
user = insert(:user) user = insert(:user)
user2 = insert(:user) user2 = insert(:user)
@ -574,12 +573,11 @@ test "returns 503 when healthcheck enabled and health is false", %{conn: conn}
end end
describe "POST /api/pleroma/disable_account" do describe "POST /api/pleroma/disable_account" do
test "it returns HTTP 200", %{conn: conn} do setup do: oauth_access(["write:accounts"])
user = insert(:user)
test "with valid permissions and password, it disables the account", %{conn: conn, user: user} do
response = response =
conn conn
|> assign(:user, user)
|> post("/api/pleroma/disable_account", %{"password" => "test"}) |> post("/api/pleroma/disable_account", %{"password" => "test"})
|> json_response(:ok) |> json_response(:ok)
@ -591,12 +589,11 @@ test "it returns HTTP 200", %{conn: conn} do
assert user.deactivated == true assert user.deactivated == true
end end
test "it returns returns when password invalid", %{conn: conn} do test "with valid permissions and invalid password, it returns an error", %{conn: conn} do
user = insert(:user) user = insert(:user)
response = response =
conn conn
|> assign(:user, user)
|> post("/api/pleroma/disable_account", %{"password" => "test1"}) |> post("/api/pleroma/disable_account", %{"password" => "test1"})
|> json_response(:ok) |> json_response(:ok)
@ -666,7 +663,7 @@ test "it redirect to webfinger url", %{conn: conn} do
"https://social.heldscal.la/main/ostatussub?profile=#{user.ap_id}" "https://social.heldscal.la/main/ostatussub?profile=#{user.ap_id}"
end end
test "it renders form with error when use not found", %{conn: conn} do test "it renders form with error when user not found", %{conn: conn} do
user2 = insert(:user, ap_id: "shp@social.heldscal.la") user2 = insert(:user, ap_id: "shp@social.heldscal.la")
response = response =
@ -691,29 +688,21 @@ test "it returns new captcha", %{conn: conn} do
end end
end end
defp with_credentials(conn, username, password) do
header_content = "Basic " <> Base.encode64("#{username}:#{password}")
put_req_header(conn, "authorization", header_content)
end
defp valid_user(_context) do
user = insert(:user)
[user: user]
end
describe "POST /api/pleroma/change_email" do describe "POST /api/pleroma/change_email" do
setup [:valid_user] setup do: oauth_access(["write:accounts"])
test "without credentials", %{conn: conn} do test "without permissions", %{conn: conn} do
conn = post(conn, "/api/pleroma/change_email")
assert json_response(conn, 403) == %{"error" => "Invalid credentials."}
end
test "with credentials and invalid password", %{conn: conn, user: current_user} do
conn = conn =
conn conn
|> with_credentials(current_user.nickname, "test") |> assign(:token, nil)
|> post("/api/pleroma/change_email", %{ |> post("/api/pleroma/change_email")
assert json_response(conn, 403) == %{"error" => "Insufficient permissions: write:accounts."}
end
test "with proper permissions and invalid password", %{conn: conn} do
conn =
post(conn, "/api/pleroma/change_email", %{
"password" => "hi", "password" => "hi",
"email" => "test@test.com" "email" => "test@test.com"
}) })
@ -721,14 +710,11 @@ test "with credentials and invalid password", %{conn: conn, user: current_user}
assert json_response(conn, 200) == %{"error" => "Invalid password."} assert json_response(conn, 200) == %{"error" => "Invalid password."}
end end
test "with credentials, valid password and invalid email", %{ test "with proper permissions, valid password and invalid email", %{
conn: conn, conn: conn
user: current_user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_email", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_email", %{
"password" => "test", "password" => "test",
"email" => "foobar" "email" => "foobar"
}) })
@ -736,28 +722,22 @@ test "with credentials, valid password and invalid email", %{
assert json_response(conn, 200) == %{"error" => "Email has invalid format."} assert json_response(conn, 200) == %{"error" => "Email has invalid format."}
end end
test "with credentials, valid password and no email", %{ test "with proper permissions, valid password and no email", %{
conn: conn, conn: conn
user: current_user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_email", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_email", %{
"password" => "test" "password" => "test"
}) })
assert json_response(conn, 200) == %{"error" => "Email can't be blank."} assert json_response(conn, 200) == %{"error" => "Email can't be blank."}
end end
test "with credentials, valid password and blank email", %{ test "with proper permissions, valid password and blank email", %{
conn: conn, conn: conn
user: current_user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_email", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_email", %{
"password" => "test", "password" => "test",
"email" => "" "email" => ""
}) })
@ -765,16 +745,13 @@ test "with credentials, valid password and blank email", %{
assert json_response(conn, 200) == %{"error" => "Email can't be blank."} assert json_response(conn, 200) == %{"error" => "Email can't be blank."}
end end
test "with credentials, valid password and non unique email", %{ test "with proper permissions, valid password and non unique email", %{
conn: conn, conn: conn
user: current_user
} do } do
user = insert(:user) user = insert(:user)
conn = conn =
conn post(conn, "/api/pleroma/change_email", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_email", %{
"password" => "test", "password" => "test",
"email" => user.email "email" => user.email
}) })
@ -782,14 +759,11 @@ test "with credentials, valid password and non unique email", %{
assert json_response(conn, 200) == %{"error" => "Email has already been taken."} assert json_response(conn, 200) == %{"error" => "Email has already been taken."}
end end
test "with credentials, valid password and valid email", %{ test "with proper permissions, valid password and valid email", %{
conn: conn, conn: conn
user: current_user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_email", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_email", %{
"password" => "test", "password" => "test",
"email" => "cofe@foobar.com" "email" => "cofe@foobar.com"
}) })
@ -799,18 +773,20 @@ test "with credentials, valid password and valid email", %{
end end
describe "POST /api/pleroma/change_password" do describe "POST /api/pleroma/change_password" do
setup [:valid_user] setup do: oauth_access(["write:accounts"])
test "without credentials", %{conn: conn} do test "without permissions", %{conn: conn} do
conn = post(conn, "/api/pleroma/change_password")
assert json_response(conn, 403) == %{"error" => "Invalid credentials."}
end
test "with credentials and invalid password", %{conn: conn, user: current_user} do
conn = conn =
conn conn
|> with_credentials(current_user.nickname, "test") |> assign(:token, nil)
|> post("/api/pleroma/change_password", %{ |> post("/api/pleroma/change_password")
assert json_response(conn, 403) == %{"error" => "Insufficient permissions: write:accounts."}
end
test "with proper permissions and invalid password", %{conn: conn} do
conn =
post(conn, "/api/pleroma/change_password", %{
"password" => "hi", "password" => "hi",
"new_password" => "newpass", "new_password" => "newpass",
"new_password_confirmation" => "newpass" "new_password_confirmation" => "newpass"
@ -819,14 +795,12 @@ test "with credentials and invalid password", %{conn: conn, user: current_user}
assert json_response(conn, 200) == %{"error" => "Invalid password."} assert json_response(conn, 200) == %{"error" => "Invalid password."}
end end
test "with credentials, valid password and new password and confirmation not matching", %{ test "with proper permissions, valid password and new password and confirmation not matching",
conn: conn, %{
user: current_user conn: conn
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_password", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_password", %{
"password" => "test", "password" => "test",
"new_password" => "newpass", "new_password" => "newpass",
"new_password_confirmation" => "notnewpass" "new_password_confirmation" => "notnewpass"
@ -837,14 +811,11 @@ test "with credentials, valid password and new password and confirmation not mat
} }
end end
test "with credentials, valid password and invalid new password", %{ test "with proper permissions, valid password and invalid new password", %{
conn: conn, conn: conn
user: current_user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_password", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_password", %{
"password" => "test", "password" => "test",
"new_password" => "", "new_password" => "",
"new_password_confirmation" => "" "new_password_confirmation" => ""
@ -855,47 +826,46 @@ test "with credentials, valid password and invalid new password", %{
} }
end end
test "with credentials, valid password and matching new password and confirmation", %{ test "with proper permissions, valid password and matching new password and confirmation", %{
conn: conn, conn: conn,
user: current_user user: user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_password", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_password", %{
"password" => "test", "password" => "test",
"new_password" => "newpass", "new_password" => "newpass",
"new_password_confirmation" => "newpass" "new_password_confirmation" => "newpass"
}) })
assert json_response(conn, 200) == %{"status" => "success"} assert json_response(conn, 200) == %{"status" => "success"}
fetched_user = User.get_cached_by_id(current_user.id) fetched_user = User.get_cached_by_id(user.id)
assert Comeonin.Pbkdf2.checkpw("newpass", fetched_user.password_hash) == true assert Comeonin.Pbkdf2.checkpw("newpass", fetched_user.password_hash) == true
end end
end end
describe "POST /api/pleroma/delete_account" do describe "POST /api/pleroma/delete_account" do
setup [:valid_user] setup do: oauth_access(["write:accounts"])
test "without credentials", %{conn: conn} do test "without permissions", %{conn: conn} do
conn = post(conn, "/api/pleroma/delete_account")
assert json_response(conn, 403) == %{"error" => "Invalid credentials."}
end
test "with credentials and invalid password", %{conn: conn, user: current_user} do
conn = conn =
conn conn
|> with_credentials(current_user.nickname, "test") |> assign(:token, nil)
|> post("/api/pleroma/delete_account", %{"password" => "hi"}) |> post("/api/pleroma/delete_account")
assert json_response(conn, 200) == %{"error" => "Invalid password."} assert json_response(conn, 403) ==
%{"error" => "Insufficient permissions: write:accounts."}
end end
test "with credentials and valid password", %{conn: conn, user: current_user} do test "with proper permissions and wrong or missing password", %{conn: conn} do
conn = for params <- [%{"password" => "hi"}, %{}] do
conn ret_conn = post(conn, "/api/pleroma/delete_account", params)
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/delete_account", %{"password" => "test"}) assert json_response(ret_conn, 200) == %{"error" => "Invalid password."}
end
end
test "with proper permissions and valid password", %{conn: conn} do
conn = post(conn, "/api/pleroma/delete_account", %{"password" => "test"})
assert json_response(conn, 200) == %{"status" => "success"} assert json_response(conn, 200) == %{"status" => "success"}
end end