forked from frequenz-floss/frequenz-dispatch-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_mananging_actor.py
More file actions
216 lines (166 loc) · 6.42 KB
/
test_mananging_actor.py
File metadata and controls
216 lines (166 loc) · 6.42 KB
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
# LICENSE: ALL RIGHTS RESERVED
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH
"""Test the dispatch runner."""
import asyncio
import heapq
from dataclasses import dataclass, replace
from datetime import datetime, timedelta, timezone
from typing import AsyncIterator, Iterator
import async_solipsism
import time_machine
from frequenz.channels import Broadcast, Receiver, Sender
from frequenz.client.dispatch.recurrence import Frequency
from frequenz.client.dispatch.test.generator import DispatchGenerator
from frequenz.sdk.actor import Actor
from pytest import fixture
from frequenz.dispatch import Dispatch, DispatchManagingActor, DispatchUpdate
from frequenz.dispatch._bg_service import DispatchScheduler
@fixture
def event_loop_policy() -> async_solipsism.EventLoopPolicy:
"""Set the event loop policy to use async_solipsism."""
policy = async_solipsism.EventLoopPolicy()
asyncio.set_event_loop_policy(policy)
return policy
@fixture
def fake_time() -> Iterator[time_machine.Coordinates]:
"""Replace real time with a time machine that doesn't automatically tick."""
# destination can be a datetime or a timestamp (int), so are moving to the
# epoch (in UTC!)
with time_machine.travel(destination=0, tick=False) as traveller:
yield traveller
def _now() -> datetime:
"""Return the current time in UTC."""
return datetime.now(tz=timezone.utc)
class MockActor(Actor):
"""Mock actor for testing."""
async def _run(self) -> None:
while True:
await asyncio.sleep(1)
@dataclass
class TestEnv:
"""Test environment."""
actor: Actor
runner_actor: DispatchManagingActor
running_status_sender: Sender[Dispatch]
updates_receiver: Receiver[DispatchUpdate]
generator: DispatchGenerator = DispatchGenerator()
@fixture
async def test_env() -> AsyncIterator[TestEnv]:
"""Create a test environment."""
channel = Broadcast[Dispatch](name="dispatch ready test channel")
updates_channel = Broadcast[DispatchUpdate](name="dispatch update test channel")
actor = MockActor()
runner_actor = DispatchManagingActor(
actor=actor,
running_status_receiver=channel.new_receiver(),
updates_sender=updates_channel.new_sender(),
)
# pylint: disable=protected-access
runner_actor._restart_limit = 0
runner_actor.start()
yield TestEnv(
actor=actor,
runner_actor=runner_actor,
running_status_sender=channel.new_sender(),
updates_receiver=updates_channel.new_receiver(),
)
await runner_actor.stop()
async def test_simple_start_stop(
test_env: TestEnv,
fake_time: time_machine.Coordinates,
) -> None:
"""Test behavior when receiving start/stop messages."""
now = _now()
duration = timedelta(minutes=10)
dispatch = test_env.generator.generate_dispatch()
dispatch = replace(
dispatch,
active=True,
dry_run=False,
duration=duration,
start_time=now,
payload={"test": True},
type="UNIT_TEST",
recurrence=replace(
dispatch.recurrence,
frequency=Frequency.UNSPECIFIED,
),
)
await test_env.running_status_sender.send(Dispatch(dispatch))
fake_time.shift(timedelta(seconds=1))
event = await test_env.updates_receiver.receive()
assert event.options == {"test": True}
assert event.components == dispatch.target
assert event.dry_run is False
assert test_env.actor.is_running is True
fake_time.shift(duration)
await test_env.running_status_sender.send(Dispatch(dispatch))
# Give await actor.stop a chance to run in DispatchManagingActor
await asyncio.sleep(0.1)
assert test_env.actor.is_running is False
def test_heapq_dispatch_compare(test_env: TestEnv) -> None:
"""Test that the heapq compare function works."""
dispatch1 = test_env.generator.generate_dispatch()
dispatch2 = test_env.generator.generate_dispatch()
# Simulate two dispatches with the same 'until' time
now = datetime.now(timezone.utc)
until_time = now + timedelta(minutes=5)
# Create the heap
scheduled_events: list[DispatchScheduler.QueueItem] = []
# Push two events with the same 'until' time onto the heap
heapq.heappush(
scheduled_events,
DispatchScheduler.QueueItem(until_time, Dispatch(dispatch1), True),
)
heapq.heappush(
scheduled_events,
DispatchScheduler.QueueItem(until_time, Dispatch(dispatch2), True),
)
def test_heapq_dispatch_start_stop_compare(test_env: TestEnv) -> None:
"""Test that the heapq compare function works."""
dispatch1 = test_env.generator.generate_dispatch()
dispatch2 = test_env.generator.generate_dispatch()
# Simulate two dispatches with the same 'until' time
now = datetime.now(timezone.utc)
until_time = now + timedelta(minutes=5)
# Create the heap
scheduled_events: list[DispatchScheduler.QueueItem] = []
# Push two events with the same 'until' time onto the heap
heapq.heappush(
scheduled_events,
DispatchScheduler.QueueItem(until_time, Dispatch(dispatch1), stop_event=False),
)
heapq.heappush(
scheduled_events,
DispatchScheduler.QueueItem(until_time, Dispatch(dispatch2), stop_event=True),
)
assert scheduled_events[0].dispatch_id == dispatch1.id
assert scheduled_events[1].dispatch_id == dispatch2.id
async def test_dry_run(test_env: TestEnv, fake_time: time_machine.Coordinates) -> None:
"""Test the dry run mode."""
dispatch = test_env.generator.generate_dispatch()
dispatch = replace(
dispatch,
dry_run=True,
active=True,
start_time=_now(),
duration=timedelta(minutes=10),
type="UNIT_TEST",
recurrence=replace(
dispatch.recurrence,
frequency=Frequency.UNSPECIFIED,
),
)
await test_env.running_status_sender.send(Dispatch(dispatch))
fake_time.shift(timedelta(seconds=1))
event = await test_env.updates_receiver.receive()
assert event.dry_run is dispatch.dry_run
assert event.components == dispatch.target
assert event.options == dispatch.payload
assert test_env.actor.is_running is True
assert dispatch.duration is not None
fake_time.shift(dispatch.duration)
await test_env.running_status_sender.send(Dispatch(dispatch))
# Give await actor.stop a chance to run in DispatchManagingActor
await asyncio.sleep(0.1)
assert test_env.actor.is_running is False