File size: 10,427 Bytes
4d127e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
"""
    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)
#

###################################################################################################
###################################################################################################
###################################################################################################
#