File: test_calendar_stream.py

package info (click to toggle)
python-ical 12.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,776 kB
  • sloc: python: 15,157; sh: 9; makefile: 5
file content (190 lines) | stat: -rw-r--r-- 6,066 bytes parent folder | download
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
"""Tests for timeline related calendar events."""

from collections.abc import Generator
import itertools
import json
import textwrap
import pathlib

import pytest
from syrupy import SnapshotAssertion

from ical.exceptions import CalendarParseError
from ical.calendar_stream import CalendarStream, IcsCalendarStream
from ical.store import TodoStore

MAX_ITERATIONS = 30
TESTDATA_PATH = pathlib.Path("tests/testdata/")
TESTDATA_FILES = list(TESTDATA_PATH.glob("*.ics"))
TESTDATA_IDS = [x.stem for x in TESTDATA_FILES]


def test_empty_ics(mock_prodid: Generator[None, None, None]) -> None:
    """Test serialization of an empty ics file."""
    calendar = IcsCalendarStream.calendar_from_ics("")
    ics = IcsCalendarStream.calendar_to_ics(calendar)
    assert ics == textwrap.dedent(
        """\
            BEGIN:VCALENDAR
            PRODID:-//example//1.2.3
            VERSION:2.0
            END:VCALENDAR"""
    )

    calendar.prodid = "-//example//1.2.4"
    ics = IcsCalendarStream.calendar_to_ics(calendar)
    assert ics == textwrap.dedent(
        """\
            BEGIN:VCALENDAR
            PRODID:-//example//1.2.4
            VERSION:2.0
            END:VCALENDAR"""
    )


@pytest.mark.parametrize("filename", TESTDATA_FILES, ids=TESTDATA_IDS)
def test_parse(
    filename: pathlib.Path, snapshot: SnapshotAssertion, json_encoder: json.JSONEncoder
) -> None:
    """Fixture to read golden file and compare to golden output."""
    cal = CalendarStream.from_ics(filename.read_text())
    data = json.loads(cal.model_dump_json(exclude_unset=True, exclude_none=True))
    assert snapshot == data

    # Re-parse the data object to verify we get the original data values
    # back. This effectively confirms that all fields can be parsed from the
    # python native format in addition to rfc5545.
    cal_reparsed = CalendarStream.model_validate(data)
    data_reparsed = json.loads(
        cal_reparsed.model_dump_json(exclude_unset=True, exclude_none=True)
    )
    assert data_reparsed == data


@pytest.mark.parametrize("filename", TESTDATA_FILES, ids=TESTDATA_IDS)
def test_serialize(filename: pathlib.Path, snapshot: SnapshotAssertion) -> None:
    """Fixture to read golden file and compare to golden output."""
    with filename.open() as f:
        cal = IcsCalendarStream.from_ics(f.read())
    assert cal.ics() == snapshot


@pytest.mark.parametrize("filename", TESTDATA_FILES, ids=TESTDATA_IDS)
def test_timeline_iteration(filename: pathlib.Path) -> None:
    """Fixture to ensure all calendar events are valid and support iteration."""
    with filename.open() as f:
        cal = IcsCalendarStream.from_ics(f.read())
    for calendar in cal.calendars:
        # Iterate over the timeline to ensure events are valid. There is a max
        # to handle recurring events that may repeat forever.
        for event in itertools.islice(calendar.timeline, MAX_ITERATIONS):
            assert event is not None


@pytest.mark.parametrize("filename", TESTDATA_FILES, ids=TESTDATA_IDS)
def test_todo_list_iteration(filename: pathlib.Path) -> None:
    """Fixture to read golden file and compare to golden output."""
    cal = CalendarStream.from_ics(filename.read_text())
    if not cal.calendars:
        return
    calendar = cal.calendars[0]
    tl = TodoStore(calendar).todo_list()
    for todo in itertools.islice(tl, MAX_ITERATIONS):
        assert todo is not None


@pytest.mark.parametrize(
    "content",
    [
        textwrap.dedent(
            """\
            invalid
            """
        ),
        textwrap.dedent(
            """\
            BEGIN:VCALENDAR
            VERSION:\x007
            END:VCALENDAR
            """
        ),
        textwrap.dedent(
            """\
            BEGIN:VCALENDAR
            PROD\uc27fID://example
            END:VCALENDAR
            """
        ),
        textwrap.dedent(
            """\
            BEGIN:VCALENDAR
            ATTENDEE;MEM\x007ER="mailto:DEV-GROUP@example.com":mailto:joecool@example.com
            END:VCALENDAR
            """
        ),
        textwrap.dedent(
            """\
            BEGIN:VCALENDAR
            ATTENDEE;MEMBER="mailto:DEV-GROUP\x00example.com":mailto:joecool@example.com
            END:VCALENDAR
            """
        ),
    ],
    ids=[
        "invalid",
        "control-char-value",
        "control-char-name",
        "control-param-name",
        "control-param-value",
    ],
)
def test_invalid_ics(content: str) -> None:
    """Test parsing failures for ics content.

    These are tested here so we can add escape sequences. Most other invalid
    encodings are tested in the yaml testdata/ files.
    """
    with pytest.raises(
        CalendarParseError,
        match="^Calendar contents are not valid ICS format, see the detailed_error for more information$",
    ):
        IcsCalendarStream.calendar_from_ics(content)


def test_component_failure() -> None:
    with pytest.raises(
        CalendarParseError,
        match="^Failed to parse calendar EVENT component: Value error, Unexpected dtstart value '2022-07-24 12:00:00' was datetime but dtend value '2022-07-24' was not datetime$",
    ):
        IcsCalendarStream.calendar_from_ics(
            textwrap.dedent(
                """\
                BEGIN:VCALENDAR
                PRODID:-//example//1.2.3
                VERSION:2.0
                BEGIN:VEVENT
                DTSTART:20220724T120000
                DTEND:20220724
                END:VEVENT
                END:VCALENDAR
            """
            )
        )


def test_multiple_calendars() -> None:
    with pytest.raises(CalendarParseError, match="more than one calendar"):
        IcsCalendarStream.calendar_from_ics(
            textwrap.dedent(
                """\
                BEGIN:VCALENDAR
                PRODID:-//example//1.2.3
                VERSION:2.0
                END:VCALENDAR
                BEGIN:VCALENDAR
                PRODID:-//example//1.2.3
                VERSION:2.0
                END:VCALENDAR
            """
            )
        )