Debian Codegraph @

hypothesis-python/tests/datetime/test_pytz_timezones.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 import datetime as dt
12 import sys
13 import warnings
14
15 import pytest
16
17 from hypothesis import assume, given, settings, strategies as st
18 from hypothesis.errors import InvalidArgument, StopTest
19 from hypothesis.strategies import data, datetimes, just, sampled_from, times
20 from hypothesis.strategies._internal.datetime import datetime_does_not_exist
21
22 from tests.common.debug import assert_all_examples, find_any, minimal
23 from tests.common.utils import Why, xfail_on_crosshair
24
25 with warnings.catch_warnings():
26 if sys.version_info[:2] >= (3, 12):
27 # See https://github.com/stub42/pytz/issues/105 and
28 # https://github.com/dateutil/dateutil/pull/1285/
29 warnings.simplefilter("ignore", DeprecationWarning)
30 import pytz
31 from dateutil.tz import datetime_exists
32
33 from hypothesis.extra.pytz import timezones
34
35
36 def test_utc_is_minimal():
37 assert pytz.UTC is minimal(timezones())
38
39
40 def test_can_generate_non_naive_time():
41 assert minimal(times(timezones=timezones()), lambda d: d.tzinfo).tzinfo == pytz.UTC
42
43
44 def test_can_generate_non_naive_datetime():
45 assert (
46 minimal(datetimes(timezones=timezones()), lambda d: d.tzinfo).tzinfo == pytz.UTC
47 )
48
49
50 @given(datetimes(timezones=timezones()))
51 def test_timezone_aware_datetimes_are_timezone_aware(dt):
52 assert dt.tzinfo is not None
53
54
55 @given(sampled_from(["min_value", "max_value"]), datetimes(timezones=timezones()))
56 def test_datetime_bounds_must_be_naive(name, val):
57 with pytest.raises(InvalidArgument):
58 datetimes(**{name: val}).validate()
59
60
61 def test_underflow_in_simplify():
62 # we shouldn't trigger a pytz bug when we're simplifying
63 minimal(
64 datetimes(
65 max_value=dt.datetime.min + dt.timedelta(days=3), timezones=timezones()
66 ),
67 lambda x: x.tzinfo != pytz.UTC,
68 )
69
70
71 def test_overflow_in_simplify():
72 # we shouldn't trigger a pytz bug when we're simplifying
73 minimal(
74 datetimes(
75 min_value=dt.datetime.max - dt.timedelta(days=3), timezones=timezones()
76 ),
77 lambda x: x.tzinfo != pytz.UTC,
78 )
79
80
81 def test_timezones_arg_to_datetimes_must_be_search_strategy():
82 with pytest.raises(InvalidArgument):
83 datetimes(timezones=pytz.all_timezones).validate()
84
85 tz = [pytz.timezone(t) for t in pytz.all_timezones]
86 with pytest.raises(InvalidArgument):
87 datetimes(timezones=tz).validate()
88
89
90 @given(times(timezones=timezones()))
91 def test_timezone_aware_times_are_timezone_aware(dt):
92 assert dt.tzinfo is not None
93
94
95 def test_can_generate_non_utc():
96 times(timezones=timezones()).filter(
97 lambda d: assume(d.tzinfo) and d.tzinfo.zone != "UTC"
98 ).validate()
99
100
101 @given(sampled_from(["min_value", "max_value"]), times(timezones=timezones()))
102 def test_time_bounds_must_be_naive(name, val):
103 with pytest.raises(InvalidArgument):
104 times(**{name: val}).validate()
105
106
107 @pytest.mark.parametrize(
108 "bound",
109 [
110 {"min_value": dt.datetime.max - dt.timedelta(days=3)},
111 {"max_value": dt.datetime.min + dt.timedelta(days=3)},
112 ],
113 )
114 def test_can_trigger_error_in_draw_near_boundary(bound):
115 found = False
116
117 # this would be better written with find_any, but I couldn't get rewriting
118 # with st.composite and assuming the event condition to work.
119 # https://github.com/HypothesisWorks/hypothesis/pull/4229#discussion_r1907993831
120 @given(st.data())
121 @settings(max_examples=1000)
122 def f(data):
123 try:
124 data.draw(datetimes(**bound, timezones=timezones()))
125 except StopTest:
126 pass
127 if "Failed to draw a datetime" in data.conjecture_data.events.get(
128 "invalid because", ""
129 ):
130 nonlocal found
131 found = True
132
133 f()
134 assert found
135
136
137 @given(data(), datetimes(), datetimes())
138 def test_datetimes_stay_within_naive_bounds(data, lo, hi):
139 if lo > hi:
140 lo, hi = hi, lo
141 out = data.draw(datetimes(lo, hi, timezones=timezones()))
142 assert lo <= out.replace(tzinfo=None) <= hi
143
144
145 @pytest.mark.parametrize(
146 "kw",
147 [
148 # Ireland uses *negative* offset DST, which means that our sloppy interpretation
149 # of "is_dst=not fold" bypasses the filter for imaginary times. This is basically
150 # unfixable without redesigning pytz per PEP-495, and it's much more likely to be
151 # replaced by dateutil or PEP-615 zoneinfo in the standard library instead.
152 {
153 "min_value": dt.datetime(2019, 3, 31),
154 "max_value": dt.datetime(2019, 4, 1),
155 "timezones": just(pytz.timezone("Europe/Dublin")),
156 },
157 # The day of a spring-forward transition in Australia; 2am is imaginary
158 # (the common case so an optimistic `is_dst=bool(fold)` also fails the test)
159 {
160 "min_value": dt.datetime(2020, 10, 4),
161 "max_value": dt.datetime(2020, 10, 5),
162 "timezones": just(pytz.timezone("Australia/Sydney")),
163 },
164 ],
165 )
166 @xfail_on_crosshair(Why.symbolic_outside_context, strict=False)
167 def test_datetimes_can_exclude_imaginary(kw):
168 # Sanity check: fail unless those days contain an imaginary hour to filter out
169 find_any(datetimes(**kw, allow_imaginary=True), lambda x: not datetime_exists(x))
170
171 # Assert that with allow_imaginary=False we only generate existing datetimes.
172 assert_all_examples(datetimes(**kw, allow_imaginary=False), datetime_exists)
173
174
175 def test_really_weird_tzinfo_case():
176 x = dt.datetime(2019, 3, 31, 2, 30, tzinfo=pytz.timezone("Europe/Dublin"))
177 assert x.tzinfo is not x.astimezone(dt.timezone.utc).astimezone(x.tzinfo)
178 # And that weird case exercises the rare branch in our helper:
179 assert datetime_does_not_exist(x)