-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathtest_timer.py
122 lines (85 loc) · 2.71 KB
/
test_timer.py
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
import asyncio
import pytest
from realtime._async.timer import AsyncTimer
def linear_backoff(tries: int) -> int:
return tries * 0.1
@pytest.mark.asyncio
async def test_timer_initialization():
async def callback():
pass
timer = AsyncTimer(callback, linear_backoff)
assert timer.tries == 0
assert timer.timer is None
assert timer.callback == callback
assert timer.timer_calc == linear_backoff
@pytest.mark.asyncio
async def test_timer_schedule():
callback_called = False
async def callback():
nonlocal callback_called
callback_called = True
timer = AsyncTimer(callback, linear_backoff)
timer.schedule_timeout()
assert timer.tries == 1
assert timer.timer is not None
assert not timer.timer.done()
# Wait for the timer to complete
await timer.timer
assert callback_called
@pytest.mark.asyncio
async def test_timer_reset():
callback_called = False
async def callback():
nonlocal callback_called
callback_called = True
timer = AsyncTimer(callback, linear_backoff)
timer.schedule_timeout()
# Reset before the timer completes
timer.reset()
assert timer.tries == 0
assert timer.timer is None
# Wait a bit to ensure the original timer doesn't fire
await asyncio.sleep(0.2)
assert not callback_called
@pytest.mark.asyncio
async def test_timer_multiple_schedules():
callback_count = 0
async def callback():
nonlocal callback_count
callback_count += 1
timer = AsyncTimer(callback, linear_backoff)
# Schedule multiple times
timer.schedule_timeout()
timer.schedule_timeout()
timer.schedule_timeout()
assert timer.tries == 3
assert timer.timer is not None
# Wait for the last timer to complete
await timer.timer
assert callback_count == 1 # Only the last schedule should fire
@pytest.mark.asyncio
async def test_timer_callback_error():
error_caught = False
async def callback():
raise ValueError("Test error")
timer = AsyncTimer(callback, linear_backoff)
timer.schedule_timeout()
# Wait for the timer to complete
await timer.timer
# The error should be caught and logged, but not re-raised
assert timer.timer.done()
@pytest.mark.asyncio
async def test_timer_cancellation():
callback_called = False
async def callback():
nonlocal callback_called
callback_called = True
timer = AsyncTimer(callback, linear_backoff)
timer.schedule_timeout()
# Cancel the timer
timer.timer.cancel()
# Wait a bit to ensure the timer doesn't fire
await asyncio.sleep(0.2)
assert not callback_called
assert timer.timer.done()
assert timer.timer.cancelled()