File: test_todo.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 (435 lines) | stat: -rw-r--r-- 13,641 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
"""Tests for Todo component."""

from __future__ import annotations

import datetime
import zoneinfo
import textwrap
from typing import Any
from unittest.mock import patch

from freezegun import freeze_time
import pytest

from ical.exceptions import CalendarParseError
from ical.todo import Todo
from ical.types.recur import Recur
from ical.calendar_stream import IcsCalendarStream

_TEST_TZ = datetime.timezone(datetime.timedelta(hours=1))


def test_empty() -> None:
    """Test that in practice a Todo requires no fields."""
    todo = Todo()
    assert not todo.summary


def test_todo() -> None:
    """Test a valid Todo object."""
    todo = Todo(summary="Example", due=datetime.date(2022, 8, 7))
    assert todo.summary == "Example"
    assert todo.due == datetime.date(2022, 8, 7)


def test_duration() -> None:
    """Test relationship between the due and duration fields."""

    todo = Todo(start=datetime.date(2022, 8, 7), duration=datetime.timedelta(days=1))
    assert todo.start
    assert todo.duration

    # Both due and Duration can't be set
    with pytest.raises(
        CalendarParseError,
        match="Failed to parse calendar TODO component: Value error, Only one of due or duration may be set.",
    ):
        Todo(
            start=datetime.date(2022, 8, 7),
            duration=datetime.timedelta(days=1),
            due=datetime.date(2022, 8, 8),
        )

    # Duration requires start date
    with pytest.raises(
        CalendarParseError,
        match="^Failed to parse calendar TODO component: Value error, Duration requires that dtstart is specified$",
    ):
        Todo(duration=datetime.timedelta(days=1))

    todo = Todo(start=datetime.date(2022, 8, 7), due=datetime.date(2022, 8, 8))
    assert todo.start
    assert todo.due
    assert todo.start_datetime

    with patch(
        "ical.util.local_timezone", return_value=zoneinfo.ZoneInfo("America/Regina")
    ):
        assert todo.start_datetime.isoformat() == "2022-08-07T06:00:00+00:00"


def test_dtstart_date_duration_hours_invalid():
    """Test that a Todo with datetime as dtstart and duration with seconds or microseconds
    (in practice anything smaller than days) fails to validate"""

    with pytest.raises(CalendarParseError):
        Todo(dtstart=datetime.date(2022, 8, 7), duration=datetime.timedelta(hours=1))


def test_computed_duration_no_start_duration():
    """Test that a Todo without start and due or duration takes a whole day"""
    todo = Todo()

    assert todo.computed_duration == datetime.timedelta(days=1)


@pytest.mark.parametrize(
    ("params"),
    [
        ({}),
        (
            {
                "start": datetime.datetime(2022, 9, 6, 6, 0, 0),
            }
        ),
        (
            {
                "due": datetime.datetime(2022, 9, 6, 6, 0, 0),
            }
        ),
        (
            {
                "duration": datetime.timedelta(hours=1),
            }
        ),
        (
            {
                "start": datetime.datetime(2022, 9, 6, 6, 0, 0),
                "due": datetime.datetime(
                    2022, 9, 7, 6, 0, 0, tzinfo=zoneinfo.ZoneInfo("America/Regina")
                ),
            }
        ),
        (
            {
                "start": datetime.datetime(
                    2022, 9, 6, 6, 0, 0, tzinfo=zoneinfo.ZoneInfo("America/Regina")
                ),
                "due": datetime.datetime(2022, 9, 7, 6, 0, 0),  # floating
            }
        ),
        (
            {
                "duration": datetime.timedelta(hours=1),
            }
        ),
    ],
)
def test_validate_rrule_required_fields(params: dict[str, Any]) -> None:
    """Test that a Todo with an rrule requires a dtstart."""
    with pytest.raises(CalendarParseError):
        todo = Todo(
            summary="Todo 1",
            rrule=Recur.from_rrule("FREQ=WEEKLY;BYDAY=WE,MO,TU,TH,FR;COUNT=3"),
            **params,
        )
        todo.as_rrule()


def test_is_recurring() -> None:
    """Test that a Todo with an rrule requires a dtstart."""
    todo = Todo(
        summary="Todo 1",
        rrule=Recur.from_rrule("FREQ=DAILY;COUNT=3"),
        dtstart="2024-02-02",
        due="2024-02-03",
    )
    assert todo.recurring
    assert todo.computed_duration == datetime.timedelta(days=1)
    assert list(todo.as_rrule()) == [
        datetime.date(2024, 2, 2),
        datetime.date(2024, 2, 3),
        datetime.date(2024, 2, 4),
    ]


def test_timestamp_start_due() -> None:
    """Test a timespan of a Todo with a start and due date."""
    todo = Todo(
        summary="Example",
        dtstart=datetime.date(2022, 8, 1),
        due=datetime.date(2022, 8, 7),
    )

    with patch("ical.todo.local_timezone", return_value=zoneinfo.ZoneInfo("CET")):
        ts = todo.timespan
    assert ts.start.isoformat() == "2022-08-01T00:00:00+02:00"
    assert ts.end.isoformat() == "2022-08-07T00:00:00+02:00"

    ts = todo.timespan_of(zoneinfo.ZoneInfo("America/Regina"))
    assert ts.start.isoformat() == "2022-08-01T00:00:00-06:00"
    assert ts.end.isoformat() == "2022-08-07T00:00:00-06:00"


def test_timespan_start_duration() -> None:
    """Test that duration is taken into account in timespan calculation"""

    duration = datetime.timedelta(hours=1)
    todo = Todo(
        dtstart=datetime.datetime(2025, 10, 27, 0, 0, 0, tzinfo=_TEST_TZ),
        duration=duration,
    )
    timespan = todo.timespan
    assert timespan.start.isoformat() == "2025-10-27T00:00:00+01:00"
    assert timespan.end.isoformat() == "2025-10-27T01:00:00+01:00"
    assert timespan.duration == duration


def test_timespan_start_date_duration() -> None:
    """Test that timestamp for todo with date-typed start and set due spans the whole day"""

    duration = datetime.timedelta(days=1)
    todo = Todo(
        dtstart=datetime.date(2025, 10, 27),
        duration=duration,
    )

    timespan = todo.timespan_of(_TEST_TZ)
    assert timespan.start.isoformat() == "2025-10-27T00:00:00+01:00"
    assert timespan.end.isoformat() == "2025-10-28T00:00:00+01:00"
    assert timespan.duration == duration


def test_timespan_missing_dtstart() -> None:
    """Test a timespan of a Todo without a dtstart."""
    todo = Todo(summary="Example", due=datetime.date(2022, 8, 7))

    with patch(
        "ical.todo.local_timezone", return_value=zoneinfo.ZoneInfo("Pacific/Honolulu")
    ):
        ts = todo.timespan
    assert ts.start.isoformat() == "2022-08-07T00:00:00-10:00"
    assert ts.end.isoformat() == "2022-08-07T00:00:00-10:00"

    ts = todo.timespan_of(zoneinfo.ZoneInfo("America/Regina"))
    assert ts.start.isoformat() == "2022-08-07T00:00:00-06:00"
    assert ts.end.isoformat() == "2022-08-07T00:00:00-06:00"


def test_timespan_fallback() -> None:
    """Test a timespan of a Todo with no explicit dtstart and due date"""

    with (
        freeze_time("2022-09-03T09:38:05", tz_offset=10),
        patch(
            "ical.todo.local_timezone",
            return_value=zoneinfo.ZoneInfo("Pacific/Honolulu"),
        ),
    ):
        todo = Todo(summary="Example")
        ts = todo.timespan
    assert ts.start.isoformat() == "2022-09-03T00:00:00-10:00"
    assert ts.end.isoformat() == "2022-09-04T00:00:00-10:00"

    with (
        freeze_time("2022-09-03T09:38:05", tz_offset=10),
        patch(
            "ical.todo.local_timezone",
            return_value=zoneinfo.ZoneInfo("Pacific/Honolulu"),
        ),
    ):
        ts = todo.timespan_of(zoneinfo.ZoneInfo("America/Regina"))
    assert ts.start.isoformat() == "2022-09-03T00:00:00-06:00"
    assert ts.end.isoformat() == "2022-09-04T00:00:00-06:00"


@pytest.mark.parametrize(
    ("due", "expected"),
    [
        (datetime.date(2022, 9, 6), True),
        (datetime.date(2022, 9, 7), True),
        (datetime.date(2022, 9, 8), False),
        (datetime.date(2022, 9, 9), False),
        (datetime.datetime(2022, 9, 7, 6, 0, 0, tzinfo=_TEST_TZ), True),
        (datetime.datetime(2022, 9, 7, 12, 0, 0, tzinfo=_TEST_TZ), False),
        (datetime.datetime(2022, 9, 8, 6, 0, 0, tzinfo=_TEST_TZ), False),
    ],
)
@freeze_time("2022-09-07T09:38:05", tz_offset=1)
def test_is_due(due: datetime.date | datetime.datetime, expected: bool) -> None:
    """Test that a Todo is due."""
    todo = Todo(
        summary="Example",
        due=due,
    )
    assert todo.is_due(tzinfo=_TEST_TZ) == expected


def test_is_due_default_timezone() -> None:
    """Test a Todo is due with the default timezone."""
    todo = Todo(
        summary="Example",
        due=datetime.date(2022, 9, 6),
    )
    assert todo.is_due()


def test_repair_mismatched_due_date_and_dtstart() -> None:
    """The calendar store has a bug when the due date changes type without updating the start date."""
    calendar = IcsCalendarStream.calendar_from_ics(
        textwrap.dedent(
            """\
                BEGIN:VCALENDAR
                PRODID:-//example.io//todo 2.0//EN
                VERSION:2.0
                BEGIN:VTODO
                DTSTAMP:20240310T151256
                UID:85cce364-def0-11ee-a2a9-6045bde93490
                CREATED:20240310T151156
                DESCRIPTION:Modify
                DTSTART:20240310T151151Z
                DUE:20240318
                LAST-MODIFIED:20240310T151256
                SEQUENCE:2
                STATUS:NEEDS-ACTION
                SUMMARY:Example
                END:VTODO
                END:VCALENDAR
            """
        )
    )
    assert len(calendar.todos) == 1
    assert calendar.todos[0].due == datetime.date(2024, 3, 18)
    assert calendar.todos[0].dtstart == datetime.date(2024, 3, 10)


def test_repair_mismatched_due_datetime_and_dtstart() -> None:
    """The calendar store has a bug when the due date changes type without updating the start date."""
    calendar = IcsCalendarStream.calendar_from_ics(
        textwrap.dedent(
            """\
                BEGIN:VCALENDAR
                PRODID:-//example.io//todo 2.0//EN
                VERSION:2.0
                BEGIN:VTODO
                DTSTAMP:20240310T151256
                UID:85cce364-def0-11ee-a2a9-6045bde93490
                CREATED:20240310T151156
                DESCRIPTION:Modify
                DTSTART:20240310
                DUE:20240318T151151Z
                LAST-MODIFIED:20240310T151256
                SEQUENCE:2
                STATUS:NEEDS-ACTION
                SUMMARY:Example
                END:VTODO
                END:VCALENDAR
            """
        )
    )
    assert len(calendar.todos) == 1
    assert calendar.todos[0].due == datetime.datetime(
        2024, 3, 18, 15, 11, 51, tzinfo=datetime.timezone.utc
    )
    assert calendar.todos[0].dtstart == datetime.datetime(
        2024, 3, 10, 0, 0, 0, tzinfo=datetime.timezone.utc
    )


def test_repair_out_of_order_due_and_dtstart() -> None:
    """The calendar store has a bug when the due date changes type without updating the start date."""
    calendar = IcsCalendarStream.calendar_from_ics(
        textwrap.dedent(
            """\
                BEGIN:VCALENDAR
                PRODID:-//example.io//todo 2.0//EN
                VERSION:2.0
                BEGIN:VTODO
                DTSTAMP:20240310T151256
                UID:85cce364-def0-11ee-a2a9-6045bde93490
                CREATED:20240310T151156
                DESCRIPTION:Modify
                DTSTART:20240410
                DUE:20240318
                LAST-MODIFIED:20240310T151256
                SEQUENCE:2
                STATUS:NEEDS-ACTION
                SUMMARY:Example
                END:VTODO
                END:VCALENDAR
            """
        )
    )
    assert len(calendar.todos) == 1
    assert calendar.todos[0].due == datetime.date(2024, 3, 18)
    assert calendar.todos[0].dtstart == datetime.date(2024, 3, 17)


@pytest.mark.parametrize(
    "dtstart, duration",
    (
        (
            datetime.datetime(2025, 10, 27, 0, 0, 0, tzinfo=_TEST_TZ),
            datetime.timedelta(hours=1),
        ),
        (
            datetime.datetime(2025, 10, 27, 0, 0, 0, tzinfo=_TEST_TZ),
            datetime.timedelta(days=1),
        ),
        (datetime.date(2025, 10, 27), datetime.timedelta(days=1)),
    ),
)
def test_computed_duration(
    dtstart: datetime.datetime | datetime.date, duration: datetime.timedelta
) -> None:
    """Test that computed_duration is the same as duration when set"""

    todo = Todo(
        dtstart=dtstart,
        duration=duration,
    )

    assert todo.computed_duration == duration


@pytest.mark.parametrize(
    "start, end",
    (
        (datetime.date(2025, 10, 27), None),
        (None, datetime.date(2025, 10, 27)),
        (None, None),
    ),
)
def test_default_computed_duration(
    start: datetime.datetime | datetime.date | None,
    end: datetime.datetime | datetime.date | None,
) -> None:
    """Test that computed_duration is no duration or start & end are defined"""

    todo = Todo(
        dtstart=start,
        due = end,
    )
    assert todo.computed_duration == datetime.timedelta(days=1)


def test_default_computed_duration_zero() -> None:
    """Test the default duration when no due or end time are set."""
    start = datetime.datetime(2025, 10, 27, 0, 0, 0, tzinfo=_TEST_TZ)
    todo = Todo(
        dtstart=start,
    )

    assert todo.end == start

    assert todo.computed_duration == datetime.timedelta()


def test_default_end_date() -> None:
    """Test that when only start is set and it's a date, end is the next day"""
    start = datetime.date(2025, 10, 27)
    todo = Todo(
        dtstart=start,
    )

    assert todo.end == start + datetime.timedelta(days=1)