Debian Codegraph @

hypothesis-python/src/hypothesis/extra/dateutil.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 """
12 This module provides :pypi:`dateutil <python-dateutil>` timezones.
13
14 You can use this strategy to make :func:`~hypothesis.strategies.datetimes`
15 and :func:`~hypothesis.strategies.times` produce timezone-aware values.
16
17 .. tip::
18 Consider using the stdlib :mod:`zoneinfo` module, via
19 :func:`st.timezones() <hypothesis.strategies.timezones>`.
20 """
21
22 import datetime as dt
23
24 from dateutil import tz, zoneinfo # type: ignore
25
26 from hypothesis import strategies as st
27 from hypothesis.strategies._internal.utils import cacheable, defines_strategy
28
29 __all__ = ["timezones"]
30
31
32 def __zone_sort_key(zone):
33 """Sort by absolute UTC offset at reference date,
34 positive first, with ties broken by name.
35 """
36 assert zone is not None
37 offset = zone.utcoffset(dt.datetime(2000, 1, 1))
38 offset = 999 if offset is None else offset
39 return (abs(offset), -offset, str(zone))
40
41
42 @cacheable
43 @defines_strategy()
44 def timezones() -> st.SearchStrategy[dt.tzinfo]:
45 """Any timezone from :pypi:`dateutil <python-dateutil>`.
46
47 This strategy minimises to UTC, or the timezone with the smallest offset
48 from UTC as of 2000-01-01, and is designed for use with
49 :py:func:`~hypothesis.strategies.datetimes`.
50
51 Note that the timezones generated by the strategy may vary depending on the
52 configuration of your machine. See the dateutil documentation for more
53 information.
54 """
55 all_timezones = sorted(
56 (tz.gettz(t) for t in zoneinfo.get_zonefile_instance().zones),
57 key=__zone_sort_key,
58 )
59 all_timezones.insert(0, tz.UTC)
60 # We discard Nones in the list comprehension because Mypy knows that
61 # tz.gettz may return None. However this should never happen for known
62 # zone names, so we assert that it's impossible first.
63 assert None not in all_timezones
64 return st.sampled_from([z for z in all_timezones if z is not None])