Skip to content

Commit

Permalink
Merge pull request #68 from 2Fake/fix_tasks
Browse files Browse the repository at this point in the history
Fix pending tasks on disconnect
  • Loading branch information
2Fake committed Nov 24, 2021
2 parents 0f8d866 + 51c4d78 commit 813ba34
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
9 changes: 7 additions & 2 deletions devolo_plc_api/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@ async def async_connect(self, session_instance: httpx.AsyncClient | None = None)
def connect(self) -> None:
""" Connect to a device synchronous. """
self._loop = asyncio.new_event_loop()
asyncio.gather(self.async_connect())
asyncio.set_event_loop(self._loop)
self._loop.run_until_complete(asyncio.ensure_future(self.async_connect()))

async def async_disconnect(self) -> None:
""" Disconnect from a device asynchronous. """
Expand All @@ -134,7 +135,11 @@ async def async_disconnect(self) -> None:

def disconnect(self) -> None:
""" Disconnect from a device synchronous. """
asyncio.gather(self.async_disconnect())
self._loop.run_until_complete(asyncio.ensure_future(self.async_disconnect()))
to_cancel = asyncio.tasks.all_tasks(self._loop)
for task in to_cancel:
task.cancel()
self._loop.run_until_complete(asyncio.tasks.gather(*to_cancel, return_exceptions=True))
self._loop.close()

async def _get_device_info(self) -> None:
Expand Down
6 changes: 6 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

### [v0.6.4] - 2021/11/24

### Fixed

- Running tasks get cleanly canceled on disconnect

### [v0.6.3] - 2021/11/18

### Fixed
Expand Down
4 changes: 2 additions & 2 deletions tests/fixtures/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@

@pytest.fixture()
def mock_device(request: pytest.FixtureRequest, event_loop: AbstractEventLoop) -> Generator[Device, None, None]:
selector = "_WindowsSelectorEventLoop" if platform == "win32" else "_UnixSelectorEventLoop"
with patch(f"devolo_plc_api.device.asyncio.unix_events.{selector}.close"):
selector = "windows_events._WindowsSelectorEventLoop" if platform == "win32" else "unix_events._UnixSelectorEventLoop"
with patch(f"devolo_plc_api.device.asyncio.{selector}.close"):
device = Device(ip=request.cls.ip)
device._info = deepcopy(request.cls.device_info)
device._loop = event_loop
Expand Down

0 comments on commit 813ba34

Please sign in to comment.