Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions news/1851.feature.6
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added a ``bymonth`` property accessor to :class:`~icalendar.prop.recur.recur.vRecur` for getting, setting, and deleting the ``BYMONTH`` part of a recurrence rule. @RishabhIIITD
89 changes: 89 additions & 0 deletions src/icalendar/prop/recur/recur.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

from collections.abc import Iterable
from typing import TYPE_CHECKING, Any, ClassVar
from xml.etree.ElementTree import Element, SubElement

Expand Down Expand Up @@ -478,6 +479,94 @@ def wkst(self) -> None:
"""Delete the WKST part of the recurrence rule."""
self.pop("WKST", None)

@property
def bymonth(self) -> tuple[vMonth, ...]:
"""The BYMONTH part of the recurrence rule.

This specifies a list of months of the year for the recurrence, per
:rfc:`5545#section-3.3.10` and :rfc:`7529`. Valid values are integers
from 1 to 12 (or leap months such as ``5L``).

Returns:
A tuple of :class:`~icalendar.prop.recur.month.vMonth` objects, or an
empty tuple if ``BYMONTH`` is not set.

Raises:
InvalidCalendar: if a stored value cannot be converted to a month
or is outside the valid range of 1 to 12.

Example:
.. code-block:: pycon

>>> from icalendar.prop import vRecur
>>> vRecur.from_ical("FREQ=YEARLY;BYMONTH=1,6,12").bymonth
(vMonth('1'), vMonth('6'), vMonth('12'))
>>> vRecur.from_ical("FREQ=YEARLY;BYMONTH=1").bymonth
(vMonth('1'),)
>>> vRecur.from_ical("FREQ=YEARLY").bymonth
()
"""
values = self.get("BYMONTH")
if values is None:
return ()
if not isinstance(values, SEQUENCE_TYPES):
values = [values]
result: list[vMonth] = []
for val in values:
if isinstance(val, bool):
raise InvalidCalendar(f"BYMONTH values must be months, got {val!r}")
try:
m = val if isinstance(val, vMonth) else vMonth(val)
except (TypeError, ValueError) as e:
raise InvalidCalendar(
f"BYMONTH values must be months, got {val!r}"
) from e
if not 1 <= int(m) <= 12:
raise InvalidCalendar(
f"BYMONTH values must be between 1 and 12, got {int(m)}"
)
result.append(m)
return tuple(result)

@bymonth.setter
def bymonth(
self, value: int | str | vMonth | Iterable[int | str | vMonth] | None
) -> None:
"""Set the BYMONTH part of the recurrence rule, or delete it if None or empty."""
if value is None:
del self.bymonth
return
if isinstance(value, (int, str, vMonth)) and not isinstance(value, bool):
months = [value]
elif isinstance(value, Iterable) and not isinstance(value, (str, bytes)):
months = list(value)
else:
raise TypeError(
f"bymonth must be an int, str, vMonth, or an iterable of them, got {value!r}"
)
if not months:
del self.bymonth
return
validated: list[vMonth] = []
for m in months:
if isinstance(m, bool) or not isinstance(m, (int, str, vMonth)):
raise TypeError(f"bymonth items must be int, str, or vMonth, got {m!r}")
try:
vm = m if isinstance(m, vMonth) else vMonth(m)
except (TypeError, ValueError) as e:
raise InvalidCalendar(f"Invalid BYMONTH value: {m!r}") from e
if not 1 <= int(vm) <= 12:
raise InvalidCalendar(
f"BYMONTH values must be between 1 and 12, got {int(vm)}"
)
validated.append(vm)
self["BYMONTH"] = validated

@bymonth.deleter
def bymonth(self) -> None:
"""Delete the BYMONTH part of the recurrence rule."""
self.pop("BYMONTH", None)

def __eq__(self, other: object) -> bool:
"""self == other"""
if not isinstance(other, vRecur):
Expand Down
139 changes: 139 additions & 0 deletions src/icalendar/tests/prop/recur/test_bymonth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
"""Tests for the vRecur.bymonth accessor (issue #1851)."""

import pytest

from icalendar.error import InvalidCalendar
from icalendar.prop import vMonth, vRecur


def test_bymonth_returns_empty_tuple_when_absent():
"""BYMONTH is not set at all."""
assert vRecur.from_ical("FREQ=YEARLY").bymonth == ()


def test_bymonth_returns_empty_tuple_when_empty_list():
"""If an empty list is in there, an empty tuple is returned."""
recur = vRecur(FREQ=["YEARLY"], BYMONTH=[])
assert recur.bymonth == ()


def test_bymonth_returns_single_value():
bymonth = vRecur.from_ical("FREQ=YEARLY;BYMONTH=6").bymonth
assert bymonth == (vMonth(6),)
assert bymonth[0] == 6
assert isinstance(bymonth[0], vMonth)


def test_bymonth_returns_multiple_values():
bymonth = vRecur.from_ical("FREQ=YEARLY;BYMONTH=1,6,12").bymonth
assert bymonth == (vMonth(1), vMonth(6), vMonth(12))
assert all(isinstance(m, vMonth) for m in bymonth)


def test_bymonth_boundary_values_are_valid():
assert vRecur.from_ical("FREQ=YEARLY;BYMONTH=1").bymonth == (vMonth(1),)
assert vRecur.from_ical("FREQ=YEARLY;BYMONTH=12").bymonth == (vMonth(12),)


def test_bymonth_leap_month_is_valid():
"""RFC 7529 allows leap months like 5L."""
bymonth = vRecur.from_ical("FREQ=YEARLY;BYMONTH=5L").bymonth
assert len(bymonth) == 1
assert bymonth[0] == 5
assert bymonth[0].leap is True


def test_setting_bymonth_with_single_int():
recur = vRecur.from_ical("FREQ=YEARLY")
recur.bymonth = 6
assert recur.bymonth == (vMonth(6),)
assert isinstance(recur["BYMONTH"][0], vMonth)
assert recur.to_ical() == b"FREQ=YEARLY;BYMONTH=6"


def test_setting_bymonth_with_vmonth():
recur = vRecur.from_ical("FREQ=YEARLY")
recur.bymonth = vMonth("5L")
assert recur.bymonth == (vMonth("5L"),)
assert recur.bymonth[0].leap is True
assert recur.to_ical() == b"FREQ=YEARLY;BYMONTH=5L"


def test_setting_bymonth_with_list():
recur = vRecur.from_ical("FREQ=YEARLY")
recur.bymonth = [1, 12]
assert recur.bymonth == (vMonth(1), vMonth(12))
assert recur.to_ical() == b"FREQ=YEARLY;BYMONTH=1,12"


def test_setting_bymonth_to_none_deletes_value():
recur = vRecur.from_ical("FREQ=YEARLY;BYMONTH=6")
recur.bymonth = None
assert recur.bymonth == ()
assert "BYMONTH" not in recur


def test_setting_bymonth_to_empty_sequence_deletes_value():
recur = vRecur.from_ical("FREQ=YEARLY;BYMONTH=6")
recur.bymonth = []
assert recur.bymonth == ()
assert "BYMONTH" not in recur

recur.bymonth = [6]
recur.bymonth = ()
assert recur.bymonth == ()
assert "BYMONTH" not in recur


def test_deleting_bymonth_removes_value():
recur = vRecur.from_ical("FREQ=YEARLY;BYMONTH=6")
del recur.bymonth
assert recur.bymonth == ()
assert "BYMONTH" not in recur


def test_deleting_bymonth_when_absent_does_not_raise():
recur = vRecur.from_ical("FREQ=YEARLY")
del recur.bymonth
assert recur.bymonth == ()


def test_setting_bymonth_to_non_int_type_raises_type_error():
recur = vRecur.from_ical("FREQ=YEARLY")
with pytest.raises(TypeError):
recur.bymonth = [1, object()]


def test_setting_bymonth_to_bool_raises_type_error():
recur = vRecur.from_ical("FREQ=YEARLY")
with pytest.raises(TypeError):
recur.bymonth = True
with pytest.raises(TypeError):
recur.bymonth = [1, True]


@pytest.mark.parametrize("invalid_month", [-1, 0, 13, 100])
def test_setting_bymonth_out_of_range_raises_invalid_calendar(invalid_month):
recur = vRecur.from_ical("FREQ=YEARLY")
with pytest.raises(
InvalidCalendar, match="BYMONTH values must be between 1 and 12"
):
recur.bymonth = invalid_month
with pytest.raises(
InvalidCalendar, match="BYMONTH values must be between 1 and 12"
):
recur.bymonth = [1, invalid_month]


@pytest.mark.parametrize("stored", [-1, 0, 13, "abc", True])
def test_directly_assigned_invalid_bymonth_raises_invalid_calendar(stored):
recur = vRecur.from_ical("FREQ=YEARLY")
recur["BYMONTH"] = [stored]
with pytest.raises(InvalidCalendar):
_ = recur.bymonth


def test_bymonth_roundtrips_through_ical():
recur = vRecur.from_ical("FREQ=YEARLY;BYMONTH=1,6,12")
roundtripped = vRecur.from_ical(recur.to_ical().decode())
assert roundtripped.bymonth == (vMonth(1), vMonth(6), vMonth(12))