1
0
mirror of https://github.com/danbee/chess synced 2025-03-04 08:39:06 +00:00

Add API controller test

This commit is contained in:
Daniel Barber 2018-02-19 16:09:57 -05:00
parent 5511ef0a06
commit c2bb7f3052
Signed by: danbarber
GPG Key ID: 931D8112E0103DD8
4 changed files with 83 additions and 7 deletions

View File

@ -6,9 +6,16 @@ defmodule Chess.Auth.ErrorHandler do
import Plug.Conn import Plug.Conn
def auth_error(conn, {_type, _reason}, _opts) do def auth_error(conn, {_type, _reason}, _opts) do
conn case get_format(conn) do
|> put_flash(:info, "You must be logged in") "html" ->
|> redirect(to: "/") conn
|> halt() |> put_flash(:info, "You must be logged in")
|> redirect(to: "/")
|> halt()
"json" ->
conn
|> put_status(403)
|> json(%{status: 403, message: "Not authorized"})
end
end end
end end

View File

@ -32,4 +32,8 @@ defmodule ChessWeb.Api.GameController do
Map.put(board, "#{to_file},#{to_rank}", piece) Map.put(board, "#{to_file},#{to_rank}", piece)
end end
defp current_user(conn) do
Guardian.Plug.current_resource(conn)
end
end end

View File

@ -18,6 +18,7 @@ defmodule ChessWeb.Router do
end end
pipeline :api do pipeline :api do
plug :fetch_session
plug :accepts, ["json"] plug :accepts, ["json"]
end end
@ -39,9 +40,9 @@ defmodule ChessWeb.Router do
end end
# Other scopes may use custom stacks. # Other scopes may use custom stacks.
scope "/api", ChessWeb do scope "/api", as: :api do
pipe_through :api pipe_through [:api, :auth, :ensure_auth]
resources "/games", Api.GameController, only: [:show, :update] resources "/games", ChessWeb.Api.GameController, only: [:show, :update]
end end
end end

View File

@ -0,0 +1,64 @@
defmodule Chess.ApiGameControllerTest do
use ChessWeb.ConnCase
alias Chess.Auth.Guardian
import Chess.Factory,
only: [create_user: 0, create_user: 2, create_game_for: 2]
test "shows chosen game", %{conn: conn} do
user = create_user()
opponent = create_user("revali", "vahmedoh")
game = create_game_for(user, opponent)
conn =
conn
|> login(user)
|> get(api_game_path(conn, :show, game))
assert json_response(conn, 200)
end
test "does not show a game if the user is not a player", %{conn: conn} do
user = create_user()
opponent = create_user("revali", "vahmedoh")
game = create_game_for(user, opponent)
other_user = create_user("mipha", "ilovelink")
conn =
conn
|> login(other_user)
assert_error_sent 404, fn ->
get conn, api_game_path(conn, :show, game.id)
end
end
test "responds with 403 if user is not logged in", %{conn: conn} do
user = create_user()
opponent = create_user("revali", "vahmedoh")
game = create_game_for(user, opponent)
conn =
conn
|> get(api_game_path(conn, :show, game.id))
assert json_response(conn, 403)
end
test "renders page not found when id is nonexistent", %{conn: conn} do
user = create_user()
conn = login(conn, user)
assert_error_sent 404, fn ->
get conn, api_game_path(conn, :show, -1)
end
end
defp login(conn, user) do
conn
|> Guardian.Plug.sign_in(user)
end
end