1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
"""
:Copyright: 2014-2025 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from flask import g
from flask_babel import lazy_gettext
import pytest

from byceps.util.authz import (
    has_current_user_any_permission,
    has_current_user_permission,
    register_permissions,
)


register_permissions(
    'chill',
    [
        ('browse_the_web', lazy_gettext('Browse the web')),
        ('play_video_games', lazy_gettext('Play video games')),
        ('watch_movies', lazy_gettext('Watch movies')),
    ],
)


class CurrentUserMock:
    def __init__(self, permissions: set[str]) -> None:
        self.permissions = permissions


@pytest.mark.parametrize(
    ('permissions_assigned', 'permission_requested', 'expected'),
    [
        (
            {},
            'chill.browse_the_web',
            False,
        ),
        (
            {'chill.watch_movies'},
            'chill.play_video_games',
            False,
        ),
        (
            {'chill.watch_movies'},
            'chill.watch_movies',
            True,
        ),
        (
            {
                'chill.browse_the_web',
                'chill.play_video_games',
            },
            'chill.watch_movies',
            False,
        ),
        (
            {
                'chill.browse_the_web',
                'chill.play_video_games',
            },
            'chill.play_video_games',
            True,
        ),
    ],
)
def test_has_current_user_permission(
    site_app, permissions_assigned, permission_requested, expected
):
    g.user = CurrentUserMock(permissions_assigned)
    assert has_current_user_permission(permission_requested) == expected


@pytest.mark.parametrize(
    ('permissions_assigned', 'permissions_requested', 'expected'),
    [
        (
            {},
            {
                'chill.browse_the_web',
            },
            False,
        ),
        (
            {'chill.watch_movies'},
            {
                'chill.browse_the_web',
                'chill.play_video_games',
            },
            False,
        ),
        (
            {'chill.watch_movies'},
            {
                'chill.play_video_games',
                'chill.watch_movies',
            },
            True,
        ),
    ],
)
def test_has_current_user_any_permission(
    site_app, permissions_assigned, permissions_requested, expected
):
    g.user = CurrentUserMock(permissions_assigned)
    assert has_current_user_any_permission(*permissions_requested) == expected