Merge branch 'tests/mastodon_api_controller.ex' into 'develop'

tests for mastodon_api_controller.ex

See merge request pleroma/pleroma!1639
This commit is contained in:
Haelwenn 2019-09-28 19:02:05 +00:00
commit b35a0f0ce4
10 changed files with 402 additions and 139 deletions

View file

@ -137,11 +137,18 @@ def get_by_ap_id_with_object(ap_id) do
|> Repo.one() |> Repo.one()
end end
@spec get_by_id(String.t()) :: Activity.t() | nil
def get_by_id(id) do def get_by_id(id) do
case FlakeId.flake_id?(id) do
true ->
Activity Activity
|> where([a], a.id == ^id) |> where([a], a.id == ^id)
|> restrict_deactivated_users() |> restrict_deactivated_users()
|> Repo.one() |> Repo.one()
_ ->
nil
end
end end
def get_by_id_with_object(id) do def get_by_id_with_object(id) do

View file

@ -248,4 +248,11 @@ def increase_vote_count(ap_id, name) do
_ -> :noop _ -> :noop
end end
end end
@doc "Updates data field of an object"
def update_data(%Object{data: data} = object, attrs \\ %{}) do
object
|> Object.change(%{data: Map.merge(data || %{}, attrs)})
|> Repo.update()
end
end end

View file

@ -505,6 +505,11 @@ def get_all_by_ap_id(ap_ids) do
|> Repo.all() |> Repo.all()
end end
def get_all_by_ids(ids) do
from(u in __MODULE__, where: u.id in ^ids)
|> Repo.all()
end
# This is mostly an SPC migration fix. This guesses the user nickname by taking the last part # This is mostly an SPC migration fix. This guesses the user nickname by taking the last part
# of the ap_id and the domain and tries to get that user # of the ap_id and the domain and tries to get that user
def get_by_guessed_nickname(ap_id) do def get_by_guessed_nickname(ap_id) do
@ -765,6 +770,19 @@ def update_note_count(%User{} = user) do
update_info(user, &User.Info.set_note_count(&1, note_count)) update_info(user, &User.Info.set_note_count(&1, note_count))
end end
def update_mascot(user, url) do
info_changeset =
User.Info.mascot_update(
user.info,
url
)
user
|> change()
|> put_embed(:info, info_changeset)
|> update_and_set_cache()
end
@spec maybe_fetch_follow_information(User.t()) :: User.t() @spec maybe_fetch_follow_information(User.t()) :: User.t()
def maybe_fetch_follow_information(user) do def maybe_fetch_follow_information(user) do
with {:ok, user} <- fetch_follow_information(user) do with {:ok, user} <- fetch_follow_information(user) do

View file

@ -40,8 +40,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
alias Pleroma.Web.OAuth.Token alias Pleroma.Web.OAuth.Token
alias Pleroma.Web.TwitterAPI.TwitterAPI alias Pleroma.Web.TwitterAPI.TwitterAPI
import Ecto.Query
require Logger require Logger
require Pleroma.Constants require Pleroma.Constants
@ -393,9 +391,7 @@ def poll_vote(%{assigns: %{user: user}} = conn, %{"id" => id, "choices" => choic
end end
def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
id = List.wrap(id) targets = User.get_all_by_ids(List.wrap(id))
q = from(u in User, where: u.id in ^id)
targets = Repo.all(q)
conn conn
|> put_view(AccountView) |> put_view(AccountView)
@ -405,19 +401,15 @@ def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
# Instead of returning a 400 when no "id" params is present, Mastodon returns an empty array. # Instead of returning a 400 when no "id" params is present, Mastodon returns an empty array.
def relationships(%{assigns: %{user: _user}} = conn, _), do: json(conn, []) def relationships(%{assigns: %{user: _user}} = conn, _), do: json(conn, [])
def update_media(%{assigns: %{user: user}} = conn, data) do def update_media(
with %Object{} = object <- Repo.get(Object, data["id"]), %{assigns: %{user: user}} = conn,
%{"id" => id, "description" => description} = _
)
when is_binary(description) do
with %Object{} = object <- Repo.get(Object, id),
true <- Object.authorize_mutation(object, user), true <- Object.authorize_mutation(object, user),
true <- is_binary(data["description"]), {:ok, %Object{data: data}} <- Object.update_data(object, %{"name" => description}) do
description <- data["description"] do attachment_data = Map.put(data, "id", object.id)
new_data = %{object.data | "name" => description}
{:ok, _} =
object
|> Object.change(%{data: new_data})
|> Repo.update()
attachment_data = Map.put(new_data, "id", object.id)
conn conn
|> put_view(StatusView) |> put_view(StatusView)
@ -425,6 +417,8 @@ def update_media(%{assigns: %{user: user}} = conn, data) do
end end
end end
def update_media(_conn, _data), do: {:error, :bad_request}
def upload(%{assigns: %{user: user}} = conn, %{"file" => file} = data) do def upload(%{assigns: %{user: user}} = conn, %{"file" => file} = data) do
with {:ok, object} <- with {:ok, object} <-
ActivityPub.upload( ActivityPub.upload(
@ -459,8 +453,7 @@ def set_mascot(%{assigns: %{user: user}} = conn, %{"file" => file}) do
def get_mascot(%{assigns: %{user: user}} = conn, _params) do def get_mascot(%{assigns: %{user: user}} = conn, _params) do
mascot = User.get_mascot(user) mascot = User.get_mascot(user)
conn json(conn, mascot)
|> json(mascot)
end end
def followers(%{assigns: %{user: for_user}} = conn, %{"id" => id} = params) do def followers(%{assigns: %{user: for_user}} = conn, %{"id" => id} = params) do
@ -633,10 +626,8 @@ def subscribe(%{assigns: %{user: user}} = conn, %{"id" => id}) do
|> put_view(AccountView) |> put_view(AccountView)
|> render("relationship.json", %{user: user, target: subscription_target}) |> render("relationship.json", %{user: user, target: subscription_target})
else else
{:error, message} -> nil -> {:error, :not_found}
conn e -> e
|> put_status(:forbidden)
|> json(%{error: message})
end end
end end
@ -647,10 +638,8 @@ def unsubscribe(%{assigns: %{user: user}} = conn, %{"id" => id}) do
|> put_view(AccountView) |> put_view(AccountView)
|> render("relationship.json", %{user: user, target: subscription_target}) |> render("relationship.json", %{user: user, target: subscription_target})
else else
{:error, message} -> nil -> {:error, :not_found}
conn e -> e
|> put_status(:forbidden)
|> json(%{error: message})
end end
end end
@ -721,8 +710,10 @@ def bookmarks(%{assigns: %{user: user}} = conn, params) do
def account_lists(%{assigns: %{user: user}} = conn, %{"id" => account_id}) do def account_lists(%{assigns: %{user: user}} = conn, %{"id" => account_id}) do
lists = Pleroma.List.get_lists_account_belongs(user, account_id) lists = Pleroma.List.get_lists_account_belongs(user, account_id)
res = ListView.render("lists.json", lists: lists)
json(conn, res) conn
|> put_view(ListView)
|> render("index.json", %{lists: lists})
end end
def index(%{assigns: %{user: user}} = conn, _params) do def index(%{assigns: %{user: user}} = conn, _params) do
@ -848,7 +839,7 @@ def login(%{assigns: %{user: %User{}}} = conn, _params) do
@doc "Local Mastodon FE login init action" @doc "Local Mastodon FE login init action"
def login(conn, %{"code" => auth_token}) do def login(conn, %{"code" => auth_token}) do
with {:ok, app} <- get_or_make_app(), with {:ok, app} <- get_or_make_app(),
%Authorization{} = auth <- Repo.get_by(Authorization, token: auth_token, app_id: app.id), {:ok, auth} <- Authorization.get_by_token(app, auth_token),
{:ok, token} <- Token.exchange_token(app, auth) do {:ok, token} <- Token.exchange_token(app, auth) do
conn conn
|> put_session(:oauth_token, token.token) |> put_session(:oauth_token, token.token)
@ -860,9 +851,7 @@ def login(conn, %{"code" => auth_token}) do
def login(conn, _) do def login(conn, _) do
with {:ok, app} <- get_or_make_app() do with {:ok, app} <- get_or_make_app() do
path = path =
o_auth_path( o_auth_path(conn, :authorize,
conn,
:authorize,
response_type: "code", response_type: "code",
client_id: app.client_id, client_id: app.client_id,
redirect_uri: ".", redirect_uri: ".",
@ -884,31 +873,12 @@ defp local_mastodon_root_path(conn) do
end end
end end
@spec get_or_make_app() :: {:ok, App.t()} | {:error, Ecto.Changeset.t()}
defp get_or_make_app do defp get_or_make_app do
find_attrs = %{client_name: @local_mastodon_name, redirect_uris: "."} App.get_or_make(
scopes = ["read", "write", "follow", "push"] %{client_name: @local_mastodon_name, redirect_uris: "."},
["read", "write", "follow", "push"]
with %App{} = app <- Repo.get_by(App, find_attrs) do
{:ok, app} =
if app.scopes == scopes do
{:ok, app}
else
app
|> Changeset.change(%{scopes: scopes})
|> Repo.update()
end
{:ok, app}
else
_e ->
cs =
App.register_changeset(
%App{},
Map.put(find_attrs, :scopes, scopes)
) )
Repo.insert(cs)
end
end end
def logout(conn, _) do def logout(conn, _) do
@ -917,16 +887,8 @@ def logout(conn, _) do
|> redirect(to: "/") |> redirect(to: "/")
end end
def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do # Stubs for unimplemented mastodon api
Logger.debug("Unimplemented, returning unmodified relationship") #
with %User{} = target <- User.get_cached_by_id(id) do
conn
|> put_view(AccountView)
|> render("relationship.json", %{user: user, target: target})
end
end
def empty_array(conn, _) do def empty_array(conn, _) do
Logger.debug("Unimplemented, returning an empty array") Logger.debug("Unimplemented, returning an empty array")
json(conn, []) json(conn, [])
@ -1033,7 +995,7 @@ def account_register(
end end
end end
def account_register(%{assigns: %{app: _app}} = conn, _params) do def account_register(%{assigns: %{app: _app}} = conn, _) do
render_error(conn, :bad_request, "Missing parameters") render_error(conn, :bad_request, "Missing parameters")
end end

View file

@ -207,6 +207,7 @@ def unmute_conversation(%{assigns: %{user: user}} = conn, %{"id" => id}) do
end end
@doc "GET /api/v1/statuses/:id/card" @doc "GET /api/v1/statuses/:id/card"
@deprecated "https://github.com/tootsuite/mastodon/pull/11213"
def card(%{assigns: %{user: user}} = conn, %{"id" => status_id}) do def card(%{assigns: %{user: user}} = conn, %{"id" => status_id}) do
with %Activity{} = activity <- Activity.get_by_id(status_id), with %Activity{} = activity <- Activity.get_by_id(status_id),
true <- Visibility.visible_for_user?(activity, user) do true <- Visibility.visible_for_user?(activity, user) do

View file

@ -339,9 +339,7 @@ def render("card.json", %{rich_media: rich_media, page_url: page_url}) do
} }
end end
def render("card.json", _) do def render("card.json", _), do: nil
nil
end
def render("attachment.json", %{attachment: attachment}) do def render("attachment.json", %{attachment: attachment}) do
[attachment_url | _] = attachment["url"] [attachment_url | _] = attachment["url"]

View file

@ -5,6 +5,7 @@
defmodule Pleroma.Web.OAuth.App do defmodule Pleroma.Web.OAuth.App do
use Ecto.Schema use Ecto.Schema
import Ecto.Changeset import Ecto.Changeset
alias Pleroma.Repo
@type t :: %__MODULE__{} @type t :: %__MODULE__{}
@ -39,4 +40,29 @@ def register_changeset(struct, params \\ %{}) do
changeset changeset
end end
end end
@doc """
Gets app by attrs or create new with attrs.
And updates the scopes if need.
"""
@spec get_or_make(map(), list(String.t())) :: {:ok, App.t()} | {:error, Ecto.Changeset.t()}
def get_or_make(attrs, scopes) do
with %__MODULE__{} = app <- Repo.get_by(__MODULE__, attrs) do
update_scopes(app, scopes)
else
_e ->
%__MODULE__{}
|> register_changeset(Map.put(attrs, :scopes, scopes))
|> Repo.insert()
end
end
defp update_scopes(%__MODULE__{} = app, []), do: {:ok, app}
defp update_scopes(%__MODULE__{scopes: scopes} = app, scopes), do: {:ok, app}
defp update_scopes(%__MODULE__{} = app, scopes) do
app
|> change(%{scopes: scopes})
|> Repo.update()
end
end end

View file

@ -29,7 +29,7 @@ def register_user(params, opts \\ []) do
captcha_enabled = Pleroma.Config.get([Pleroma.Captcha, :enabled]) captcha_enabled = Pleroma.Config.get([Pleroma.Captcha, :enabled])
# true if captcha is disabled or enabled and valid, false otherwise # true if captcha is disabled or enabled and valid, false otherwise
captcha_ok = captcha_ok =
if !captcha_enabled do if not captcha_enabled do
:ok :ok
else else
Pleroma.Captcha.validate( Pleroma.Captcha.validate(

View file

@ -399,6 +399,17 @@ test "returns the relationships for the current user", %{conn: conn} do
assert to_string(other_user.id) == relationship["id"] assert to_string(other_user.id) == relationship["id"]
end end
test "returns an empty list on a bad request", %{conn: conn} do
user = insert(:user)
conn =
conn
|> assign(:user, user)
|> get("/api/v1/accounts/relationships", %{})
assert [] = json_response(conn, 200)
end
end end
describe "media upload" do describe "media upload" do
@ -533,6 +544,7 @@ test "respects limit_to_local_content == :unauthenticated for remote user nickna
end end
end end
describe "/api/v1/pleroma/mascot" do
test "mascot upload", %{conn: conn} do test "mascot upload", %{conn: conn} do
user = insert(:user) user = insert(:user)
@ -598,6 +610,7 @@ test "mascot retrieving", %{conn: conn} do
assert %{"url" => url, "type" => "image"} = json_response(conn, 200) assert %{"url" => url, "type" => "image"} = json_response(conn, 200)
assert url =~ "an_image" assert url =~ "an_image"
end end
end
test "getting followers", %{conn: conn} do test "getting followers", %{conn: conn} do
user = insert(:user) user = insert(:user)
@ -908,6 +921,7 @@ test "without notifications", %{conn: conn} do
end end
end end
describe "subscribing / unsubscribing" do
test "subscribing / unsubscribing to a user", %{conn: conn} do test "subscribing / unsubscribing to a user", %{conn: conn} do
user = insert(:user) user = insert(:user)
subscription_target = insert(:user) subscription_target = insert(:user)
@ -926,6 +940,33 @@ test "subscribing / unsubscribing to a user", %{conn: conn} do
assert %{"id" => _id, "subscribing" => false} = json_response(conn, 200) assert %{"id" => _id, "subscribing" => false} = json_response(conn, 200)
end end
end
describe "subscribing" do
test "returns 404 when subscription_target not found", %{conn: conn} do
user = insert(:user)
conn =
conn
|> assign(:user, user)
|> post("/api/v1/pleroma/accounts/target_id/subscribe")
assert %{"error" => "Record not found"} = json_response(conn, 404)
end
end
describe "unsubscribing" do
test "returns 404 when subscription_target not found", %{conn: conn} do
user = insert(:user)
conn =
conn
|> assign(:user, user)
|> post("/api/v1/pleroma/accounts/target_id/unsubscribe")
assert %{"error" => "Record not found"} = json_response(conn, 404)
end
end
test "getting a list of mutes", %{conn: conn} do test "getting a list of mutes", %{conn: conn} do
user = insert(:user) user = insert(:user)
@ -1573,6 +1614,17 @@ test "redirects to the getting-started page when referer is not present", %{conn
end end
describe "create account by app" do describe "create account by app" do
setup do
valid_params = %{
username: "lain",
email: "lain@example.org",
password: "PlzDontHackLain",
agreement: true
}
[valid_params: valid_params]
end
test "Account registration via Application", %{conn: conn} do test "Account registration via Application", %{conn: conn} do
conn = conn =
conn conn
@ -1616,6 +1668,7 @@ test "Account registration via Application", %{conn: conn} do
username: "lain", username: "lain",
email: "lain@example.org", email: "lain@example.org",
password: "PlzDontHackLain", password: "PlzDontHackLain",
bio: "Test Bio",
agreement: true agreement: true
}) })
@ -1634,6 +1687,18 @@ test "Account registration via Application", %{conn: conn} do
assert token_from_db.user.info.confirmation_pending assert token_from_db.user.info.confirmation_pending
end end
test "returns error when user already registred", %{conn: conn, valid_params: valid_params} do
_user = insert(:user, email: "lain@example.org")
app_token = insert(:oauth_token, user: nil)
conn =
conn
|> put_req_header("authorization", "Bearer " <> app_token.token)
res = post(conn, "/api/v1/accounts", valid_params)
assert json_response(res, 400) == %{"error" => "{\"email\":[\"has already been taken\"]}"}
end
test "rate limit", %{conn: conn} do test "rate limit", %{conn: conn} do
app_token = insert(:oauth_token, user: nil) app_token = insert(:oauth_token, user: nil)
@ -1677,6 +1742,41 @@ test "rate limit", %{conn: conn} do
assert json_response(conn, :too_many_requests) == %{"error" => "Throttled"} assert json_response(conn, :too_many_requests) == %{"error" => "Throttled"}
end end
test "returns bad_request if missing required params", %{
conn: conn,
valid_params: valid_params
} do
app_token = insert(:oauth_token, user: nil)
conn =
conn
|> put_req_header("authorization", "Bearer " <> app_token.token)
res = post(conn, "/api/v1/accounts", valid_params)
assert json_response(res, 200)
[{127, 0, 0, 1}, {127, 0, 0, 2}, {127, 0, 0, 3}, {127, 0, 0, 4}]
|> Stream.zip(valid_params)
|> Enum.each(fn {ip, {attr, _}} ->
res =
conn
|> Map.put(:remote_ip, ip)
|> post("/api/v1/accounts", Map.delete(valid_params, attr))
|> json_response(400)
assert res == %{"error" => "Missing parameters"}
end)
end
test "returns forbidden if token is invalid", %{conn: conn, valid_params: valid_params} do
conn =
conn
|> put_req_header("authorization", "Bearer " <> "invalid-token")
res = post(conn, "/api/v1/accounts", valid_params)
assert json_response(res, 403) == %{"error" => "Invalid credentials"}
end
end end
describe "GET /api/v1/polls/:id" do describe "GET /api/v1/polls/:id" do
@ -2019,4 +2119,115 @@ test "returns suggestions", %{conn: conn, user: user, other_user: other_user} do
] ]
end end
end end
describe "PUT /api/v1/media/:id" do
setup do
actor = insert(:user)
file = %Plug.Upload{
content_type: "image/jpg",
path: Path.absname("test/fixtures/image.jpg"),
filename: "an_image.jpg"
}
{:ok, %Object{} = object} =
ActivityPub.upload(
file,
actor: User.ap_id(actor),
description: "test-m"
)
[actor: actor, object: object]
end
test "updates name of media", %{conn: conn, actor: actor, object: object} do
media =
conn
|> assign(:user, actor)
|> put("/api/v1/media/#{object.id}", %{"description" => "test-media"})
|> json_response(:ok)
assert media["description"] == "test-media"
assert refresh_record(object).data["name"] == "test-media"
end
test "returns error wheb request is bad", %{conn: conn, actor: actor, object: object} do
media =
conn
|> assign(:user, actor)
|> put("/api/v1/media/#{object.id}", %{})
|> json_response(400)
assert media == %{"error" => "bad_request"}
end
end
describe "DELETE /auth/sign_out" do
test "redirect to root page", %{conn: conn} do
user = insert(:user)
conn =
conn
|> assign(:user, user)
|> delete("/auth/sign_out")
assert conn.status == 302
assert redirected_to(conn) == "/"
end
end
describe "GET /api/v1/accounts/:id/lists - account_lists" do
test "returns lists to which the account belongs", %{conn: conn} do
user = insert(:user)
other_user = insert(:user)
assert {:ok, %Pleroma.List{} = list} = Pleroma.List.create("Test List", user)
{:ok, %{following: _following}} = Pleroma.List.follow(list, other_user)
res =
conn
|> assign(:user, user)
|> get("/api/v1/accounts/#{other_user.id}/lists")
|> json_response(200)
assert res == [%{"id" => to_string(list.id), "title" => "Test List"}]
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 =
conn
|> assign(:user, user)
|> get("/api/v1/accounts/#{user.id}/identity_proofs")
|> json_response(200)
assert res == []
end
test "GET /api/v1/endorsements", %{conn: conn} do
user = insert(:user)
res =
conn
|> assign(:user, user)
|> get("/api/v1/endorsements")
|> json_response(200)
assert res == []
end
test "GET /api/v1/trends", %{conn: conn} do
user = insert(:user)
res =
conn
|> assign(:user, user)
|> get("/api/v1/trends")
|> json_response(200)
assert res == []
end
end
end end

View file

@ -0,0 +1,33 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.OAuth.AppTest do
use Pleroma.DataCase
alias Pleroma.Web.OAuth.App
import Pleroma.Factory
describe "get_or_make/2" do
test "gets exist app" do
attrs = %{client_name: "Mastodon-Local", redirect_uris: "."}
app = insert(:oauth_app, Map.merge(attrs, %{scopes: ["read", "write"]}))
{:ok, %App{} = exist_app} = App.get_or_make(attrs, [])
assert exist_app == app
end
test "make app" do
attrs = %{client_name: "Mastodon-Local", redirect_uris: "."}
{:ok, %App{} = app} = App.get_or_make(attrs, ["write"])
assert app.scopes == ["write"]
end
test "gets exist app and updates scopes" do
attrs = %{client_name: "Mastodon-Local", redirect_uris: "."}
app = insert(:oauth_app, Map.merge(attrs, %{scopes: ["read", "write"]}))
{:ok, %App{} = exist_app} = App.get_or_make(attrs, ["read", "write", "follow", "push"])
assert exist_app.id == app.id
assert exist_app.scopes == ["read", "write", "follow", "push"]
end
end
end