Files
toiminnanohjaus-django/apps/users/tests/application/test_use_cases.py
T
petriandClaude Opus 5.5 e7b2745916 Vaihe 1/1: users-moduuli, kirjautuminen ja käyttäjähallinta
- shared-moduuli: DomainError, EmailAddress, UnitOfWork, tapahtumat,
  TimestampedModel, daisyUI-lomakerenderöinti ja yhteiset pohjat
- users-moduuli Clean Architecture -kerroksin: oma käyttäjämalli
  (AUTH_USER_MODEL), roolit ja oikeudet, harjoittelija-, vastuuhenkilö-
  ja viimeisen pääkäyttäjän säännöt
- kirjautuminen sähköpostilla, yritysten rajoitus, "muista minut",
  istunnon katkaisu kun tunnus poistetaan käytöstä tai harjoittelu päättyy
- kertakäyttöiset salasanalinkit (72 h / 60 min, uusi mitätöi vanhan),
  salasanasääntö ja create_admin-komento
- käyttäjähallinta: lista (HTMX-haku), lomakkeet ja kopioitava linkki
- Tailwind 4 + daisyUI 5 + HTMX + Alpine npm-buildilla, suomennokset
- testit: domain, application (fakeilla), integraatio ja selaintestit
  (axe, vaalea/tumma, 1920/320 px); ruff, mypy ja import-linter
- dokumentit päivitetty toteutuksen mukaisiksi

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 13:20:24 +02:00

180 lines
6.9 KiB
Python

from datetime import date
import pytest
from apps.shared.domain.value_objects import EmailAddress
from apps.users.application.dto import PasswordLinkPurpose, UserDetailsData
from apps.users.application.use_cases import (
CheckLoginAllowed,
CreateUser,
IssuePasswordLink,
RequestPasswordReset,
UpdateUser,
)
from apps.users.domain.enums import Role
from apps.users.domain.exceptions import (
EmailAlreadyTaken,
InvalidSupervisor,
LastActiveAdmin,
SupervisorHasInterns,
UserNotFound,
)
from apps.users.tests.fakes import (
FakePasswordLinkService,
FakeUnitOfWork,
FixedClock,
InMemoryUserRepository,
account,
)
TODAY = date(2026, 3, 1)
@pytest.fixture
def repo() -> InMemoryUserRepository:
return InMemoryUserRepository()
@pytest.fixture
def links() -> FakePasswordLinkService:
return FakePasswordLinkService()
def details(**overrides: object) -> UserDetailsData:
base: dict[str, object] = {
"name": "Eeva Employee",
"email": "[email protected]",
"role": Role.EMPLOYEE,
}
return UserDetailsData(**{**base, **overrides}) # type: ignore[arg-type]
class TestCreateUser:
def test_creates_user_and_emails_setup_link(
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
) -> None:
created = CreateUser(repo, FakeUnitOfWork(), links).execute(details())
assert repo.get_by_id(created.user_id) is not None
assert links.issued == [(created.user_id, PasswordLinkPurpose.SETUP)]
assert links.sent == [("[email protected]", PasswordLinkPurpose.SETUP)]
assert created.password_link.emailed
def test_email_must_be_unique(
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
) -> None:
repo.save(account(email=EmailAddress("[email protected]")))
with pytest.raises(EmailAlreadyTaken):
CreateUser(repo, FakeUnitOfWork(), links).execute(details(email="[email protected]"))
def test_failed_email_still_creates_user(self, repo: InMemoryUserRepository) -> None:
links = FakePasswordLinkService(send_ok=False)
created = CreateUser(repo, FakeUnitOfWork(), links).execute(details())
assert repo.get_by_id(created.user_id) is not None
assert not created.password_link.emailed
def test_intern_supervisor_must_be_active_employee_or_management(
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
) -> None:
sub = repo.save(account(email=EmailAddress("[email protected]"), role=Role.SUBCONTRACTOR))
with pytest.raises(InvalidSupervisor):
CreateUser(repo, FakeUnitOfWork(), links).execute(
details(
role=Role.INTERN, employment_ends_on=date(2026, 6, 30), supervisor_id=sub.id
)
)
class TestUpdateUser:
def test_last_active_admin_cannot_be_deactivated(self, repo: InMemoryUserRepository) -> None:
admin = repo.save(account(role=Role.ADMIN))
with pytest.raises(LastActiveAdmin):
UpdateUser(repo, FakeUnitOfWork()).execute(
admin.id, # type: ignore[arg-type]
details(name="Admin", email="[email protected]", role=Role.ADMIN, is_active=False),
)
assert repo.locked
def test_last_active_admin_cannot_change_role(self, repo: InMemoryUserRepository) -> None:
admin = repo.save(account(role=Role.ADMIN))
with pytest.raises(LastActiveAdmin):
UpdateUser(repo, FakeUnitOfWork()).execute(
admin.id, # type: ignore[arg-type]
details(email="[email protected]", role=Role.MANAGEMENT),
)
def test_admin_can_be_deactivated_when_another_exists(
self, repo: InMemoryUserRepository
) -> None:
admin = repo.save(account(role=Role.ADMIN))
repo.save(account(role=Role.ADMIN, email=EmailAddress("[email protected]")))
UpdateUser(repo, FakeUnitOfWork()).execute(
admin.id, # type: ignore[arg-type]
details(email="[email protected]", role=Role.ADMIN, is_active=False),
)
assert not repo.get_by_id(admin.id).is_active # type: ignore[arg-type, union-attr]
def test_supervisor_with_active_interns_cannot_be_deactivated(
self, repo: InMemoryUserRepository
) -> None:
boss = repo.save(account(role=Role.EMPLOYEE))
repo.save(
account(
email=EmailAddress("[email protected]"),
role=Role.INTERN,
employment_ends_on=date(2026, 6, 30),
supervisor_id=boss.id,
)
)
with pytest.raises(SupervisorHasInterns):
UpdateUser(repo, FakeUnitOfWork()).execute(
boss.id, # type: ignore[arg-type]
details(email="[email protected]", is_active=False),
)
def test_unknown_user(self, repo: InMemoryUserRepository) -> None:
with pytest.raises(UserNotFound):
UpdateUser(repo, FakeUnitOfWork()).execute(99, details())
class TestPasswordLinks:
def test_issue_link_for_existing_user(
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
) -> None:
user = repo.save(account())
link = IssuePasswordLink(repo, links).execute(user.id) # type: ignore[arg-type]
assert link.emailed
assert links.issued == [(user.id, PasswordLinkPurpose.SETUP)]
def test_reset_is_sent_to_user_who_may_log_in(
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
) -> None:
repo.save(account())
RequestPasswordReset(repo, links, FixedClock(TODAY)).execute("[email protected]")
assert links.sent == [("[email protected]", PasswordLinkPurpose.RESET)]
@pytest.mark.parametrize("email", ["[email protected]", "not an email", ""])
def test_reset_does_nothing_for_unknown_address(
self, repo: InMemoryUserRepository, links: FakePasswordLinkService, email: str
) -> None:
RequestPasswordReset(repo, links, FixedClock(TODAY)).execute(email)
assert links.issued == []
def test_reset_is_not_sent_to_ended_intern(
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
) -> None:
repo.save(account(role=Role.INTERN, employment_ends_on=date(2026, 2, 28), supervisor_id=9))
RequestPasswordReset(repo, links, FixedClock(TODAY)).execute("[email protected]")
assert links.issued == []
class TestCheckLoginAllowed:
def test_allowed_and_denied(self, repo: InMemoryUserRepository) -> None:
active = repo.save(account())
inactive = repo.save(account(email=EmailAddress("[email protected]"), is_active=False))
check = CheckLoginAllowed(repo, FixedClock(TODAY))
assert check.execute(active.id) # type: ignore[arg-type]
assert not check.execute(inactive.id) # type: ignore[arg-type]
assert not check.execute(12345)