Implement tests for token creation

This commit is contained in:
Nat 2023-06-08 09:41:02 -07:00
parent 1468d21c57
commit 711353398c
Signed by: nat
GPG Key ID: B53AB05285D710D6
4 changed files with 43 additions and 3 deletions

View File

@ -24,7 +24,8 @@ defmodule Hostas.Denizen do
# Hash the password
defp hash_password(%Ecto.Changeset{valid?: true, changes: %{password: password}} = changeset) do
change(changeset, Bcrypt.add_hash(password))
%{password_hash: hash} = Bcrypt.add_hash(password)
change(changeset, password: hash)
end
defp hash_password(changeset), do: changeset
end

View File

@ -50,8 +50,7 @@ defmodule HostasWeb.Auth.TokenController do
def create(conn, params) do
conn
|> put_status(422)
|> json(params)
# |> json(%{"error" => "Missing required parameters"})
|> json(%{"error" => "Missing required parameters"})
end
@doc """

View File

@ -0,0 +1,39 @@
defmodule HostasWeb.Auth.TokenControllerTest do
use HostasWeb.ConnCase
# For testing with Ecto
alias Hostas.Repo
alias Hostas.Denizen
@denizen_data %{handle: "testuser", name: "Test User", password: "password"}
defp create_denizen, do: Repo.insert!(Denizen.changeset(%Denizen{}, @denizen_data))
describe "token create" do
test "creates a token", %{conn: conn} do
create_denizen()
conn = post(conn, ~p"/hostapi/auth/token", %{handle: "testuser", password: "password"})
assert Map.has_key?(json_response(conn, 201), "token")
assert Map.has_key?(json_response(conn, 201), "expires")
end
test "fails due to password mismatch", %{conn: conn} do
create_denizen()
conn = post(conn, ~p"/hostapi/auth/token", %{handle: "testuser", password: "incorrect"})
assert json_response(conn, 401)["error"] == "Password mismatch"
end
test "fails due to non-existant denizen", %{conn: conn} do
conn = post(conn, ~p"/hostapi/auth/token", %{handle: "testuser", password: "password"})
assert json_response(conn, 404)["error"] == "No user with handle testuser"
end
test "fails due to missing fields", %{conn: conn} do
conn = post(conn, ~p"/hostapi/auth/token", %{password: "password"})
assert json_response(conn, 422)["error"] == "Missing required parameters"
end
end
end

View File

@ -33,6 +33,7 @@ defmodule HostasWeb.ConnCase do
setup tags do
Hostas.DataCase.setup_sandbox(tags)
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end