Skip to content

Commit 01728be

Browse files
Close MockServer (Fake server) gracefully in tests
Previosly only one of 2 methods (stop, wait_for_termination) was called to shut down the server. But both should be called. Otherwise server will continue working. Server will be destroyed by GC in different test causing missleading warnings. `stop` method stops the server from servicing new RPCs. `wait_for_termination` Block current coroutine until the server stops. Signed-off-by: ela-kotulska-frequenz <[email protected]>
1 parent a04c70c commit 01728be

File tree

7 files changed

+43
-24
lines changed

7 files changed

+43
-24
lines changed

tests/actor/test_data_sourcing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,5 +93,5 @@ async def test_data_sourcing_actor(self) -> None:
9393
assert sample is not None
9494
assert 100.0 == sample.value
9595

96-
await server.stop(0.1)
96+
assert await server.graceful_shutdown()
9797
_microgrid._MICROGRID = None # pylint: disable=protected-access

tests/microgrid/mock_api.py

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
from __future__ import annotations
1212

13+
import asyncio
14+
1315
# pylint: disable=invalid-name,no-name-in-module,unused-import
1416
from concurrent import futures
1517
from typing import Iterable, Iterator, List, Optional, Tuple
@@ -268,10 +270,31 @@ async def start(self) -> None:
268270
"""Start the server."""
269271
await self._server.start()
270272

271-
async def stop(self, grace: Optional[float]) -> None:
273+
async def _stop(self, grace: Optional[float]) -> None:
272274
"""Stop the server."""
273275
await self._server.stop(grace)
274276

275-
async def wait_for_termination(self, timeout: Optional[float] = None) -> None:
277+
async def _wait_for_termination(self, timeout: Optional[float] = None) -> None:
276278
"""Wait for termination."""
277279
await self._server.wait_for_termination(timeout)
280+
281+
async def graceful_shutdown(
282+
self, stop_timeout: float = 0.1, terminate_timeout: float = 0.2
283+
) -> bool:
284+
"""Shutdown server gracefully.
285+
286+
Args:
287+
stop_timeout: Argument for self.stop method
288+
terminate_timeout: Argument for self.wait_for_termination method.
289+
290+
Returns:
291+
True if server was stopped in given timeout. False otherwise.
292+
"""
293+
await self._stop(stop_timeout)
294+
try:
295+
await asyncio.wait_for(
296+
self._wait_for_termination(None), timeout=terminate_timeout
297+
)
298+
except TimeoutError:
299+
return False
300+
return True

tests/microgrid/test_client.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ async def test_components(self) -> None:
130130
}
131131

132132
finally:
133-
await server.stop(grace=1.0)
133+
assert await server.graceful_shutdown()
134134

135135
async def test_connections(self) -> None:
136136
servicer = mock_api.MockMicrogridServicer()
@@ -284,7 +284,7 @@ async def test_connections(self) -> None:
284284
}
285285

286286
finally:
287-
await server.stop(grace=1.0)
287+
assert await server.graceful_shutdown()
288288

289289
async def test_bad_connections(self) -> None:
290290
"""Validate that the client does not apply connection filters itself."""
@@ -355,7 +355,7 @@ def ListAllComponents(
355355
)
356356

357357
finally:
358-
await server.stop(grace=1.0)
358+
assert await server.graceful_shutdown()
359359

360360
async def test_meter_data(self) -> None:
361361
servicer = mock_api.MockMicrogridServicer()
@@ -383,7 +383,7 @@ async def test_meter_data(self) -> None:
383383
await asyncio.sleep(0.2)
384384

385385
finally:
386-
await server.stop(0.1)
386+
assert await server.graceful_shutdown()
387387

388388
latest = peekable.peek()
389389
assert isinstance(latest, MeterData)
@@ -415,7 +415,7 @@ async def test_battery_data(self) -> None:
415415
await asyncio.sleep(0.2)
416416

417417
finally:
418-
await server.stop(0.1)
418+
assert await server.graceful_shutdown()
419419

420420
latest = peekable.peek()
421421
assert isinstance(latest, BatteryData)
@@ -447,7 +447,7 @@ async def test_inverter_data(self) -> None:
447447
await asyncio.sleep(0.2)
448448

449449
finally:
450-
await server.stop(0.1)
450+
assert await server.graceful_shutdown()
451451

452452
latest = peekable.peek()
453453
assert isinstance(latest, InverterData)
@@ -479,7 +479,7 @@ async def test_ev_charger_data(self) -> None:
479479
await asyncio.sleep(0.2)
480480

481481
finally:
482-
await server.stop(0.1)
482+
assert await server.graceful_shutdown()
483483

484484
latest = peekable.peek()
485485
assert isinstance(latest, EVChargerData)
@@ -506,7 +506,7 @@ async def test_charge(self) -> None:
506506
assert servicer.latest_charge.power_w == 12
507507

508508
finally:
509-
await server.stop(0.1)
509+
assert await server.graceful_shutdown()
510510

511511
async def test_discharge(self) -> None:
512512
"""Check if discharge is able to discharge component."""
@@ -528,7 +528,7 @@ async def test_discharge(self) -> None:
528528
assert servicer.latest_discharge.component_id == 73
529529
assert servicer.latest_discharge.power_w == 15
530530
finally:
531-
await server.stop(0.1)
531+
assert await server.graceful_shutdown()
532532

533533
async def test_set_bounds(self) -> None:
534534
servicer = mock_api.MockMicrogridServicer()
@@ -558,7 +558,7 @@ async def test_set_bounds(self) -> None:
558558
await asyncio.sleep(0.1)
559559

560560
finally:
561-
await server.stop(0.1)
561+
assert await server.graceful_shutdown()
562562

563563
assert len(expected_bounds) == len(servicer.get_bounds())
564564

tests/microgrid/test_graph.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -766,7 +766,7 @@ async def test_refresh_from_api(self) -> None:
766766
}
767767
graph.validate()
768768

769-
await server.stop(1)
769+
assert await server.graceful_shutdown()
770770

771771
def test_validate(self) -> None:
772772
# `validate` will fail if any of the following are the case:

tests/microgrid/test_mock_api.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ async def test_MockGrpcServer() -> None:
239239
Connection(start=2, end=3),
240240
]
241241

242-
await server1.stop(1)
242+
await server1.graceful_shutdown()
243243

244244
servicer2 = mock_api.MockMicrogridServicer(
245245
components=[
@@ -285,4 +285,4 @@ async def test_MockGrpcServer() -> None:
285285
Connection(start=77, end=9999),
286286
]
287287

288-
await server2.wait_for_termination(0.1)
288+
await server2.graceful_shutdown()

tests/microgrid/test_timeout.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,6 @@
3030
# error and needs to be greater than `GRPC_CALL_TIMEOUT`.
3131
GRPC_SERVER_DELAY: float = 0.3
3232

33-
# How long a mocked Microgrid server should be running for a single test function,
34-
# before it gets shut down so that the tests can finish.
35-
GRPC_SERVER_SHUTDOWN_DELAY: float = 1.0
36-
3733

3834
@patch(
3935
"frequenz.sdk.microgrid.client._client.DEFAULT_GRPC_CALL_TIMEOUT", GRPC_CALL_TIMEOUT
@@ -59,7 +55,7 @@ def mock_list_components(
5955
with pytest.raises(grpc.aio.AioRpcError) as err_ctx:
6056
_ = await client.components()
6157
assert err_ctx.value.code() == grpc.StatusCode.DEADLINE_EXCEEDED
62-
await server.wait_for_termination(GRPC_SERVER_SHUTDOWN_DELAY)
58+
assert await server.graceful_shutdown()
6359

6460

6561
@patch(
@@ -86,7 +82,7 @@ def mock_list_connections(
8682
with pytest.raises(grpc.aio.AioRpcError) as err_ctx:
8783
_ = await client.connections()
8884
assert err_ctx.value.code() == grpc.StatusCode.DEADLINE_EXCEEDED
89-
await server.wait_for_termination(GRPC_SERVER_SHUTDOWN_DELAY)
85+
assert await server.graceful_shutdown()
9086

9187

9288
@patch(
@@ -117,4 +113,4 @@ def mock_set_power(
117113
_ = await client.set_power(component_id=1, power_w=power_w)
118114
assert err_ctx.value.code() == grpc.StatusCode.DEADLINE_EXCEEDED
119115

120-
await server.stop(GRPC_SERVER_SHUTDOWN_DELAY)
116+
assert await server.graceful_shutdown()

tests/timeseries/mock_microgrid.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,5 +243,5 @@ async def _init_client_and_actors(
243243

244244
async def cleanup(self) -> None:
245245
"""Clean up after a test."""
246-
await self._server.stop(0.1)
246+
await self._server.graceful_shutdown()
247247
microgrid._microgrid._MICROGRID = None # pylint: disable=protected-access

0 commit comments

Comments
 (0)