Skip to content

Commit

Permalink
feat: context managers in ServiceBrowser and AsyncServiceBrowser (#1233)
Browse files Browse the repository at this point in the history
Co-authored-by: J. Nick Koston <nick@koston.org>
  • Loading branch information
Tenebrosus3141 and bdraco committed Aug 27, 2023
1 parent 041549c commit bd8d846
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 1 deletion.
14 changes: 14 additions & 0 deletions src/zeroconf/_services/browser.py
Expand Up @@ -26,6 +26,7 @@
import threading
import warnings
from abc import abstractmethod
from types import TracebackType # noqa # used in type hints
from typing import (
TYPE_CHECKING,
Callable,
Expand All @@ -35,6 +36,7 @@
Optional,
Set,
Tuple,
Type,
Union,
cast,
)
Expand Down Expand Up @@ -576,3 +578,15 @@ def async_update_records_complete(self) -> None:
for pending in self._pending_handlers.items():
self.queue.put(pending)
self._pending_handlers.clear()

def __enter__(self) -> 'ServiceBrowser':
return self

def __exit__( # pylint: disable=useless-return
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> Optional[bool]:
self.cancel()
return None
12 changes: 12 additions & 0 deletions src/zeroconf/asyncio.py
Expand Up @@ -93,6 +93,18 @@ def async_update_records_complete(self) -> None:
self._fire_service_state_changed_event(pending)
self._pending_handlers.clear()

async def __aenter__(self) -> 'AsyncServiceBrowser':
return self

async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> Optional[bool]:
await self.async_cancel()
return None


class AsyncZeroconfServiceTypes(ZeroconfServiceTypes):
"""An async version of ZeroconfServiceTypes."""
Expand Down
32 changes: 31 additions & 1 deletion tests/services/test_browser.py
Expand Up @@ -3,13 +3,14 @@

""" Unit tests for zeroconf._services.browser. """

import asyncio
import logging
import os
import socket
import time
import unittest
from threading import Event
from typing import Iterable, Set
from typing import Iterable, Set, cast
from unittest.mock import patch

import pytest
Expand Down Expand Up @@ -75,6 +76,35 @@ class MyServiceListener(r.ServiceListener):
zc.close()


def test_service_browser_cancel_context_manager():
"""Test we can cancel a ServiceBrowser with it being used as a context manager."""

# instantiate a zeroconf instance
zc = Zeroconf(interfaces=['127.0.0.1'])
# start a browser
type_ = "_hap._tcp.local."

class MyServiceListener(r.ServiceListener):
pass

listener = MyServiceListener()

browser = r.ServiceBrowser(zc, type_, None, listener)

assert cast(bool, browser.done) is False

with browser:
pass

# ensure call_soon_threadsafe in ServiceBrowser.cancel is run
assert zc.loop is not None
asyncio.run_coroutine_threadsafe(asyncio.sleep(0), zc.loop).result()

assert cast(bool, browser.done) is True

zc.close()


def test_service_browser_cancel_multiple_times_after_close():
"""Test we can cancel a ServiceBrowser multiple times after close."""

Expand Down
27 changes: 27 additions & 0 deletions tests/test_asyncio.py
Expand Up @@ -9,6 +9,7 @@
import socket
import threading
import time
from typing import cast
from unittest.mock import ANY, call, patch

import pytest
Expand Down Expand Up @@ -779,6 +780,32 @@ async def test_async_context_manager() -> None:
assert aiosinfo is not None


@pytest.mark.asyncio
async def test_service_browser_cancel_async_context_manager():
"""Test we can cancel an AsyncServiceBrowser with it being used as an async context manager."""

# instantiate a zeroconf instance
aiozc = AsyncZeroconf(interfaces=['127.0.0.1'])
zc = aiozc.zeroconf
type_ = "_hap._tcp.local."

class MyServiceListener(ServiceListener):
pass

listener = MyServiceListener()

browser = AsyncServiceBrowser(zc, type_, None, listener)

assert cast(bool, browser.done) is False

async with browser:
pass

assert cast(bool, browser.done) is True

await aiozc.async_close()


@pytest.mark.asyncio
async def test_async_unregister_all_services() -> None:
"""Test unregistering all services."""
Expand Down

0 comments on commit bd8d846

Please sign in to comment.