| 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:`pytz` timezones. |
| 13 |
|
| 14 |
If you are unable to use the stdlib :mod:`zoneinfo` module, e.g. via the |
| 15 |
:func:`hypothesis.strategies.timezones` strategy, you can use this |
| 16 |
strategy with :py:func:`hypothesis.strategies.datetimes` and |
| 17 |
:py:func:`hypothesis.strategies.times` to produce timezone-aware values. |
| 18 |
|
| 19 |
.. warning:: |
| 20 |
|
| 21 |
Since :mod:`zoneinfo` was added in Python 3.9, this extra |
| 22 |
is deprecated. We intend to remove it after libraries |
| 23 |
such as Pandas and Django complete their own migrations. |
| 24 |
""" |
| 25 |
|
| 26 |
import datetime as dt |
| 27 |
|
| 28 |
import pytz |
| 29 |
from pytz.tzfile import StaticTzInfo # type: ignore # considered private by typeshed |
| 30 |
|
| 31 |
from hypothesis import strategies as st |
| 32 |
from hypothesis.strategies._internal.utils import cacheable, defines_strategy |
| 33 |
|
| 34 |
__all__ = ["timezones"] |
| 35 |
|
| 36 |
|
| 37 |
@cacheable |
| 38 |
@defines_strategy() |
| 39 |
def timezones() -> st.SearchStrategy[dt.tzinfo]: |
| 40 |
"""Any timezone in the Olsen database, as a pytz tzinfo object. |
| 41 |
|
| 42 |
This strategy minimises to UTC, or the smallest possible fixed |
| 43 |
offset, and is designed for use with :func:`hypothesis.strategies.datetimes`. |
| 44 |
|
| 45 |
.. tip:: |
| 46 |
Prefer the :func:`hypothesis.strategies.timezones` strategy, which uses |
| 47 |
the stdlib :mod:`zoneinfo` module and avoids `the many footguns in pytz |
| 48 |
<https://blog.ganssle.io/articles/2018/03/pytz-fastest-footgun.html>`__. |
| 49 |
""" |
| 50 |
all_timezones = [pytz.timezone(tz) for tz in pytz.all_timezones] |
| 51 |
# Some timezones have always had a constant offset from UTC. This makes |
| 52 |
# them simpler than timezones with daylight savings, and the smaller the |
| 53 |
# absolute offset the simpler they are. Of course, UTC is even simpler! |
| 54 |
static: list = [pytz.UTC] |
| 55 |
static += sorted( |
| 56 |
(t for t in all_timezones if isinstance(t, StaticTzInfo)), |
| 57 |
key=lambda tz: abs(tz.utcoffset(dt.datetime(2000, 1, 1))), |
| 58 |
) |
| 59 |
# Timezones which have changed UTC offset; best ordered by name. |
| 60 |
dynamic = [tz for tz in all_timezones if tz not in static] |
| 61 |
return st.sampled_from(static + dynamic) |