|
| 1 | +"""Tests for surface access template tags.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import pytest |
| 6 | +from django.contrib.auth.models import AnonymousUser, Group |
| 7 | + |
| 8 | +from accounts.templatetags.surface_access import ( |
| 9 | + can_access_surface, |
| 10 | + has_group, |
| 11 | + is_admin_surface_user, |
| 12 | +) |
| 13 | +from tests.factories import UserFactory |
| 14 | + |
| 15 | +pytestmark = pytest.mark.django_db |
| 16 | + |
| 17 | + |
| 18 | +def add_group(user, group_name: str) -> None: |
| 19 | + """Attach a Django group to a user for test setup.""" |
| 20 | + |
| 21 | + group, _ = Group.objects.get_or_create(name=group_name) |
| 22 | + user.groups.add(group) |
| 23 | + |
| 24 | + |
| 25 | +def test_has_group_returns_true_for_matching_role_group() -> None: |
| 26 | + """The template filter should confirm membership for valid mapped roles.""" |
| 27 | + |
| 28 | + merchant_user = UserFactory() |
| 29 | + add_group(merchant_user, "merchant") |
| 30 | + |
| 31 | + assert has_group(merchant_user, "merchant") is True |
| 32 | + |
| 33 | + |
| 34 | +def test_has_group_returns_false_for_unknown_role() -> None: |
| 35 | + """The template filter should reject unknown role keys.""" |
| 36 | + |
| 37 | + user = UserFactory() |
| 38 | + |
| 39 | + assert has_group(user, "unknown") is False |
| 40 | + |
| 41 | + |
| 42 | +def test_can_access_surface_returns_true_for_allowed_surface() -> None: |
| 43 | + """The template filter should mirror the shared surface access helper.""" |
| 44 | + |
| 45 | + customer_user = UserFactory() |
| 46 | + add_group(customer_user, "customer") |
| 47 | + |
| 48 | + assert can_access_surface(customer_user, "customer") is True |
| 49 | + |
| 50 | + |
| 51 | +def test_can_access_surface_returns_false_for_unknown_surface() -> None: |
| 52 | + """Unknown surface names should be rejected by the template filter.""" |
| 53 | + |
| 54 | + user = UserFactory() |
| 55 | + |
| 56 | + assert can_access_surface(user, "unknown") is False |
| 57 | + |
| 58 | + |
| 59 | +def test_is_admin_surface_user_returns_true_for_superuser() -> None: |
| 60 | + """The simple tag should identify admin-capable users.""" |
| 61 | + |
| 62 | + admin_user = UserFactory(is_superuser=True, is_staff=True) |
| 63 | + |
| 64 | + assert is_admin_surface_user(admin_user) is True |
| 65 | + |
| 66 | + |
| 67 | +def test_is_admin_surface_user_returns_false_for_anonymous_user() -> None: |
| 68 | + """Anonymous users should never be treated as admin-capable.""" |
| 69 | + |
| 70 | + assert is_admin_surface_user(AnonymousUser()) is False |
0 commit comments