Exemple #1
0
        room['room'].available_equipment = room['equipment']
    db.session.flush()
    results = list(Room.get_with_data(only_active=only_active))
    assert len(results) == len(rooms) - only_active
    for row in results:
        room = row.pop('room')
        room_type = room_types[room]
        if room_type == 'inactive':
            assert not only_active


@pytest.mark.parametrize(
    ('has_booking', 'has_blocking', 'has_pre_booking', 'include_pre_bookings',
     'has_pending_blocking', 'include_pending_blockings', 'filtered'),
    set(
        bool_matrix('00.0.0', expect=False) +  # nothing confirmed/pending
        bool_matrix('000.0.', expect=False) +  # nothing pending included
        bool_matrix('1.....', expect=True) +  # confirmed booking
        bool_matrix('.1....', expect=True) +  # active blocking
        bool_matrix('00....', expect=lambda x: all(x[2:4]) or all(x[4:6]))
    )  # included pending booking/blocking
)
def test_filter_available(dummy_room, create_reservation, create_blocking,
                          has_booking, has_blocking, has_pre_booking,
                          include_pre_bookings, has_pending_blocking,
                          include_pending_blockings, filtered):
    if has_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(8)),
                           end_dt=datetime.combine(date.today(), time(10)))
    if has_pre_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(10)),
Exemple #2
0
def test_max_capacity(create_room):
    assert not Room.query.count()
    assert Room.max_capacity == 0
    create_room(capacity=0)
    assert Room.max_capacity == 0
    create_room(capacity=10)
    create_room(capacity=5)
    assert Room.max_capacity == 10


@pytest.mark.parametrize(
    ('has_booking', 'has_blocking',
     'has_pre_booking', 'include_pre_bookings',
     'has_pending_blocking', 'include_pending_blockings',
     'filtered'),
    set(bool_matrix('00.0.0', expect=False) +                                # nothing confirmed/pending
        bool_matrix('000.0.', expect=False) +                                # nothing pending included
        bool_matrix('1.....', expect=True) +                                 # confirmed booking
        bool_matrix('.1....', expect=True) +                                 # active blocking
        bool_matrix('00....', expect=lambda x: all(x[2:4]) or all(x[4:6])))  # included pending booking/blocking
)
def test_filter_available(dummy_room, create_reservation, create_blocking,
                          has_booking, has_blocking,
                          has_pre_booking, include_pre_bookings,
                          has_pending_blocking, include_pending_blockings, filtered):
    if has_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(8)),
                           end_dt=datetime.combine(date.today(), time(10)))
    if has_pre_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(10)),
                           end_dt=datetime.combine(date.today(), time(12)),
    (ChangeType.deleted, False),
    (ChangeType.data_changed, False),
    (ChangeType.protection_changed, True),
    (ChangeType.moved, True),
))
@pytest.mark.usefixtures('queue_entry_dummy_object')
def test_process_records_cascade(mocker, change, cascade):
    """Test if certain changes cascade to child elements"""
    cascade_mock = mocker.patch(
        'indico_livesync.simplify._process_cascaded_category_contents')
    records = [LiveSyncQueueEntry(change=change)]
    process_records(records)
    assert cascade_mock.call_args == (({records[0]} if cascade else set(), ), )


@pytest.mark.parametrize('changes', bool_matrix('......'))
def test_process_records_simplify(changes, mocker, db, create_event,
                                  dummy_agent):
    """Test if queue entries for the same object are properly simplified"""
    event1 = create_event(id_=1)
    event2 = create_event(id_=2)

    db.session.add(dummy_agent)
    db.session.add(event1)
    db.session.add(event2)

    refs = ({
        'type': EntryType.event,
        'event_id': event1.id
    }, {
        'type': EntryType.event,
Exemple #4
0
        create_blocking(start_date=date(2014, 12, 5), end_date=date(2014, 12, 7)),
        create_blocking(start_date=date(2014, 12, 6), end_date=date(2014, 12, 8)),
    ]
    filters = {"start_date": start_date, "end_date": end_date}
    assert set(BlockedRoom.find_with_filters(filters)) == set(blockings[i].blocked_rooms[0] for i in matches)


@pytest.mark.parametrize("state", BlockedRoom.State)
def test_find_with_filters_state(create_blocking, state):
    other_state = next(s for s in BlockedRoom.State if s != state)
    create_blocking(state=other_state)
    blocking = create_blocking(state=state)
    assert set(BlockedRoom.find_with_filters({"state": state})) == {blocking.blocked_rooms[0]}


@pytest.mark.parametrize(("with_user", "with_reason"), bool_matrix(".."))
def test_reject(dummy_user, dummy_blocking, smtp, with_user, with_reason):
    br = dummy_blocking.blocked_rooms[0]
    assert br.state == BlockedRoom.State.pending
    kwargs = {}
    if with_user:
        kwargs["user"] = dummy_user
    if with_reason:
        kwargs["reason"] = u"foo"
    br.reject(**kwargs)
    assert br.state == BlockedRoom.State.rejected
    mail = extract_emails(smtp, one=True, to=dummy_blocking.created_by_user.email, subject="Room blocking REJECTED")
    if with_reason:
        assert kwargs["reason"] in mail.as_string()
    assert not smtp.outbox
Exemple #5
0
    calls = []
    with signals.acl.can_access.connected_to(_signal_fn_late, sender=Event):
        event.can_access(dummy_user)
    assert calls == [None, True]

    # late check - signal invoked twice, once with the regular access state
    calls = []
    event.protection_mode = ProtectionMode.protected
    with signals.acl.can_access.connected_to(_signal_fn_late, sender=Event):
        event.can_access(dummy_user)
    assert calls == [None, False]


@pytest.mark.parametrize(
    ('is_admin', 'allow_admin', 'not_explicit', 'expected'),
    bool_matrix('...', expect=all))
def test_can_manage_admin(create_event, create_user, is_admin, allow_admin,
                          not_explicit, expected):
    event = create_event()
    user = create_user(123, admin=is_admin)
    assert event.can_manage(user,
                            allow_admin=allow_admin,
                            explicit_permission=not not_explicit) == expected


def test_can_manage_guest(create_event, dummy_category):
    event = create_event()
    # we grant explicit management access on the parent to ensure that
    # we don't even check there but bail out early
    event.category = dummy_category
    event.category.can_manage = MagicMock(return_value=True)
Exemple #6
0
    # late check - signal invoked twice, once with the regular access state
    calls = []
    with signals.acl.can_access.connected_to(_signal_fn_late, sender=Event):
        event.can_access(dummy_user)
    assert calls == [None, True]

    # late check - signal invoked twice, once with the regular access state
    calls = []
    event.protection_mode = ProtectionMode.protected
    with signals.acl.can_access.connected_to(_signal_fn_late, sender=Event):
        event.can_access(dummy_user)
    assert calls == [None, False]


@pytest.mark.parametrize(('is_admin', 'allow_admin', 'not_explicit', 'expected'), bool_matrix('...', expect=all))
def test_can_manage_admin(create_event, create_user, is_admin, allow_admin, not_explicit, expected):
    event = create_event()
    user = create_user(123, admin=is_admin)
    assert event.can_manage(user, allow_admin=allow_admin, explicit_role=not not_explicit) == expected


def test_can_manage_guest(create_event, dummy_category):
    event = create_event()
    # we grant explicit management access on the parent to ensure that
    # we don't even check there but bail out early
    event.category = dummy_category
    event.category.can_manage = MagicMock(return_value=True)
    assert not event.can_manage(None)

                                end_dt=date.today() + relativedelta(hour=5))
    return db_occ, occ


# ======================================================================================================================
# Hybrid property tests
# ======================================================================================================================


def test_date(dummy_occurrence):
    assert dummy_occurrence.date == date.today()
    assert ReservationOccurrence.find_first(date=date.today()) == dummy_occurrence


@pytest.mark.parametrize(('is_rejected', 'is_cancelled', 'expected'),
                         bool_matrix('..', expect=lambda x: not any(x)))
def test_is_valid(db, dummy_occurrence, is_rejected, is_cancelled, expected):
    dummy_occurrence.is_rejected = is_rejected
    dummy_occurrence.is_cancelled = is_cancelled
    db.session.flush()
    assert dummy_occurrence.is_valid == expected
    assert ReservationOccurrence.find_first(is_valid=expected) == dummy_occurrence


# ======================================================================================================================
# staticmethod tests
# ======================================================================================================================


def test_create_series_for_reservation(dummy_reservation):
    occurrences = ReservationOccurrence.iter_create_occurrences(start=dummy_reservation.start_dt,
Exemple #8
0
    ]
    filters = {'start_date': start_date, 'end_date': end_date}
    assert set(BlockedRoom.find_with_filters(filters)) == set(
        blockings[i].blocked_rooms[0] for i in matches)


@pytest.mark.parametrize('state', BlockedRoom.State)
def test_find_with_filters_state(create_blocking, state):
    other_state = next(s for s in BlockedRoom.State if s != state)
    create_blocking(state=other_state)
    blocking = create_blocking(state=state)
    assert set(BlockedRoom.find_with_filters(
        {'state': state})) == {blocking.blocked_rooms[0]}


@pytest.mark.parametrize(('with_user', 'with_reason'), bool_matrix('..'))
def test_reject(dummy_user, dummy_blocking, smtp, with_user, with_reason):
    br = dummy_blocking.blocked_rooms[0]
    assert br.state == BlockedRoom.State.pending
    kwargs = {}
    if with_user:
        kwargs['user'] = dummy_user
    if with_reason:
        kwargs['reason'] = u'foo'
    br.reject(**kwargs)
    assert br.state == BlockedRoom.State.rejected
    mail = extract_emails(smtp,
                          one=True,
                          to=dummy_blocking.created_by_user.getEmail(),
                          subject='Room blocking REJECTED')
    if with_reason:
    (ChangeType.created,            False),
    (ChangeType.deleted,            False),
    (ChangeType.data_changed,       False),
    (ChangeType.protection_changed, True),
    (ChangeType.moved,              True),
))
@pytest.mark.usefixtures('queue_entry_dummy_object')
def test_process_records_cascade(mocker, change, cascade):
    """Test if certain changes cascade to child elements"""
    cascade_mock = mocker.patch('indico_livesync.simplify._process_cascaded_category_contents')
    records = [LiveSyncQueueEntry(change=change)]
    process_records(records)
    assert cascade_mock.call_args == (({records[0]} if cascade else set(),),)


@pytest.mark.parametrize('changes', bool_matrix('......'))
def test_process_records_simplify(changes, mocker, db, create_event, dummy_agent):
    """Test if queue entries for the same object are properly simplified"""
    event1 = create_event(id_=1)
    event2 = create_event(id_=2)

    db.session.add(dummy_agent)
    db.session.add(event1)
    db.session.add(event2)

    refs = (
        {'type': EntryType.event, 'event_id': event1.id},
        {'type': EntryType.event, 'event_id': event2.id}
    )

    queue = []
Exemple #10
0
    db.session.flush()
    results = list(Room.get_with_data(only_active=only_active))
    assert len(results) == len(rooms) - only_active
    for row in results:
        room = row.pop('room')
        room_type = room_types[room]
        if room_type == 'inactive':
            assert not only_active


@pytest.mark.parametrize(
    ('has_booking', 'has_blocking',
     'has_pre_booking', 'include_pre_bookings',
     'has_pending_blocking', 'include_pending_blockings',
     'filtered'),
    set(bool_matrix('00.0.0', expect=False) +                                # nothing confirmed/pending
        bool_matrix('000.0.', expect=False) +                                # nothing pending included
        bool_matrix('1.....', expect=True) +                                 # confirmed booking
        bool_matrix('.1....', expect=True) +                                 # active blocking
        bool_matrix('00....', expect=lambda x: all(x[2:4]) or all(x[4:6])))  # included pending booking/blocking
)
def test_filter_available(dummy_room, create_reservation, create_blocking,
                          has_booking, has_blocking,
                          has_pre_booking, include_pre_bookings,
                          has_pending_blocking, include_pending_blockings, filtered):
    if has_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(8)),
                           end_dt=datetime.combine(date.today(), time(10)))
    if has_pre_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(10)),
                           end_dt=datetime.combine(date.today(), time(12)),
Exemple #11
0
    assert entry.full_access
    assert entry.read_access
    assert set(entry.roles) == {'foo', 'bar', 'foobar'}


def test_update_principal_errors(create_event, dummy_user):
    event = create_event()
    with pytest.raises(ValueError):
        event.update_principal(dummy_user, roles={'foo'}, add_roles={'bar'})
    with pytest.raises(ValueError):
        event.update_principal(dummy_user, roles={'foo'}, del_roles={'bar'})
    with pytest.raises(ValueError):
        event.update_principal(dummy_user, roles={'invalid'})


@pytest.mark.parametrize(('allow_key', 'has_key', 'authenticated', 'expected'), bool_matrix('...', expect=all))
def test_can_manage_key(create_event, dummy_user, allow_key, has_key, authenticated, expected):
    event = create_event()
    event.as_legacy.canKeyModify = lambda: has_key
    assert event.can_manage(dummy_user if authenticated else None, allow_key=allow_key) == expected


@pytest.mark.usefixtures('request_context')
def test_can_manage_roles(create_event, dummy_user):
    event = create_event()
    assert not event.can_manage(dummy_user, 'ANY')
    event.update_principal(dummy_user, roles={'foo'})
    assert not event.can_manage(dummy_user)
    assert not event.can_manage(dummy_user, 'bar')
    assert event.can_manage(dummy_user, 'foo')
    assert event.can_manage(dummy_user, 'ANY')
    assert ReservationOccurrence.find_first(
        ReservationOccurrence.is_in_notification_window(exclude_first_day=True)
    ) == (occurrence if expected_with_exclude else None)


# ======================================================================================================================
# Hybrid property tests
# ======================================================================================================================


def test_date(dummy_occurrence):
    assert dummy_occurrence.date == date.today()
    assert ReservationOccurrence.find_first(date=date.today()) == dummy_occurrence


@pytest.mark.parametrize(("is_rejected", "is_cancelled", "expected"), bool_matrix("..", expect=lambda x: not any(x)))
def test_is_valid(db, dummy_occurrence, is_rejected, is_cancelled, expected):
    dummy_occurrence.is_rejected = is_rejected
    dummy_occurrence.is_cancelled = is_cancelled
    db.session.flush()
    assert dummy_occurrence.is_valid == expected
    assert ReservationOccurrence.find_first(is_valid=expected) == dummy_occurrence


# ======================================================================================================================
# staticmethod tests
# ======================================================================================================================


def test_create_series_for_reservation(dummy_reservation):
    occurrences = ReservationOccurrence.iter_create_occurrences(
Exemple #13
0
    create_room(capacity=5)
    assert Room.max_capacity == 10


@pytest.mark.parametrize(
    (
        "has_booking",
        "has_blocking",
        "has_pre_booking",
        "include_pre_bookings",
        "has_pending_blocking",
        "include_pending_blockings",
        "filtered",
    ),
    set(
        bool_matrix("00.0.0", expect=False)
        + bool_matrix("000.0.", expect=False)  # nothing confirmed/pending
        + bool_matrix("1.....", expect=True)  # nothing pending included
        + bool_matrix(".1....", expect=True)  # confirmed booking
        + bool_matrix("00....", expect=lambda x: all(x[2:4]) or all(x[4:6]))  # active blocking
    ),  # included pending booking/blocking
)
def test_filter_available(
    dummy_room,
    create_reservation,
    create_blocking,
    has_booking,
    has_blocking,
    has_pre_booking,
    include_pre_bookings,
    has_pending_blocking,
Exemple #14
0

@pytest.mark.parametrize(('days_delta', 'expected'), (
    (-1, True),   # Reservation in the past
    (1,  False),  # Reservation in the future
    (0,  False),  # Reservation in course
))
def test_is_archived(create_reservation, days_delta, expected):
    start_dt = date.today() + relativedelta(days=days_delta, hour=0, minute=0)
    end_dt = date.today() + relativedelta(days=days_delta, hour=23, minute=59)
    reservation = create_reservation(start_dt=start_dt, end_dt=end_dt)
    assert reservation.is_archived == expected


@pytest.mark.parametrize(('is_accepted', 'is_rejected', 'is_cancelled', 'expected'),
                         bool_matrix('...', expect=lambda x: not any(x)))  # neither accepted/rejected/cancelled
def test_is_pending(create_reservation, is_accepted, is_rejected, is_cancelled, expected):
    reservation = create_reservation(is_accepted=is_accepted, is_rejected=is_rejected, is_cancelled=is_cancelled)
    assert reservation.is_pending == expected
    assert Reservation.find_first(is_pending=expected) == reservation


@pytest.mark.parametrize(('repeat_frequency', 'expected'), (
    (RepeatFrequency.NEVER, False),
    (RepeatFrequency.DAY,   True),
    (RepeatFrequency.WEEK,  True),
    (RepeatFrequency.MONTH, True),
))
def test_is_repeating(create_reservation, repeat_frequency, expected):
    reservation = create_reservation(repeat_frequency=repeat_frequency)
    assert reservation.is_repeating == expected
Exemple #15
0
    (RuntimeError, IndicoError, 'foo'),
    (Exception,    Exception,   'bar'),
    (ValueError,   ValueError,  'bar')
))
def test_unimplemented(raised, caught, message):
    @unimplemented(RuntimeError, message='foo')
    def _func():
        raise raised('bar')

    exc_info = pytest.raises(caught, _func)
    assert exc_info.value.message == message


@pytest.mark.parametrize(
    ('not_repeating', 'only_one_valid', 'propagate', 'proxied'),
    bool_matrix('..0', expect=False) +
    bool_matrix('..1', expect='any_dynamic')
)
@pytest.mark.usefixtures('smtp')
def test_proxy_to_reservation_if_last_valid_occurrence(db, mock, create_reservation, dummy_avatar,
                                                       not_repeating, only_one_valid, propagate, proxied):
    resv = create_reservation(start_dt=datetime.combine(date.today(), time(8)),
                              end_dt=datetime.combine(date.today() + timedelta(days=1), time(17)),
                              repeat_frequency=RepeatFrequency.NEVER if not_repeating else RepeatFrequency.DAY)
    if only_one_valid:
        for occ in resv.occurrences[1:]:
            occ.is_cancelled = True
        db.session.flush()

    occ = resv.occurrences.first()
    mock.patch.object(resv, 'cancel')
Exemple #16
0
def test_max_capacity(create_room):
    assert not Room.query.count()
    assert Room.max_capacity == 0
    create_room(capacity=0)
    assert Room.max_capacity == 0
    create_room(capacity=10)
    create_room(capacity=5)
    assert Room.max_capacity == 10


@pytest.mark.parametrize(
    ('has_booking', 'has_blocking',
     'has_pre_booking', 'include_pre_bookings',
     'has_pending_blocking', 'include_pending_blockings',
     'filtered'),
    set(bool_matrix('00.0.0', expect=False) +                                # nothing confirmed/pending
        bool_matrix('000.0.', expect=False) +                                # nothing pending included
        bool_matrix('1.....', expect=True) +                                 # confirmed booking
        bool_matrix('.1....', expect=True) +                                 # active blocking
        bool_matrix('00....', expect=lambda x: all(x[2:4]) or all(x[4:6])))  # included pending booking/blocking
)
def test_filter_available(dummy_room, create_reservation, create_blocking,
                          has_booking, has_blocking,
                          has_pre_booking, include_pre_bookings,
                          has_pending_blocking, include_pending_blockings, filtered):
    if has_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(8)),
                           end_dt=datetime.combine(date.today(), time(10)))
    if has_pre_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(10)),
                           end_dt=datetime.combine(date.today(), time(12)),

@pytest.mark.parametrize(('days_delta', 'expected'), (
    (-1, True),   # Reservation in the past
    (1,  False),  # Reservation in the future
    (0,  False),  # Reservation in course
))
def test_is_archived(create_reservation, days_delta, expected):
    start_dt = date.today() + relativedelta(days=days_delta, hour=0, minute=0)
    end_dt = date.today() + relativedelta(days=days_delta, hour=23, minute=59)
    reservation = create_reservation(start_dt=start_dt, end_dt=end_dt)
    assert reservation.is_archived == expected


@pytest.mark.parametrize(('is_accepted', 'is_rejected', 'is_cancelled', 'expected'),
                         bool_matrix('...', expect=lambda x: not any(x)))  # neither accepted/rejected/cancelled
def test_is_pending(create_reservation, is_accepted, is_rejected, is_cancelled, expected):
    reservation = create_reservation(is_accepted=is_accepted, is_rejected=is_rejected, is_cancelled=is_cancelled)
    assert reservation.is_pending == expected
    assert Reservation.find_first(is_pending=expected) == reservation


@pytest.mark.parametrize(('repeat_frequency', 'expected'), (
    (RepeatFrequency.NEVER, False),
    (RepeatFrequency.DAY,   True),
    (RepeatFrequency.WEEK,  True),
    (RepeatFrequency.MONTH, True),
))
def test_is_repeating(create_reservation, repeat_frequency, expected):
    reservation = create_reservation(repeat_frequency=repeat_frequency)
    assert reservation.is_repeating == expected
Exemple #18
0
def test_max_capacity(create_room):
    assert not Room.query.count()
    assert Room.max_capacity == 0
    create_room(capacity=0)
    assert Room.max_capacity == 0
    create_room(capacity=10)
    create_room(capacity=5)
    assert Room.max_capacity == 10


@pytest.mark.parametrize(
    ('has_booking', 'has_blocking',
     'has_pre_booking', 'include_pre_bookings',
     'has_pending_blocking', 'include_pending_blockings',
     'filtered'),
    set(bool_matrix('00.0.0', expect=False) +                                # nothing confirmed/pending
        bool_matrix('000.0.', expect=False) +                                # nothing pending included
        bool_matrix('1.....', expect=True) +                                 # confirmed booking
        bool_matrix('.1....', expect=True) +                                 # active blocking
        bool_matrix('00....', expect=lambda x: all(x[2:4]) or all(x[4:6])))  # included pending booking/blocking
)
def test_filter_available(dummy_room, create_reservation, create_blocking,
                          has_booking, has_blocking,
                          has_pre_booking, include_pre_bookings,
                          has_pending_blocking, include_pending_blockings, filtered):
    if has_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(8)),
                           end_dt=datetime.combine(date.today(), time(10)))
    if has_pre_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(10)),
                           end_dt=datetime.combine(date.today(), time(12)),
Exemple #19
0
def test_max_capacity(create_room):
    assert not Room.query.count()
    assert Room.max_capacity == 0
    create_room(capacity=0)
    assert Room.max_capacity == 0
    create_room(capacity=10)
    create_room(capacity=5)
    assert Room.max_capacity == 10


@pytest.mark.parametrize(
    ('has_booking', 'has_blocking', 'has_pre_booking', 'include_pre_bookings',
     'has_pending_blocking', 'include_pending_blockings', 'filtered'),
    set(
        bool_matrix('00.0.0', expect=False) +  # nothing confirmed/pending
        bool_matrix('000.0.', expect=False) +  # nothing pending included
        bool_matrix('1.....', expect=True) +  # confirmed booking
        bool_matrix('.1....', expect=True) +  # active blocking
        bool_matrix('00....', expect=lambda x: all(x[2:4]) or all(x[4:6]))
    )  # included pending booking/blocking
)
def test_filter_available(dummy_room, create_reservation, create_blocking,
                          has_booking, has_blocking, has_pre_booking,
                          include_pre_bookings, has_pending_blocking,
                          include_pending_blockings, filtered):
    if has_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(8)),
                           end_dt=datetime.combine(date.today(), time(10)))
    if has_pre_booking:
        create_reservation(start_dt=datetime.combine(date.today(), time(10)),
Exemple #20
0
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.

import pytest

from indico.modules.rb import rb_settings
from indico.modules.rb.util import rb_check_user_access, rb_is_admin
from indico.testing.util import bool_matrix


@pytest.mark.parametrize(('is_rb_admin', 'acl_empty', 'in_acl', 'expected'), bool_matrix('...', expect=any))
def test_rb_check_user_access(db, mocker, dummy_user, dummy_group, is_rb_admin, acl_empty, in_acl, expected):
    if is_rb_admin:
        mocker.patch('indico.modules.rb.util.rb_is_admin', return_value=True)
    if not acl_empty:
        rb_settings.acls.add_principal('authorized_principals', dummy_group)
    if in_acl:
        rb_settings.acls.add_principal('authorized_principals', dummy_user)
    assert rb_check_user_access(dummy_user) == expected


@pytest.mark.parametrize(('is_admin', 'is_rb_admin', 'expected'), bool_matrix('..', expect=any))
def test_rb_is_admin(create_user, is_admin, is_rb_admin, expected):
    user = create_user(1, admin=is_admin, rb_admin=is_rb_admin)
    assert rb_is_admin(user) == expected
        create_blocking(start_date=date(2014, 12, 6), end_date=date(2014, 12, 8))
    ]
    filters = {'start_date': start_date,
               'end_date': end_date}
    assert set(BlockedRoom.find_with_filters(filters)) == set(blockings[i].blocked_rooms[0] for i in matches)


@pytest.mark.parametrize('state', BlockedRoom.State)
def test_find_with_filters_state(create_blocking, state):
    other_state = next(s for s in BlockedRoom.State if s != state)
    create_blocking(state=other_state)
    blocking = create_blocking(state=state)
    assert set(BlockedRoom.find_with_filters({'state': state})) == {blocking.blocked_rooms[0]}


@pytest.mark.parametrize(('with_user', 'with_reason'), bool_matrix('..'))
def test_reject(dummy_user, dummy_blocking, smtp, with_user, with_reason):
    br = dummy_blocking.blocked_rooms[0]
    assert br.state == BlockedRoom.State.pending
    kwargs = {}
    if with_user:
        kwargs['user'] = dummy_user
    if with_reason:
        kwargs['reason'] = u'foo'
    br.reject(**kwargs)
    assert br.state == BlockedRoom.State.rejected
    mail = extract_emails(smtp, one=True, to=dummy_blocking.created_by_user.email, subject='Room blocking REJECTED')
    if with_reason:
        assert kwargs['reason'] in mail.as_string()
    assert not smtp.outbox
Exemple #22
0
    check_date = datetime.strptime(check_date, '%Y-%m-%d').date()
    blocking = create_blocking(start_date=start_date, end_date=end_date)
    assert blocking.is_active_at(check_date) == expected
    assert Blocking.find_first(
        Blocking.is_active_at(check_date)) == (blocking if expected else None)


def test_created_by_user(dummy_blocking, dummy_user, create_user):
    assert dummy_blocking.created_by_user == dummy_user
    other_user = create_user(123)
    dummy_blocking.created_by_user = other_user
    assert dummy_blocking.created_by_user == other_user


@pytest.mark.parametrize(('is_admin', 'is_creator', 'expected'),
                         bool_matrix('..', expect=any))
def test_can_edit_delete(dummy_blocking, create_user, is_admin, is_creator,
                         expected):
    user = create_user(123, rb_admin=is_admin)
    if is_creator:
        dummy_blocking.created_by_user = user
    assert dummy_blocking.can_edit(user) == expected
    assert dummy_blocking.can_delete(user) == expected


@pytest.mark.parametrize(
    ('is_creator', 'is_admin', 'has_room', 'is_room_owner', 'expected'),
    bool_matrix('!00..', expect=True) +  # creator or admin
    bool_matrix(' 00..', expect='all_dynamic')  # room owner
)
def test_can_override(dummy_room, dummy_blocking, create_user, is_creator,
Exemple #23
0
                                         if expected_with_exclude else None)


# ======================================================================================================================
# Hybrid property tests
# ======================================================================================================================


def test_date(dummy_occurrence):
    assert dummy_occurrence.date == date.today()
    assert ReservationOccurrence.find_first(
        date=date.today()) == dummy_occurrence


@pytest.mark.parametrize(('is_rejected', 'is_cancelled', 'expected'),
                         bool_matrix('..', expect=lambda x: not any(x)))
def test_is_valid(db, dummy_occurrence, is_rejected, is_cancelled, expected):
    dummy_occurrence.is_rejected = is_rejected
    dummy_occurrence.is_cancelled = is_cancelled
    db.session.flush()
    assert dummy_occurrence.is_valid == expected
    assert ReservationOccurrence.find_first(
        is_valid=expected) == dummy_occurrence


# ======================================================================================================================
# staticmethod tests
# ======================================================================================================================


def test_create_series_for_reservation(dummy_reservation):
Exemple #24
0
from __future__ import unicode_literals

from datetime import date, datetime, time, timedelta

import pytest
import pytz

from indico.modules.rb import rb_settings
from indico.modules.rb.util import get_booking_params_for_event, rb_check_user_access, rb_is_admin
from indico.testing.util import bool_matrix


pytest_plugins = ('indico.modules.rb.testing.fixtures', 'indico.modules.events.timetable.testing.fixtures')


@pytest.mark.parametrize(('is_rb_admin', 'acl_empty', 'in_acl', 'expected'), bool_matrix('...', expect=any))
def test_rb_check_user_access(db, mocker, dummy_user, dummy_group, is_rb_admin, acl_empty, in_acl, expected):
    if is_rb_admin:
        mocker.patch('indico.modules.rb.util.rb_is_admin', return_value=True)
    if not acl_empty:
        rb_settings.acls.add_principal('authorized_principals', dummy_group)
    if in_acl:
        rb_settings.acls.add_principal('authorized_principals', dummy_user)
    assert rb_check_user_access(dummy_user) == expected


@pytest.mark.parametrize(('is_admin', 'is_rb_admin', 'expected'), bool_matrix('..', expect=any))
def test_rb_is_admin(create_user, is_admin, is_rb_admin, expected):
    user = create_user(1, admin=is_admin, rb_admin=is_rb_admin)
    assert rb_is_admin(user) == expected
Exemple #25
0
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.

import pytest

from indico.modules.rb import rb_settings
from indico.modules.rb.util import rb_is_admin, rb_check_user_access
from indico.testing.util import bool_matrix


@pytest.mark.parametrize(('is_rb_admin', 'acl_empty', 'in_acl', 'expected'),
                         bool_matrix('...', expect=any))
def test_rb_check_user_access(db, mocker, dummy_user, dummy_group, is_rb_admin,
                              acl_empty, in_acl, expected):
    if is_rb_admin:
        mocker.patch('indico.modules.rb.util.rb_is_admin', return_value=True)
    if not acl_empty:
        rb_settings.acls.add_principal('authorized_principals', dummy_group)
    if in_acl:
        rb_settings.acls.add_principal('authorized_principals', dummy_user)
    assert rb_check_user_access(dummy_user) == expected


@pytest.mark.parametrize(('is_admin', 'is_rb_admin', 'expected'),
                         bool_matrix('..', expect=any))
def test_rb_is_admin(create_user, is_admin, is_rb_admin, expected):
    user = create_user(1, admin=is_admin, rb_admin=is_rb_admin)
Exemple #26
0
def test_is_active_at(create_blocking, check_date, expected):
    start_date = date(2014, 12, 5)
    end_date = date(2014, 12, 7)
    check_date = datetime.strptime(check_date, '%Y-%m-%d').date()
    blocking = create_blocking(start_date=start_date, end_date=end_date)
    assert blocking.is_active_at(check_date) == expected
    assert Blocking.find_first(Blocking.is_active_at(check_date)) == (blocking if expected else None)


def test_created_by_user(dummy_blocking, dummy_user, create_user):
    assert dummy_blocking.created_by_user == dummy_user
    dummy_blocking.created_by_user = user = create_user(123)
    assert dummy_blocking.created_by_user == user


@pytest.mark.parametrize(('is_admin', 'is_creator', 'expected'), bool_matrix('..', expect=any))
def test_can_be_modified_deleted(dummy_blocking, create_user, is_admin, is_creator, expected):
    user = create_user(123, rb_admin=is_admin)
    if is_creator:
        dummy_blocking.created_by_user = user
    assert dummy_blocking.can_be_modified(user) == expected
    assert dummy_blocking.can_be_deleted(user) == expected


@pytest.mark.parametrize(
    ('is_creator', 'is_admin', 'has_room', 'is_room_owner', 'expected'),
    bool_matrix('!00..', expect=True) +         # creator or admin
    bool_matrix(' 00..', expect='all_dynamic')  # room owner
)
def test_can_be_overridden(dummy_room, dummy_blocking, create_user,
                           is_creator, is_admin, has_room, is_room_owner, expected):
Exemple #27
0
# LICENSE file for more details.

from datetime import date, datetime, time, timedelta

import pytest

from indico.modules.rb.models.reservation_occurrences import ReservationOccurrenceState
from indico.modules.rb.models.reservations import RepeatFrequency
from indico.testing.util import bool_matrix

pytest_plugins = 'indico.modules.rb.testing.fixtures'


@pytest.mark.parametrize(
    ('not_repeating', 'only_one_valid', 'propagate', 'proxied'),
    bool_matrix('..0', expect=False) + bool_matrix('..1', expect='any_dynamic')
)
@pytest.mark.usefixtures('smtp')
def test_proxy_to_reservation_if_last_valid_occurrence(
        db, mocker, create_reservation, dummy_user, not_repeating,
        only_one_valid, propagate, proxied, freeze_time):
    resv = create_reservation(start_dt=datetime.combine(date.today(), time(8)),
                              end_dt=datetime.combine(
                                  date.today() + timedelta(days=1), time(17)),
                              repeat_frequency=RepeatFrequency.NEVER
                              if not_repeating else RepeatFrequency.DAY)
    freeze_time(datetime.combine(date.today(), time(8)))
    if only_one_valid:
        for occ in resv.occurrences[1:]:
            occ.state = ReservationOccurrenceState.cancelled
        db.session.flush()
    ('days_delta', 'expected'),
    (
        (-1, True),  # Reservation in the past
        (1, False),  # Reservation in the future
        (0, False),  # Reservation in course
    ))
def test_is_archived(create_reservation, days_delta, expected):
    start_dt = date.today() + relativedelta(days=days_delta, hour=0, minute=0)
    end_dt = date.today() + relativedelta(days=days_delta, hour=23, minute=59)
    reservation = create_reservation(start_dt=start_dt, end_dt=end_dt)
    assert reservation.is_archived == expected


@pytest.mark.parametrize(
    ('is_accepted', 'is_rejected', 'is_cancelled', 'expected'),
    bool_matrix('...', expect=lambda x: not any(x))
)  # neither accepted/rejected/cancelled
def test_is_pending(create_reservation, is_accepted, is_rejected, is_cancelled,
                    expected):
    reservation = create_reservation(is_accepted=is_accepted,
                                     is_rejected=is_rejected,
                                     is_cancelled=is_cancelled)
    assert reservation.is_pending == expected
    assert Reservation.find_first(is_pending=expected) == reservation


@pytest.mark.parametrize(('repeat_frequency', 'expected'), (
    (RepeatFrequency.NEVER, False),
    (RepeatFrequency.DAY, True),
    (RepeatFrequency.WEEK, True),
    (RepeatFrequency.MONTH, True),
Exemple #29
0
    ("days_delta", "expected"),
    (
        (-1, True),  # Reservation in the past
        (1, False),  # Reservation in the future
        (0, False),  # Reservation in course
    ),
)
def test_is_archived(create_reservation, days_delta, expected):
    start_dt = date.today() + relativedelta(days=days_delta, hour=0, minute=0)
    end_dt = date.today() + relativedelta(days=days_delta, hour=23, minute=59)
    reservation = create_reservation(start_dt=start_dt, end_dt=end_dt)
    assert reservation.is_archived == expected


@pytest.mark.parametrize(
    ("is_accepted", "is_rejected", "is_cancelled", "expected"), bool_matrix("...", expect=lambda x: not any(x))
)  # neither accepted/rejected/cancelled
def test_is_pending(create_reservation, is_accepted, is_rejected, is_cancelled, expected):
    reservation = create_reservation(is_accepted=is_accepted, is_rejected=is_rejected, is_cancelled=is_cancelled)
    assert reservation.is_pending == expected
    assert Reservation.find_first(is_pending=expected) == reservation


@pytest.mark.parametrize(
    ("repeat_frequency", "expected"),
    (
        (RepeatFrequency.NEVER, False),
        (RepeatFrequency.DAY, True),
        (RepeatFrequency.WEEK, True),
        (RepeatFrequency.MONTH, True),
    ),