""" Tests for the shared date/time boilerplate. These pin timezone resolution, epoch conversions, and the centralized sleep helpers that replaced raw `time.sleep()`/`asyncio.sleep()` calls in application modules. """ from __future__ import annotations # ################################################################################################### ################################################################################################### ################################################################################################### Standard Modules # import asyncio import time as time_module from datetime import datetime, timezone, tzinfo import pytest # ################################################################################################### ################################################################################################### ################################################################################################### My Modules # from candlefetcher.util import datetimer from candlefetcher.util.datetimer import ( async_sleep, datetime_to_timestamp, get_timezone, get_timezone_object, monotonic, monotonic_ns, now_utc, resolve_timezone, set_timezone, sleep, timestamp, timestamp_to_datetime, timestamp_to_human, utc_timezone, ) # ################################################################################################### ################################################################################################### ################################################################################################### Timezone Resolution # def test_resolve_timezone_defaults_to_working_timezone() -> None: """`None` resolves to the process-wide working timezone object.""" resolved = resolve_timezone() assert (isinstance(resolved, tzinfo)) assert (resolved is get_timezone_object()) # def test_resolve_timezone_accepts_names_and_objects() -> None: """Timezone names and tzinfo objects both resolve.""" utc_by_name = resolve_timezone('UTC') utc_by_tzinfo = resolve_timezone(timezone.utc) assert (str(utc_by_name) == 'UTC') assert (utc_by_tzinfo is timezone.utc) # @pytest.mark.parametrize( 'bad_name', ['', ' ', 'Mars/Olympus_Mons'], ) def test_resolve_timezone_rejects_invalid_names(bad_name:str) -> None: """Empty and unknown timezone names fail fast with a descriptive error.""" with pytest.raises(ValueError, match='[Tt]imezone'): resolve_timezone(bad_name) # # def test_resolve_timezone_rejects_wrong_types() -> None: """Non-string, non-tzinfo inputs are type errors.""" with pytest.raises(TypeError): resolve_timezone(42) # type: ignore[arg-type] # # def test_set_timezone_and_restore(monkeypatch:pytest.MonkeyPatch) -> None: """The working timezone can be changed and reset to the default.""" default = get_timezone() try: set_timezone('UTC') assert (get_timezone() == 'UTC') assert (get_timezone_object() is resolve_timezone('UTC')) set_timezone(None) assert (get_timezone() == default) # finally: set_timezone(default) # # def test_utc_timezone_helper() -> None: """Publication planning can request fixed UTC explicitly.""" assert (utc_timezone() is timezone.utc) # def test_now_utc_is_timezone_aware() -> None: """The UTC now helper always returns aware datetimes.""" value = now_utc() assert (value.tzinfo is timezone.utc) assert (abs(value.timestamp() - time_module.time()) < 5.0) # ################################################################################################### ################################################################################################### ################################################################################################### Epoch Conversions # @pytest.mark.parametrize( 'input_value, expected_seconds', [ (1_700_000_000 , 1_700_000_000.0), (1_700_000_000_000 , 1_700_000_000.0), # milliseconds (1_700_000_000.5 , 1_700_000_000.5), ], ) def test_timestamp_to_datetime_units(input_value:float, expected_seconds:float) -> None: """Second- and millisecond-magnitude inputs convert to the correct instant.""" resolved = timestamp_to_datetime(input_value, ms=(input_value > 1e12)) assert (pytest.approx(resolved.timestamp()) == expected_seconds) # def test_timestamp_to_datetime_timezone_choice() -> None: """Rendering timezone affects the wall clock, not the instant.""" in_utc = timestamp_to_datetime(1_700_000_000, tz='UTC') in_tehran = timestamp_to_datetime(1_700_000_000, tz='Asia/Tehran') assert (in_utc.hour == 22) assert (in_tehran.hour == 1) assert (in_tehran.day == 15) assert (in_utc.timestamp() == in_tehran.timestamp()) # @pytest.mark.parametrize( 'bad_value', [float('nan'), float('inf'), -float('inf'), '1700000000'], ) def test_timestamp_to_datetime_rejects_non_finite_and_non_numeric(bad_value:object) -> None: """Non-finite and non-numeric timestamps fail validation.""" with pytest.raises((TypeError, ValueError)): timestamp_to_datetime(bad_value) # type: ignore[arg-type] # # def test_datetime_to_timestamp_roundtrip() -> None: """Aware datetimes round-trip exactly; naive datetimes are rejected.""" aware = datetime(2023, 11, 14, 22, 13, 20, tzinfo=timezone.utc) seconds = datetime_to_timestamp(aware) assert (seconds == 1_700_000_000.0) assert (datetime_to_timestamp(aware.astimezone(utc_timezone())) == seconds) assert (datetime_to_timestamp(aware, ms=True) == 1_700_000_000_000) with pytest.raises(ValueError, match='timezone-aware'): datetime_to_timestamp(datetime(2023, 11, 14, 22, 13, 20)) # type: ignore[arg-type] # # def test_timestamp_to_human_filesystem_format() -> None: """Human formatting produces the project's filesystem-safe convention.""" text = timestamp_to_human(1_700_000_000, tz='UTC') assert (text == '2023_11_14__22_13_20') # def test_timestamp_helpers_current_clock() -> None: """Current-clock helpers produce sane values in the right units.""" seconds = timestamp() millis = timestamp(ms=True) assert (isinstance(seconds, float)) assert (isinstance(millis, int)) assert (abs(seconds - time_module.time()) < 1.0) assert (abs(millis / 1000.0 - time_module.time()) < 1.0) # def test_monotonic_helpers_only_measure_durations() -> None: """Monotonic readings advance and never flow backward.""" start = monotonic() start_ns = monotonic_ns() time_module.sleep(0.01) assert (monotonic() >= start) assert (monotonic_ns() >= start_ns) assert (monotonic_ns() > start_ns) # ################################################################################################### ################################################################################################### ################################################################################################### Centralized Sleep # def test_sync_sleep_accepts_zero_and_rejects_invalid() -> None: """Zero sleeps return immediately; negative and non-finite delays fail validation.""" sleep(0.0) sleep(0) for bad_value in (-0.1, float('nan'), float('inf'), True, '1', None): with pytest.raises((TypeError, ValueError)): sleep(bad_value) # type: ignore[arg-type] # # # def test_sync_sleep_delegates_to_time_sleep(monkeypatch:pytest.MonkeyPatch) -> None: """The helper routes through the standard sleep primitive exactly once.""" calls:list[float] = [] monkeypatch.setattr(datetimer.time, 'sleep', lambda seconds:calls.append(seconds)) sleep(0.25) assert (calls == [0.25]) # @pytest.mark.asyncio async def test_async_sleep_yields_to_event_loop() -> None: """Async sleep keeps the loop responsive while waiting.""" heartbeats = 0 async def heartbeat() -> None: nonlocal heartbeats for _ in range(5): await asyncio.sleep(0) heartbeats += 1 # # await asyncio.gather(async_sleep(0.01), heartbeat()) assert (heartbeats == 5) # @pytest.mark.asyncio async def test_async_sleep_rejects_invalid() -> None: """The async helper shares the sync helper's validation contract.""" for bad_value in (-0.1, float('nan'), True, '1'): with pytest.raises((TypeError, ValueError)): await async_sleep(bad_value) # type: ignore[arg-type] # # # ################################################################################################### ################################################################################################### ################################################################################################### Remaining Helpers # def test_now_iso_and_filesystem_helpers() -> None: """The remaining current-time helpers produce well-formed output.""" from candlefetcher.util.datetimer import now__yyyy_mm_dd, now__yyyy_mm_dd__hh_mm_ss, now_iso, timestamp_ns iso = now_iso(tz='UTC') assert ('T' in iso) with pytest.raises(ValueError, match='timespec'): now_iso(tz='UTC', timespec='nanoseconds') # type: ignore[arg-type] # stamp = now__yyyy_mm_dd__hh_mm_ss(tz='UTC') assert (len(stamp) == len('YYYY_MM_DD__HH_MM_SS')) assert (stamp.count('_') == 6) # three in the date, two separators, one double-underscore date_text = now__yyyy_mm_dd(tz='UTC') assert (len(date_text) == 10) nanos = timestamp_ns() assert (nanos > 1_500_000_000_000_000_000) # def test_datetime_to_timestamp_millisecond_branch() -> None: """The millisecond output branch truncates rather than rounding.""" aware = datetime(2023, 11, 14, 22, 13, 20, 500_000, tzinfo=timezone.utc) assert (datetime_to_timestamp(aware, ms=True) == 1_700_000_000_500) # ################################################################################################### ################################################################################################### ################################################################################################### #