Skip to content
Snippets Groups Projects
Commit 3c63d3c6 authored by Krzysztof Mochocki's avatar Krzysztof Mochocki
Browse files

Add teardown to AbstractCommunicator and apply it

parent 6e89a3eb
No related branches found
No related tags found
1 merge request!73Clive integration related fixes
Showing with 46 additions and 16 deletions
...@@ -140,7 +140,7 @@ class BeekeeperCommon(BeekeeperNotificationCallbacks, ABC): ...@@ -140,7 +140,7 @@ class BeekeeperCommon(BeekeeperNotificationCallbacks, ABC):
try: try:
self.__wait_till_ready() self.__wait_till_ready()
except (AssertionError, TimeoutError) as e: except (AssertionError, TimeoutError) as e:
self.close() self._close()
raise BeekeeperFailedToStartNotReadyOnTimeError from e raise BeekeeperFailedToStartNotReadyOnTimeError from e
def _run_application(self, settings: Settings, additional_cli_arguments: BeekeeperArguments) -> None: def _run_application(self, settings: Settings, additional_cli_arguments: BeekeeperArguments) -> None:
...@@ -163,7 +163,7 @@ class BeekeeperCommon(BeekeeperNotificationCallbacks, ABC): ...@@ -163,7 +163,7 @@ class BeekeeperCommon(BeekeeperNotificationCallbacks, ABC):
self.__close_notification_server() self.__close_notification_server()
return pid return pid
def close(self) -> None: def _close(self) -> None:
self._close_application() self._close_application()
self.__close_notification_server() self.__close_notification_server()
...@@ -218,7 +218,11 @@ class Beekeeper(BeekeeperCommon, SyncRemoteBeekeeper, ContextSync["Beekeeper"]): ...@@ -218,7 +218,11 @@ class Beekeeper(BeekeeperCommon, SyncRemoteBeekeeper, ContextSync["Beekeeper"]):
return self return self
def _finally(self) -> None: def _finally(self) -> None:
self.close() self.teardown()
def teardown(self) -> None:
self._close()
super().teardown()
class AsyncBeekeeper(BeekeeperCommon, AsyncRemoteBeekeeper, ContextAsync["AsyncBeekeeper"]): class AsyncBeekeeper(BeekeeperCommon, AsyncRemoteBeekeeper, ContextAsync["AsyncBeekeeper"]):
...@@ -244,4 +248,8 @@ class AsyncBeekeeper(BeekeeperCommon, AsyncRemoteBeekeeper, ContextAsync["AsyncB ...@@ -244,4 +248,8 @@ class AsyncBeekeeper(BeekeeperCommon, AsyncRemoteBeekeeper, ContextAsync["AsyncB
return self return self
async def _afinally(self) -> None: async def _afinally(self) -> None:
self.close() self.teardown()
def teardown(self) -> None:
self._close()
super().teardown()
...@@ -51,7 +51,7 @@ class Beekeeper(BeekeeperInterface, StateInvalidator): ...@@ -51,7 +51,7 @@ class Beekeeper(BeekeeperInterface, StateInvalidator):
@StateInvalidator.empty_call_after_invalidation(None) @StateInvalidator.empty_call_after_invalidation(None)
def teardown(self) -> None: def teardown(self) -> None:
if isinstance(self.__instance, AsynchronousBeekeeperHandle): if isinstance(self.__instance, AsynchronousBeekeeperHandle):
self.__instance.close() self.__instance.teardown()
self.invalidate(InvalidatedStateByClosingBeekeeperError()) self.invalidate(InvalidatedStateByClosingBeekeeperError())
def detach(self) -> int: def detach(self) -> int:
......
...@@ -51,7 +51,7 @@ class Beekeeper(BeekeeperInterface, StateInvalidator): ...@@ -51,7 +51,7 @@ class Beekeeper(BeekeeperInterface, StateInvalidator):
@StateInvalidator.empty_call_after_invalidation(None) @StateInvalidator.empty_call_after_invalidation(None)
def teardown(self) -> None: def teardown(self) -> None:
if isinstance(self.__instance, SynchronousBeekeeperHandle): if isinstance(self.__instance, SynchronousBeekeeperHandle):
self.__instance.close() self.__instance.teardown()
self.invalidate(InvalidatedStateByClosingBeekeeperError()) self.invalidate(InvalidatedStateByClosingBeekeeperError())
def detach(self) -> int: def detach(self) -> int:
......
...@@ -3,7 +3,8 @@ from __future__ import annotations ...@@ -3,7 +3,8 @@ from __future__ import annotations
import asyncio import asyncio
import time import time
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from typing import TYPE_CHECKING from threading import Thread
from typing import TYPE_CHECKING, Any, Awaitable
from helpy._communication.settings import CommunicationSettings from helpy._communication.settings import CommunicationSettings
from helpy._interfaces.settings_holder import SharedSettingsHolder from helpy._interfaces.settings_holder import SharedSettingsHolder
...@@ -26,6 +27,10 @@ class AbstractCommunicator(SharedSettingsHolder[CommunicationSettings], ABC): ...@@ -26,6 +27,10 @@ class AbstractCommunicator(SharedSettingsHolder[CommunicationSettings], ABC):
async def _async_send(self, url: HttpUrl, data: bytes, stopwatch: StopwatchResult) -> str: async def _async_send(self, url: HttpUrl, data: bytes, stopwatch: StopwatchResult) -> str:
"""Sends to given url given data asynchronously.""" """Sends to given url given data asynchronously."""
@abstractmethod
def teardown(self) -> None:
"""Called when work with communicator is over."""
async def _async_sleep_for_retry(self) -> None: async def _async_sleep_for_retry(self) -> None:
"""Sleeps using asyncio.sleep (for asynchronous implementations).""" """Sleeps using asyncio.sleep (for asynchronous implementations)."""
await asyncio.sleep(self.settings.period_between_retries.total_seconds()) await asyncio.sleep(self.settings.period_between_retries.total_seconds())
...@@ -70,3 +75,8 @@ class AbstractCommunicator(SharedSettingsHolder[CommunicationSettings], ABC): ...@@ -70,3 +75,8 @@ class AbstractCommunicator(SharedSettingsHolder[CommunicationSettings], ABC):
return TimeoutExceededError( return TimeoutExceededError(
url=url, request=data, timeout_secs=self.settings.timeout.total_seconds(), total_wait_time=total_time_secs url=url, request=data, timeout_secs=self.settings.timeout.total_seconds(), total_wait_time=total_time_secs
) )
def _asyncio_run(self, coro: Awaitable[Any]) -> None:
thread = Thread(target=asyncio.run, args=(coro,))
thread.start()
thread.join()
...@@ -54,3 +54,6 @@ class AioHttpCommunicator(AbstractCommunicator): ...@@ -54,3 +54,6 @@ class AioHttpCommunicator(AbstractCommunicator):
def _send(self, url: HttpUrl, data: bytes, stopwatch: StopwatchResult) -> str: def _send(self, url: HttpUrl, data: bytes, stopwatch: StopwatchResult) -> str:
raise NotImplementedError raise NotImplementedError
def teardown(self) -> None:
self._asyncio_run(self.session.close())
...@@ -25,9 +25,9 @@ class HttpxCommunicator(AbstractCommunicator): ...@@ -25,9 +25,9 @@ class HttpxCommunicator(AbstractCommunicator):
self.__async_client: httpx.AsyncClient | None = None self.__async_client: httpx.AsyncClient | None = None
self.__sync_client: httpx.Client | None = None self.__sync_client: httpx.Client | None = None
async def close(self) -> None: def teardown(self) -> None:
if self.__async_client is not None: if self.__async_client is not None:
await self.__async_client.aclose() self._asyncio_run(self.__async_client.aclose())
self.__async_client = None self.__async_client = None
if self.__sync_client is not None: if self.__sync_client is not None:
......
...@@ -57,3 +57,6 @@ class RequestCommunicator(AbstractCommunicator): ...@@ -57,3 +57,6 @@ class RequestCommunicator(AbstractCommunicator):
if last_exception is None: if last_exception is None:
raise ValueError("Retry loop finished, but last_exception was not set") raise ValueError("Retry loop finished, but last_exception was not set")
raise last_exception raise last_exception
def teardown(self) -> None:
self.session.close()
...@@ -113,6 +113,9 @@ class AbstractHandle(UniqueSettingsHolder[Settings], ABC, Generic[ApiT]): ...@@ -113,6 +113,9 @@ class AbstractHandle(UniqueSettingsHolder[Settings], ABC, Generic[ApiT]):
def __configure_logger(self) -> Logger: def __configure_logger(self) -> Logger:
return logger.bind(**self._logger_extras()) return logger.bind(**self._logger_extras())
def teardown(self) -> None:
self._overseer.teardown()
class AbstractAsyncHandle(AbstractHandle[ApiT], ABC): class AbstractAsyncHandle(AbstractHandle[ApiT], ABC):
"""Base class for service handlers that uses asynchronous communication.""" """Base class for service handlers that uses asynchronous communication."""
......
...@@ -43,7 +43,7 @@ def test_invalid_wallet_names(beekeeper: Beekeeper, invalid_wallet_name: str) -> ...@@ -43,7 +43,7 @@ def test_invalid_wallet_names(beekeeper: Beekeeper, invalid_wallet_name: str) ->
def test_wallet_open(beekeeper: Beekeeper, wallet: WalletInfo) -> None: def test_wallet_open(beekeeper: Beekeeper, wallet: WalletInfo) -> None:
# ARRANGE # ARRANGE
beekeeper.close() beekeeper.teardown()
beekeeper.run() beekeeper.run()
# ACT & ASSERT # ACT & ASSERT
......
...@@ -29,7 +29,7 @@ def beekeeper_not_started(settings_with_logger: SettingsLoggerFactory) -> Iterat ...@@ -29,7 +29,7 @@ def beekeeper_not_started(settings_with_logger: SettingsLoggerFactory) -> Iterat
yield bk yield bk
if bk.is_running: if bk.is_running:
bk.close() bk.teardown()
@pytest.fixture() @pytest.fixture()
......
...@@ -30,7 +30,7 @@ def beekeeper_not_started(settings_with_logger: SettingsLoggerFactory) -> Iterat ...@@ -30,7 +30,7 @@ def beekeeper_not_started(settings_with_logger: SettingsLoggerFactory) -> Iterat
yield bk yield bk
if bk.is_running: if bk.is_running:
bk.close() bk.teardown()
@pytest.fixture() @pytest.fixture()
......
...@@ -3,6 +3,7 @@ from __future__ import annotations ...@@ -3,6 +3,7 @@ from __future__ import annotations
import re import re
import shutil import shutil
from pathlib import Path from pathlib import Path
from typing import AsyncIterator, Iterator
import pytest import pytest
...@@ -59,10 +60,12 @@ def hived_http_endpoint(request: pytest.FixtureRequest) -> helpy.HttpUrl: ...@@ -59,10 +60,12 @@ def hived_http_endpoint(request: pytest.FixtureRequest) -> helpy.HttpUrl:
@pytest.fixture() @pytest.fixture()
def sync_node(hived_http_endpoint: helpy.HttpUrl) -> helpy.Hived: def sync_node(hived_http_endpoint: helpy.HttpUrl) -> Iterator[helpy.Hived]:
return helpy.Hived(settings=helpy.Settings(http_endpoint=hived_http_endpoint)) with helpy.Hived(settings=helpy.Settings(http_endpoint=hived_http_endpoint)) as hived:
yield hived
@pytest.fixture() @pytest.fixture()
def async_node(hived_http_endpoint: helpy.HttpUrl) -> helpy.AsyncHived: async def async_node(hived_http_endpoint: helpy.HttpUrl) -> AsyncIterator[helpy.AsyncHived]:
return helpy.AsyncHived(settings=helpy.Settings(http_endpoint=hived_http_endpoint)) async with helpy.AsyncHived(settings=helpy.Settings(http_endpoint=hived_http_endpoint)) as hived:
yield hived
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment