diff --git a/news/1851.feature.1 b/news/1851.feature.1 new file mode 100644 index 000000000..859da74de --- /dev/null +++ b/news/1851.feature.1 @@ -0,0 +1 @@ +Added an :attr:`~icalendar.prop.recur.recur.vRecur.interval` accessor for reading, setting, and deleting the positive INTERVAL value of a recurrence rule. I used OpenAI GPT-6 to assist with implementation and tests. @aspire488 diff --git a/src/icalendar/prop/integer.py b/src/icalendar/prop/integer.py index 634e04e17..9f52fcb5b 100644 --- a/src/icalendar/prop/integer.py +++ b/src/icalendar/prop/integer.py @@ -243,4 +243,29 @@ def examples(cls) -> list[vInt]: XCAL_TYPE = "xsd:nonNegativeInteger" -__all__ = ["vInt", "vNonNegativeInt"] +class vPositiveInt(vInt): + """This is an integer that is at least ``1``.""" + + min: ClassVar[int] = 1 + + @classmethod + def examples(cls) -> list[vInt]: + """Examples of vPositiveInt.""" + return [cls(1000), cls(1)] + + XCAL_TYPE = "xsd:positiveInteger" + + @classmethod + def from_xcal_element(cls, element: ElementAdapter, params: Parameters) -> Self: + """Parse a positive integer from xCal.""" + value = super().from_xcal_element(element, params) + if value < cls.min: + raise XCalParsingError( + f"Expected {cls.XCAL_TYPE}", + element.get_xsd_token(), + element, + ) + return value + + +__all__ = ["vInt", "vNonNegativeInt", "vPositiveInt"] diff --git a/src/icalendar/prop/recur/recur.py b/src/icalendar/prop/recur/recur.py index 8e6920334..785d4f879 100644 --- a/src/icalendar/prop/recur/recur.py +++ b/src/icalendar/prop/recur/recur.py @@ -12,7 +12,7 @@ from icalendar.parser.xcal.wrapper import from_xcal_wrapper from icalendar.parser_tools import DEFAULT_ENCODING, SEQUENCE_TYPES from icalendar.prop.dt import vDDDTypes -from icalendar.prop.integer import vInt, vNonNegativeInt +from icalendar.prop.integer import vInt, vNonNegativeInt, vPositiveInt from icalendar.prop.recur.frequency import vFrequency from icalendar.prop.recur.month import vMonth from icalendar.prop.recur.skip import vSkip @@ -170,7 +170,7 @@ class vRecur(CaselessDict): ] = CaselessDict( { "COUNT": vNonNegativeInt, - "INTERVAL": vNonNegativeInt, + "INTERVAL": vPositiveInt, "BYSECOND": vNonNegativeInt, "BYMINUTE": vNonNegativeInt, "BYHOUR": vNonNegativeInt, @@ -414,6 +414,75 @@ def count(self) -> None: """Delete the COUNT part of the recurrence rule.""" self.pop("COUNT", None) + @property + def interval(self) -> int | None: + """The INTERVAL part of the recurrence rule. + + This is the positive integer interval between occurrences of the + recurrence frequency. When omitted, although :rfc:`5545#section-3.3.10` + defines the default as ``1``, this accessor returns ``None`` instead. + As such, callers can distinguish an omitted value from an explicit one. + + If multiple values are present, only the first one is returned. If the + value is missing or an empty sequence, ``None`` is returned. Assigning + ``None`` or deleting the property removes the entire INTERVAL entry, + including all values in a multi-value entry. + + Raises: + ValueError: when parsing an RRULE whose INTERVAL is not a positive + integer. + InvalidCalendar: after using :ref:`dictionary-access`, if a stored + value cannot be read through :ref:`property-access` as an + :class:`int` or is less than ``1``, or when setting a value + less than ``1``. + TypeError: when setting a value that is not an :class:`int`. + + Example: + .. code-block:: pycon + + >>> from icalendar.prop import vRecur + >>> vRecur.from_ical("FREQ=DAILY;INTERVAL=2").interval + 2 + >>> vRecur(FREQ=["DAILY"], INTERVAL=[2, 3]).interval + 2 + >>> vRecur.from_ical("FREQ=DAILY").interval is None + True + """ + values = self.get("INTERVAL") + if values is None or (isinstance(values, SEQUENCE_TYPES) and len(values) == 0): + return None + value = values[0] if isinstance(values, SEQUENCE_TYPES) else values + if isinstance(value, bool): + raise InvalidCalendar( + f"INTERVAL must be an int, got {type(value).__name__}" + ) + try: + interval = int(value) + except (TypeError, ValueError) as e: + raise InvalidCalendar( + f"INTERVAL must be an int, got {type(value).__name__}" + ) from e + if interval < 1: + raise InvalidCalendar(f"INTERVAL must be >= 1, got {interval}.") + return interval + + @interval.setter + def interval(self, value: int | None) -> None: + """Set the INTERVAL part of the recurrence rule, or delete it if ``None``.""" + if value is None: + del self.interval + return + if not isinstance(value, int) or isinstance(value, bool): + raise TypeError(f"interval must be an int, got {value!r}") + if value < 1: + raise InvalidCalendar(f"INTERVAL must be >= 1, got {value}") + self["INTERVAL"] = [vPositiveInt(value)] + + @interval.deleter + def interval(self) -> None: + """Delete the INTERVAL part of the recurrence rule.""" + self.pop("INTERVAL", None) + @property def wkst(self) -> vWeekday | None: """The WKST part of the recurrence rule. diff --git a/src/icalendar/tests/prop/recur/test_interval.py b/src/icalendar/tests/prop/recur/test_interval.py new file mode 100644 index 000000000..4e08915aa --- /dev/null +++ b/src/icalendar/tests/prop/recur/test_interval.py @@ -0,0 +1,134 @@ +"""Tests for the vRecur.interval accessor (issue #1851).""" + +import pytest + +from icalendar.error import InvalidCalendar +from icalendar.prop import vRecur +from icalendar.prop.integer import vPositiveInt + + +def test_interval_returns_none_when_absent(): + assert vRecur.from_ical("FREQ=DAILY").interval is None + + +def test_interval_returns_the_value(): + assert vRecur.from_ical("FREQ=DAILY;INTERVAL=2").interval == 2 + + +def test_interval_returns_first_value_when_multiple_are_present(): + recur = vRecur(FREQ=["DAILY"], INTERVAL=[2, 3]) + assert recur.interval == 2 + + +def test_interval_returns_none_when_value_is_an_empty_list(): + recur = vRecur(FREQ=["DAILY"], INTERVAL=[]) + assert recur.interval is None + + +def test_setting_interval_stores_a_registered_positive_int(): + recur = vRecur.from_ical("FREQ=DAILY") + recur.interval = 3 + + assert recur.interval == 3 + assert isinstance(recur["INTERVAL"][0], vPositiveInt) + assert recur.to_ical() == b"FREQ=DAILY;INTERVAL=3" + + +def test_setting_interval_to_none_deletes_the_value(): + recur = vRecur.from_ical("FREQ=DAILY;INTERVAL=2") + recur.interval = None + + assert recur.interval is None + assert "INTERVAL" not in recur + + +def test_setting_interval_to_none_removes_all_multiple_values(): + recur = vRecur(FREQ=["DAILY"], INTERVAL=[2, 3]) + recur.interval = None + + assert recur.interval is None + assert "INTERVAL" not in recur + + +def test_deleting_interval_removes_the_value(): + recur = vRecur.from_ical("FREQ=DAILY;INTERVAL=2") + del recur.interval + + assert recur.interval is None + assert "INTERVAL" not in recur + + +def test_deleting_interval_removes_all_multiple_values(): + recur = vRecur(FREQ=["DAILY"], INTERVAL=[2, 3]) + del recur.interval + + assert recur.interval is None + assert "INTERVAL" not in recur + + +def test_deleting_interval_when_absent_does_not_raise(): + recur = vRecur.from_ical("FREQ=DAILY") + del recur.interval + assert recur.interval is None + + +@pytest.mark.parametrize("value", ["2", 2.0, True]) +def test_setting_interval_to_non_int_raises_type_error(value): + recur = vRecur.from_ical("FREQ=DAILY") + with pytest.raises(TypeError): + recur.interval = value + + +@pytest.mark.parametrize("value", [0, -1]) +def test_setting_interval_to_non_positive_value_raises_invalid_calendar(value): + recur = vRecur.from_ical("FREQ=DAILY") + with pytest.raises(InvalidCalendar, match="INTERVAL must be >= 1"): + recur.interval = value + + +@pytest.mark.parametrize("value", ["0", "-1", "True", "abc"]) +def test_parsing_invalid_interval_raises_value_error(value): + with pytest.raises(ValueError): + vRecur.from_ical(f"FREQ=DAILY;INTERVAL={value}") + + +@pytest.mark.parametrize("stored", [0, -1]) +def test_dictionary_access_non_positive_interval_raises_invalid_calendar(stored): + recur = vRecur.from_ical("FREQ=DAILY") + recur["INTERVAL"] = [stored] + with pytest.raises(InvalidCalendar, match="INTERVAL must be >= 1"): + recur.interval + + +@pytest.mark.parametrize( + ("stored", "value_type"), + [("abc", "str"), ("", "str"), (["abc"], "str"), (True, "bool")], +) +def test_dictionary_access_unreadable_interval_raises_invalid_calendar( + stored, value_type +): + recur = vRecur.from_ical("FREQ=DAILY") + recur["INTERVAL"] = stored + with pytest.raises( + InvalidCalendar, + match=f"INTERVAL must be an int, got {value_type}", + ): + recur.interval + + +def test_interval_roundtrips_through_ical(): + recur = vRecur.from_ical("FREQ=DAILY;INTERVAL=3") + roundtripped = vRecur.from_ical(recur.to_ical().decode()) + + assert roundtripped.interval == 3 + assert isinstance(roundtripped["INTERVAL"][0], vPositiveInt) + + +def test_setting_interval_matches_parsed_vrecur(): + parsed = vRecur.from_ical("FREQ=DAILY;INTERVAL=3") + assigned = vRecur.from_ical("FREQ=DAILY") + assigned.interval = 3 + + assert assigned == parsed + assert assigned["INTERVAL"] == parsed["INTERVAL"] + assert assigned.to_ical() == parsed.to_ical() diff --git a/src/icalendar/tests/rfc_6321_xcal/prop/test_recur.py b/src/icalendar/tests/rfc_6321_xcal/prop/test_recur.py index 94bc52198..7d99c5486 100644 --- a/src/icalendar/tests/rfc_6321_xcal/prop/test_recur.py +++ b/src/icalendar/tests/rfc_6321_xcal/prop/test_recur.py @@ -257,7 +257,7 @@ def test_leap_month_from_xcal(leap): ( key, "asd", - f"Expected xsd:nonNegativeInteger, got 'asd' in /recur/{key.lower()}[1].", + f"Expected xsd:{'positiveInteger' if key == 'INTERVAL' else 'nonNegativeInteger'}, got 'asd' in /recur/{key.lower()}[1].", ) ) @@ -282,7 +282,7 @@ def test_invalid_values_raise_xcal_error(key, xml, message): assert e.value.message == message -@pytest.mark.parametrize("key", POSITIVE_INTS) +@pytest.mark.parametrize("key", [key for key in POSITIVE_INTS if key != "INTERVAL"]) def test_negative_integer_still_parses(key): """We still want to preserve invalid values because - we might just want to convert a calendar @@ -294,6 +294,16 @@ def test_negative_integer_still_parses(key): assert result[key][0].min == 0 +def test_negative_interval_raises_xcal_error(): + """INTERVAL is an xsd:positiveInteger and cannot be negative.""" + xml = list2xml(["recur", ["interval", "-1"]]) + with pytest.raises(XCalParsingError) as exc_info: + vRecur.from_xcal(xml) + assert exc_info.value.message == ( + "Expected xsd:positiveInteger, got '-1' in /recur/interval[1]." + ) + + def test_weekday_becomes_uppercase(): """Uppercase is required for xCal.""" xml = list2xml(["recur", ["byday", "su"]]) diff --git a/src/icalendar/tests/rfc_7265_jcal/test_invalid_jcal.py b/src/icalendar/tests/rfc_7265_jcal/test_invalid_jcal.py index 78031ab0c..69d67e200 100644 --- a/src/icalendar/tests/rfc_7265_jcal/test_invalid_jcal.py +++ b/src/icalendar/tests/rfc_7265_jcal/test_invalid_jcal.py @@ -434,7 +434,7 @@ def test_int_parameters(int_expected, key, as_list): # parse bad value with pytest.raises( JCalParsingError, - match=f'\\[3\\]\\["{key}"\\](?:\\[0\\])? in v(NonNegative)?Int: The value must be an integer.', + match=f'\\[3\\]\\["{key}"\\](?:\\[0\\])? in v(?:NonNegative|Positive)?Int: The value must be an integer.', ): vRecur.from_jcal(["rrule", {}, "recur", {key: int_expected}])