-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_dates.py
More file actions
285 lines (225 loc) · 8.93 KB
/
Copy pathtest_dates.py
File metadata and controls
285 lines (225 loc) · 8.93 KB
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
"""
test_dates
~~~~~~~~~~~~~~~
Test functions in dates.py
"""
# stdlib
import re
from datetime import date, datetime, timedelta
from typing import Union
# 3rd party
import pytest
# this package
from domdf_python_tools import dates
from domdf_python_tools.dates import calc_easter, month_full_names
from domdf_python_tools.testing import count
# TODO: test get_timezone
try:
# 3rd party
import pytz
test_date = datetime(1996, 10, 13, 2, 20).replace(tzinfo=pytz.utc)
today = datetime.utcnow().replace(tzinfo=pytz.utc) # make sure UTC
def test_utc_offset():
# Check that the correct UTC offsets are given for common timezones
assert dates.get_utc_offset("US/Pacific", test_date) == timedelta(-1, 61200)
assert dates.get_utc_offset("Europe/London", test_date) == timedelta(0, 3600)
assert dates.get_utc_offset("Africa/Algiers", test_date) == timedelta(0, 3600)
# TODO: Finish
# Check that the correct UTC offsets are given for common timezones for today
assert dates.get_utc_offset("US/Pacific", today) in {
timedelta(-1, 57600),
timedelta(-1, 61200),
}
assert dates.get_utc_offset("Europe/London", today) in {
timedelta(0, 3600), # BST
timedelta(0, 0),
}
assert dates.get_utc_offset("Africa/Algiers", today) == timedelta(0, 3600)
# Check that the correct UTC offsets are given for common timezones when ``date`` is not given
assert dates.get_utc_offset("US/Pacific") in {
timedelta(-1, 57600),
timedelta(-1, 61200),
}
assert dates.get_utc_offset("Europe/London") in {
timedelta(0, 3600), # BST
timedelta(0, 0),
}
assert dates.get_utc_offset("Africa/Algiers") == timedelta(0, 3600)
def test_converting_timezone():
# No matter what timezone we convert to the timestamp should be the same
for tz in pytz.all_timezones:
assert test_date.astimezone(dates.get_timezone(tz, test_date),
).timestamp() == test_date.timestamp() == 845173200.0
if dates.get_utc_offset(tz, test_date): # otherwise the timezone stayed as UTC
assert test_date.astimezone(dates.get_timezone(tz, test_date)).hour != test_date.hour
# And again with today's date
assert today.astimezone(dates.get_timezone(tz, today)).timestamp() == today.timestamp()
if dates.get_utc_offset(tz, today): # otherwise the timezone stayed as UTC
assert today.astimezone(dates.get_timezone(tz, today)).hour != today.hour
def test_utc_timestamp_to_datetime():
# Going from a datetime object to timezone and back should give us the same object
for tz in pytz.all_timezones:
tzinfo = dates.get_timezone(tz, test_date)
dt = test_date.astimezone(tzinfo)
assert dates.utc_timestamp_to_datetime(dt.timestamp(), tzinfo) == dt
# And again with today's date
tzinfo = dates.get_timezone(tz, today)
dt = today.astimezone(tzinfo)
assert dates.utc_timestamp_to_datetime(dt.timestamp(), tzinfo) == dt
@pytest.mark.xfail()
def test_set_timezone():
# Setting the timezone should change the timestamp
for tz in pytz.all_timezones:
if dates.get_utc_offset(tz, today): # otherwise the timezone stayed as UTC
# ensure timestamp did change
target_tz = dates.get_timezone(tz, today)
assert target_tz is not None
assert dates.set_timezone(today, target_tz).timestamp() != today.timestamp()
# Difference between "today" and the new timezone should be the timezone difference
target_tz = dates.get_timezone(tz, today)
assert target_tz is not None
utc_offset = dates.get_utc_offset(tz, today)
assert utc_offset is not None
as_seconds = dates.set_timezone(today, target_tz).timestamp() + utc_offset.total_seconds()
assert as_seconds == today.timestamp()
if tz in {
"America/Punta_Arenas",
"America/Santiago",
"Antarctica/Palmer",
"Chile/Continental",
"Chile/EasterIsland",
"Pacific/Easter",
}:
continue
if dates.get_utc_offset(tz, test_date): # otherwise the timezone stayed as UTC
# print(dates.set_timezone(test_date, get_timezone(tz, test_date)).timestamp())
# print(repr(test_date))
# print(get_utc_offset(tz, test_date).total_seconds())
# print(test_date.timestamp())
# print(repr(dates.set_timezone(test_date, get_timezone(tz, test_date))))
# print(dates.set_timezone(test_date, get_timezone(tz, test_date)).timestamp())
# print(dates.set_timezone(test_date, get_timezone(tz, test_date)).timestamp() + get_utc_offset(tz, test_date).total_seconds())
# print(get_utc_offset(tz, test_date).total_seconds())
# print(
# dates.set_timezone(test_date, get_timezone(tz, test_date)).timestamp() +
# get_utc_offset(tz, test_date).total_seconds()
#
# )
target_tz = dates.get_timezone(tz, test_date)
assert target_tz is not None
offset = dates.get_utc_offset(tz, test_date)
assert offset is not None
as_seconds = dates.set_timezone(test_date, target_tz).timestamp() + offset.total_seconds()
assert as_seconds == test_date.timestamp()
except ImportError:
def test_utc_offset_no_pytz():
with pytest.raises(
ImportError,
match=r"'get_utc_offset' requires pytz \(.*\), but it could not be imported",
):
dates.get_utc_offset # pylint: disable=pointless-statement
with pytest.raises(
ImportError,
match=r"'get_utc_offset' requires pytz \(.*\), but it could not be imported",
):
# this package
from domdf_python_tools.dates import get_utc_offset # noqa: F401
# TODO: Finish
def test_parse_month():
for month_idx, month in enumerate(month_full_names):
month_idx += 1 # to make 1-indexed
for i in range(3, len(month)):
assert dates.parse_month(month.lower()[:i]) == month
assert dates.parse_month(month.upper()[:i]) == month
assert dates.parse_month(month.capitalize()[:i]) == month
assert dates.parse_month(month_idx) == month
for value in ["abc", 0, '0', -1, "-1", 13, "13"]:
with pytest.raises(ValueError, match=fr"The given month \({value!r}\) is not recognised."):
dates.parse_month(value) # type: ignore
@pytest.mark.parametrize("month_idx, month", enumerate(month_full_names))
def test_get_month_number_from_name(month_idx: int, month: str):
month_idx += 1 # to make 1-indexed
for i in range(3, len(month)):
assert dates.get_month_number(month.lower()[:i]) == month_idx
assert dates.get_month_number(month.upper()[:i]) == month_idx
assert dates.get_month_number(month.capitalize()[:i]) == month_idx
assert dates.get_month_number(month) == month_idx
@count(13, 1)
def test_get_month_number_from_no(count: int):
assert dates.get_month_number(count) == count
@pytest.mark.parametrize(
"value, match",
[
(0, "The given month (0) is not recognised."),
(-1, "The given month (-1) is not recognised."),
(13, "The given month (13) is not recognised."),
("abc", "The given month ('abc') is not recognised."),
('0', "The given month ('0') is not recognised."),
("-1", "The given month ('-1') is not recognised."),
("13", "The given month ('13') is not recognised."),
]
)
def test_get_month_number_errors(value: Union[str, int], match: str):
with pytest.raises(ValueError, match=re.escape(match)):
dates.get_month_number(value)
def test_check_date():
for month_idx, month in enumerate(month_full_names):
month_idx += 1 # to make 1-indexed
if month_idx in {9, 4, 6, 11}:
max_day = 30
elif month_idx == 2:
max_day = 28
else:
max_day = 31
for day in range(-5, 36):
if month_idx == 2 and day == 29:
for i in range(3, len(month)):
assert dates.check_date(month.lower()[:i], 29)
assert dates.check_date(month.upper()[:i], 29)
assert dates.check_date(month.capitalize()[:i], 29)
assert not dates.check_date(month.lower()[:i], 29, False)
assert not dates.check_date(month.upper()[:i], 29, False)
assert not dates.check_date(month.capitalize()[:i], 29, False)
assert dates.check_date(month, 29)
assert not dates.check_date(month, 29, False)
elif 0 < day <= max_day:
for i in range(3, len(month)):
assert dates.check_date(month.lower()[:i], day)
assert dates.check_date(month.upper()[:i], day)
assert dates.check_date(month.capitalize()[:i], day)
assert dates.check_date(month, day)
else:
for i in range(3, len(month)):
assert not dates.check_date(month.lower()[:i], day)
assert not dates.check_date(month.upper()[:i], day)
assert not dates.check_date(month.capitalize()[:i], day)
assert not dates.check_date(month, day)
@pytest.mark.parametrize(
"date",
[
date(2000, 4, 23),
date(2001, 4, 15),
date(2002, 3, 31),
date(2003, 4, 20),
date(2004, 4, 11),
date(2005, 3, 27),
date(2006, 4, 16),
date(2007, 4, 8),
date(2008, 3, 23),
date(2009, 4, 12),
date(2010, 4, 4),
date(2011, 4, 24),
date(2012, 4, 8),
date(2013, 3, 31),
date(2014, 4, 20),
date(2015, 4, 5),
date(2016, 3, 27),
date(2017, 4, 16),
date(2018, 4, 1),
date(2019, 4, 21),
date(2020, 4, 12),
date(2021, 4, 4),
]
)
def test_calc_easter(date):
assert calc_easter(date.year) == date