示例工程 16-stdlib-tour

16-stdlib-tour/04-aware-datetime/test_aware_datetime.py

python · 1.2 KB

"""test_aware_datetime.py"""
 
from __future__ import annotations
 
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
 
import pytest
from aware_datetime import main
 
 
def test_naive_vs_aware() -> None:
    naive = datetime(2024, 1, 1, 12, 0, 0)
    aware = datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC)
    assert naive.tzinfo is None
    assert aware.tzinfo is UTC
    with pytest.raises(TypeError, match="offset-naive"):
        _ = naive - aware
 
 
def test_zone_conversion() -> None:
    aware = datetime(2024, 1, 1, 12, 0, tzinfo=UTC)
    shanghai = aware.astimezone(ZoneInfo("Asia/Shanghai"))
    assert shanghai.isoformat() == "2024-01-01T20:00:00+08:00"
    new_york = datetime(2024, 7, 1, 12, 0, tzinfo=UTC).astimezone(ZoneInfo("America/New_York"))
    assert new_york.isoformat() == "2024-07-01T08:00:00-04:00"
 
 
def test_dst_gap() -> None:
    before = datetime(2024, 3, 10, 1, 30, tzinfo=ZoneInfo("America/New_York"))
    after = before + timedelta(hours=2)
    assert after.isoformat() == "2024-03-10T03:30:00-04:00"
 
 
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
    main()
    out = capsys.readouterr().out
    assert "shanghai: 2024-01-01T20:00:00+08:00" in out
    assert "naive-aware: can't subtract" in out