| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import datetime |
| 4 |
import os |
| 5 |
import time |
| 6 |
import typing |
| 7 |
import zoneinfo |
| 8 |
from contextlib import contextmanager |
| 9 |
|
| 10 |
import pytest |
| 11 |
|
| 12 |
|
| 13 |
@contextmanager |
| 14 |
def stub_timezone_ctx(tzname: str | None) -> typing.Generator[None]: |
| 15 |
""" |
| 16 |
Switch to a locally-known timezone specified by `tzname`. |
| 17 |
On exit, restore the previous timezone. |
| 18 |
If `tzname` is `None`, do nothing. |
| 19 |
""" |
| 20 |
if tzname is None: |
| 21 |
yield |
| 22 |
return |
| 23 |
|
| 24 |
# Only supported on Unix |
| 25 |
if not hasattr(time, "tzset"): |
| 26 |
pytest.skip("Timezone patching is not supported") |
| 27 |
|
| 28 |
# Make sure the new timezone exists |
| 29 |
try: |
| 30 |
zoneinfo.ZoneInfo(tzname) |
| 31 |
except zoneinfo.ZoneInfoNotFoundError: |
| 32 |
raise ValueError(f"Invalid timezone specified: {tzname!r}") |
| 33 |
|
| 34 |
# Get the current timezone |
| 35 |
old_tzname = datetime.datetime.now().astimezone().tzname() |
| 36 |
if old_tzname is None: |
| 37 |
raise OSError("Cannot determine current timezone") |
| 38 |
|
| 39 |
os.environ["TZ"] = tzname |
| 40 |
time.tzset() |
| 41 |
yield |
| 42 |
os.environ["TZ"] = old_tzname |
| 43 |
time.tzset() |