lecutre 07

This commit is contained in:
SowinskiBraeden committed 2026-10-23 13:43:58 -07:00
1 parent 15fbe95787
commit fa887da9ca
122 files changed
+9723

No files matched your search

@@ -0,0 +1,79 @@
defmodule BcitWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use BcitWeb.ConnCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# The default endpoint for testing
@endpoint BcitWeb.Endpoint
use BcitWeb, :verified_routes
# Import conveniences for testing with connections
import Plug.Conn
import Phoenix.ConnTest
import BcitWeb.ConnCase
end
end
setup tags do
Bcit.DataCase.setup_sandbox(tags)
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
@doc """
Setup helper that registers and logs in users.
setup :register_and_log_in_user
It stores an updated connection and a registered user in the
test context.
"""
def register_and_log_in_user(%{conn: conn} = context) do
user = Bcit.AccountsFixtures.user_fixture()
scope = Bcit.Accounts.Scope.for_user(user)
opts =
context
|> Map.take([:token_authenticated_at])
|> Enum.into([])
%{conn: log_in_user(conn, user, opts), user: user, scope: scope}
end
@doc """
Logs the given `user` into the `conn`.
It returns an updated `conn`.
"""
def log_in_user(conn, user, opts \\ []) do
token = Bcit.Accounts.generate_user_session_token(user)
maybe_set_token_authenticated_at(token, opts[:token_authenticated_at])
conn
|> Phoenix.ConnTest.init_test_session(%{})
|> Plug.Conn.put_session(:user_token, token)
end
defp maybe_set_token_authenticated_at(_token, nil), do: nil
defp maybe_set_token_authenticated_at(token, authenticated_at) do
Bcit.AccountsFixtures.override_token_authenticated_at(token, authenticated_at)
end
end
@@ -0,0 +1,58 @@
defmodule Bcit.DataCase do
@moduledoc """
This module defines the setup for tests requiring
access to the application's data layer.
You may define functions here to be used as helpers in
your tests.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use Bcit.DataCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
alias Bcit.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Bcit.DataCase
end
end
setup tags do
Bcit.DataCase.setup_sandbox(tags)
:ok
end
@doc """
Sets up the sandbox based on the test tags.
"""
def setup_sandbox(tags) do
pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Bcit.Repo, shared: not tags[:async])
on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
end
@doc """
A helper that transforms changeset errors into a map of messages.
assert {:error, changeset} = Accounts.create_user(%{password: "short"})
assert "password is too short" in errors_on(changeset).password
assert %{password: ["password is too short"]} = errors_on(changeset)
"""
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
@@ -0,0 +1,89 @@
defmodule Bcit.AccountsFixtures do
@moduledoc """
This module defines test helpers for creating
entities via the `Bcit.Accounts` context.
"""
import Ecto.Query
alias Bcit.Accounts
alias Bcit.Accounts.Scope
def unique_user_email, do: "user#{System.unique_integer()}@example.com"
def valid_user_password, do: "hello world!"
def valid_user_attributes(attrs \\ %{}) do
Enum.into(attrs, %{
email: unique_user_email()
})
end
def unconfirmed_user_fixture(attrs \\ %{}) do
{:ok, user} =
attrs
|> valid_user_attributes()
|> Accounts.register_user()
user
end
def user_fixture(attrs \\ %{}) do
user = unconfirmed_user_fixture(attrs)
token =
extract_user_token(fn url ->
Accounts.deliver_login_instructions(user, url)
end)
{:ok, {user, _expired_tokens}} =
Accounts.login_user_by_magic_link(token)
user
end
def user_scope_fixture do
user = user_fixture()
user_scope_fixture(user)
end
def user_scope_fixture(user) do
Scope.for_user(user)
end
def set_password(user) do
{:ok, {user, _expired_tokens}} =
Accounts.update_user_password(user, %{password: valid_user_password()})
user
end
def extract_user_token(fun) do
{:ok, captured_email} = fun.(&"[TOKEN]#{&1}[TOKEN]")
[_, token | _] = String.split(captured_email.text_body, "[TOKEN]")
token
end
def override_token_authenticated_at(token, authenticated_at) when is_binary(token) do
Bcit.Repo.update_all(
from(t in Accounts.UserToken,
where: t.token == ^token
),
set: [authenticated_at: authenticated_at]
)
end
def generate_user_magic_link_token(user) do
{encoded_token, user_token} = Accounts.UserToken.build_email_token(user, "login")
Bcit.Repo.insert!(user_token)
{encoded_token, user_token.token}
end
def offset_user_token(token, amount_to_add, unit) do
dt = DateTime.add(DateTime.utc_now(:second), amount_to_add, unit)
Bcit.Repo.update_all(
from(ut in Accounts.UserToken, where: ut.token == ^token),
set: [inserted_at: dt, authenticated_at: dt]
)
end
end
@@ -0,0 +1,30 @@
defmodule Bcit.SchoolsFixtures do
@moduledoc """
This module defines test helpers for creating
entities via the `Bcit.Schools` context.
"""
@doc """
Generate a unique student sid.
"""
def unique_student_sid do
"A" <> (System.unique_integer([:positive]) |> Integer.to_string() |> String.pad_leading(8, "0"))
end
@doc """
Generate a student.
"""
def student_fixture(attrs \\ %{}) do
{:ok, student} =
attrs
|> Enum.into(%{
firstname: "some firstname",
gpa: 85.5,
lastname: "some lastname",
sid: unique_student_sid()
})
|> Bcit.Schools.create_student()
student
end
end