birdy_chat/test/birdy_chat_web/api/internal/messages_test.exs

82 lines
2.5 KiB
Elixir

defmodule BirdyChatWeb.Api.Internal.MessagesTest do
use BirdyChatWeb.ConnCase, async: true
setup do
url = ~p"/api/internal"
%{url: url}
end
describe "authorisation" do
setup %{conn: conn} do
conn =
conn
|> put_req_header("content-type", "application/json")
%{conn: conn}
end
test "returns 403 when authorisation token is missing", %{url: url, conn: conn} do
message = %{"from" => "test2-user", "to" => "test2-someone", "message" => "123"}
body = Jason.encode!(message)
conn = post(conn, url, body)
assert result = json_response(conn, :forbidden)
assert result == %{"errors" => %{"general" => "Unauthorised"}}
end
test "returns 403 when authorisation token is invalid", %{url: url, conn: conn} do
server_id = "test2-user"
token = Phoenix.Token.sign(BirdyChatWeb.Endpoint, "FakeAuth", server_id)
conn =
conn
|> put_req_header("content-type", "application/json")
|> put_req_header("authorization", token)
message = %{"from" => "test2-user", "to" => "test2-someone", "message" => "123"}
body = Jason.encode!(message)
conn = post(conn, url, body)
assert result = json_response(conn, :forbidden)
assert result == %{"errors" => %{"general" => "Unauthorised"}}
end
end
describe "POST /api/server/messages" do
setup %{conn: conn} do
unique_user_id = System.unique_integer([:positive])
username = "test1-user#{unique_user_id}"
path = Application.app_dir(:birdy_chat, ["priv", "messages", "#{username}.txt"])
on_exit(fn -> File.rm(path) end)
server_id = "test2-user"
token = Phoenix.Token.sign(BirdyChatWeb.Endpoint, "serverAuth", server_id)
conn =
conn
|> put_req_header("content-type", "application/json")
|> put_req_header("authorization", token)
%{conn: conn, username: username, path: path}
end
test "saves message locally", %{conn: conn, username: username, url: url, path: path} do
message = %{"from" => "test2-user", "to" => username, "message" => "123"}
body = Jason.encode!(message)
conn = post(conn, url, body)
assert result = json_response(conn, :created)
expected_result = %{
"from" => "test2-user",
"message" => "123",
"to" => username,
"routing" => "local",
"server" => "test1"
}
assert result == expected_result
contents = File.read!(path)
assert contents == "test2-user: 123\n"
end
end
end