Debian Codegraph @

recurring_ical_events/test/conftest.py

raw symbols SCIP
1 import sys
2 import time
3 from datetime import timezone
4 from pathlib import Path
5
6 import dateutil
7 import icalendar
8 import pytest
9 import pytz
10
11 from recurring_ical_events import of
12
13 try:
14 import zoneinfo as _zoneinfo
15 except ImportError:
16 import backports.zoneinfo as _zoneinfo
17
18 HERE = Path(__file__).parent
19 REPO = Path(HERE).parent.parent
20
21 sys.path.append(str(REPO))
22
23
24 CALENDARS_FOLDER = HERE / "calendars"
25 # set the default time zone
26 # see https://stackoverflow.com/questions/1301493/setting-timezone-in-python
27 time.tzset()
28
29
30 class ICSCalendars:
31 """A collection of parsed ICS calendars
32
33 components is the argument to pass to the of function"""
34
35 Calendar = icalendar.Calendar
36 components = None
37 skip_bad_series = None
38
39 def __init__(self, tzp):
40 """Create ICS calendars in a specific timezone."""
41 self.tzp = tzp
42
43 def get_calendar(self, content):
44 """Return the calendar given the content."""
45 self.tzp()
46 return self.Calendar.from_ical(content)
47
48 def __getitem__(self, name):
49 return getattr(self, name)
50
51 @property
52 def raw(self):
53 return ICSCalendars(self.tzp)
54
55 def consistent_tz(self, dt):
56 """Make the datetime consistent with the time zones used in these calendars."""
57 assert dt.tzinfo is None or "pytz" in dt.tzinfo.__class__.__module__, (
58 "We need pytz time zones for now."
59 )
60 return dt
61
62 def _of(self, calendar):
63 """Return the calendar but also with selected components."""
64 kw = {}
65 if self.skip_bad_series is not None:
66 kw["skip_bad_series"] = self.skip_bad_series
67 if self.components is not None:
68 kw["components"] = self.components
69 return of(calendar, **kw)
70
71 def __repr__(self):
72 return f"{self.__class__.__name__}({self.tzp.__name__})"
73
74
75 _calendar_names = []
76 for calendar_path in CALENDARS_FOLDER.iterdir():
77 content = calendar_path.read_bytes()
78
79 @property
80 def get_calendar(self, content=content): # noqa: PLR0206
81 return self.get_calendar(content)
82
83 attribute_name = calendar_path.stem
84 setattr(ICSCalendars, attribute_name, get_calendar)
85 _calendar_names.append(attribute_name)
86
87
88 class Calendars(ICSCalendars):
89 """Collection of calendars from recurring_ical_events"""
90
91 def get_calendar(self, content):
92 return self._of(ICSCalendars.get_calendar(self, content))
93
94
95 class ReversedCalendars(ICSCalendars):
96 """All test should run in reversed item order.
97
98 RFC5545:
99 This memo imposes no ordering of properties within an iCalendar object.
100 """
101
102 def get_calendar(self, content):
103 """Calendar traversing events in reversed order."""
104 calendar = ICSCalendars.get_calendar(self, content)
105 _walk = calendar.walk
106
107 def walk(*args, **kw):
108 """Return properties in reversed order."""
109 return reversed(_walk(*args, **kw))
110
111 calendar.walk = walk
112 return self._of(calendar)
113
114
115 if hasattr(icalendar, "use_pytz") and hasattr(icalendar, "use_zoneinfo"):
116 tzps = [icalendar.use_pytz, icalendar.use_zoneinfo]
117 else:
118 tzps = [lambda: ...]
119
120
121 @pytest.fixture(params=tzps, scope="module")
122 def tzp(request):
123 """The timezone provider supported by icalendar."""
124 return request.param
125
126
127 # for parametrizing fixtures, see https://docs.pytest.org/en/latest/fixture.html#parametrizing-fixtures
128 @pytest.fixture(params=[Calendars, ReversedCalendars])
129 def calendars(request, tzp) -> ICSCalendars:
130 """The calendars we can use in the tests."""
131 return request.param(tzp)
132
133
134 @pytest.fixture
135 def todo():
136 """Skip a test because it needs to be written first."""
137 pytest.skip("This test is not yet implemented.")
138
139
140 @pytest.fixture(scope="module")
141 def zoneinfo():
142 """Return the zoneinfo module if present, otherwise skip the test.
143
144 Uses backports.zoneinfo or zoneinfo.
145 """
146 return _zoneinfo
147
148
149 @pytest.fixture(scope="module")
150 def ZoneInfo(zoneinfo):
151 """Shortcut for zoneinfo.ZoneInfo."""
152 return zoneinfo.ZoneInfo
153
154
155 @pytest.fixture(
156 scope="module",
157 params=[pytz.utc, _zoneinfo.ZoneInfo("UTC"), timezone.utc, dateutil.tz.UTC],
158 )
159 def utc(request):
160 """Return all the UTC implementations."""
161 return request.param
162
163
164 class DoctestZoneInfo(_zoneinfo.ZoneInfo):
165 """Constent ZoneInfo representation for tests."""
166
167 def __repr__(self):
168 return f"ZoneInfo(key={self.key!r})"
169
170
171 def doctest_print(obj):
172 """doctest print"""
173 if isinstance(obj, bytes):
174 obj = obj.decode("UTF-8")
175 print(str(obj).strip().replace("\r\n", "\n").replace("\r", "\n"))
176
177
178 @pytest.fixture
179 def env_for_doctest(monkeypatch):
180 """Modify the environment to make doctests run."""
181 monkeypatch.setitem(sys.modules, "zoneinfo", _zoneinfo)
182 monkeypatch.setattr(_zoneinfo, "ZoneInfo", DoctestZoneInfo)
183 from icalendar.timezone.zoneinfo import ZONEINFO
184
185 monkeypatch.setattr(ZONEINFO, "utc", _zoneinfo.ZoneInfo("UTC"))
186 return {
187 "print": doctest_print,
188 "CALENDARS": CALENDARS_FOLDER,
189 }
190
191
192 # remove invalid names
193 _calendar_names.remove("end_before_start_event")
194 _calendar_names.sort()
195
196
197 @pytest.fixture(scope="module", params=_calendar_names)
198 def calendar_name(request) -> str:
199 """All the calendar names."""
200 return request.param
201
202
203 @pytest.fixture
204 def alarms(calendars) -> ICSCalendars:
205 """The calendars to query for alarms.
206
207 This modifies the calendars fixture.
208 """
209 calendars.components = ["VALARM"]
210 return calendars