Skip to content

Commit

Permalink
Format existing files according to yapf
Browse files Browse the repository at this point in the history
  • Loading branch information
Shutgun committed Nov 27, 2020
1 parent 02b0217 commit 9b57bbd
Show file tree
Hide file tree
Showing 11 changed files with 38 additions and 44 deletions.
11 changes: 4 additions & 7 deletions devolo_plc_api/clients/protobuf.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@ def __init__(self):

def __getattr__(self, attr: str) -> Callable:
""" Catch attempts to call methods synchronously. """

def method(*args, **kwargs):
return self._loop.run_until_complete(getattr(self, async_method)(*args, **kwargs))

async_method = f"async_{attr}"
if hasattr(self.__class__, async_method):
return method
Expand All @@ -48,9 +50,7 @@ async def _async_get(self, sub_url: str, timeout: float = TIMEOUT) -> Response:
url = f"{self.url}{sub_url}"
self._logger.debug("Getting from %s", url)
try:
return await self._session.get(url,
auth=DigestAuth(self._user, self._password),
timeout=timeout)
return await self._session.get(url, auth=DigestAuth(self._user, self._password), timeout=timeout)
except TypeError:
raise DevicePasswordProtected("The used password is wrong.") from None

Expand All @@ -59,10 +59,7 @@ async def _async_post(self, sub_url: str, content: bytes, timeout: float = TIMEO
url = f"{self.url}{sub_url}"
self._logger.debug("Posting to %s", url)
try:
return await self._session.post(url,
auth=DigestAuth(self._user, self._password),
content=content,
timeout=timeout)
return await self._session.post(url, auth=DigestAuth(self._user, self._password), content=content, timeout=timeout)
except TypeError:
raise DevicePasswordProtected("The used password is wrong.") from None

Expand Down
14 changes: 6 additions & 8 deletions devolo_plc_api/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ def __init__(self, ip: str, password: Optional[str] = None, zeroconf_instance: O
self.device = None
self.plcnet = None

self._info: Dict = {"_dvl-plcnetapi._tcp.local.": {}, "_dvl-deviceapi._tcp.local.": {}}
self._info: Dict = {
"_dvl-plcnetapi._tcp.local.": {},
"_dvl-deviceapi._tcp.local.": {},
}
self._logger = logging.getLogger(self.__class__.__name__)
self._zeroconf_instance = zeroconf_instance

Expand Down Expand Up @@ -77,10 +80,7 @@ async def _get_device_info(self):
self.mt_number = self._info[service_type].get("MT", 0)
self.product = self._info[service_type].get("Product", "")

self.device = DeviceApi(ip=self.ip,
session=self._session,
info=self._info[service_type],
password=self.password)
self.device = DeviceApi(ip=self.ip, session=self._session, info=self._info[service_type], password=self.password)

async def _get_plcnet_info(self):
""" Get information from the devolo PlcNet API. """
Expand All @@ -93,9 +93,7 @@ async def _get_plcnet_info(self):
self.mac = self._info[service_type]['PlcMacAddress']
self.technology = self._info[service_type].get("PlcTechnology", "")

self.plcnet = PlcNetApi(ip=self.ip,
session=self._session,
info=self._info[service_type])
self.plcnet = PlcNetApi(ip=self.ip, session=self._session, info=self._info[service_type])

async def _get_zeroconf_info(self, service_type: str):
""" Browse for the desired mDNS service types and query them. """
Expand Down
10 changes: 5 additions & 5 deletions devolo_plc_api/device_api/deviceapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,7 @@ class DeviceApi(Protobuf):
:param password: Password of the device
"""

def __init__(self,
ip: str,
session: AsyncClient,
info: Dict,
password: Optional[str]):
def __init__(self, ip: str, session: AsyncClient, info: Dict, password: Optional[str]):
super().__init__()
self._ip = ip
self._port = info['Port']
Expand All @@ -38,13 +34,17 @@ def __init__(self,

def _feature(feature: str): # type: ignore # pylint: disable=no-self-argument
""" Decorator to filter unsupported features before querying the device. """

def feature_decorator(method: Callable):

def wrapper(self, *args, **kwargs):
if feature in self.features:
return method(self, *args, **kwargs)
else:
raise FeatureNotSupported(f"The device does not support {method}.")

return wrapper

return feature_decorator

@_feature("led")
Expand Down
5 changes: 1 addition & 4 deletions devolo_plc_api/plcnet_api/plcnetapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ class PlcNetApi(Protobuf):
:param info: Information collected from the mDNS query
"""

def __init__(self,
ip: str,
session: AsyncClient,
info: Dict):
def __init__(self, ip: str, session: AsyncClient, info: Dict):
super().__init__()
self._ip = ip
self._mac = info['PlcMacAddress']
Expand Down
13 changes: 6 additions & 7 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@

import pytest


pytest_plugins = ['tests.fixtures.device',
'tests.fixtures.device_api',
'tests.fixtures.plcnet_api',
'tests.fixtures.protobuf',
]

pytest_plugins = [
'tests.fixtures.device',
'tests.fixtures.device_api',
'tests.fixtures.plcnet_api',
'tests.fixtures.protobuf',
]

file = pathlib.Path(__file__).parent / "test_data.json"
with file.open("r") as fh:
Expand Down
8 changes: 3 additions & 5 deletions tests/fixtures/device_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
from unittest.mock import patch

import pytest
from devolo_plc_api.device_api.deviceapi import DeviceApi
from httpx import AsyncClient, Response

from devolo_plc_api.device_api.deviceapi import DeviceApi

try:
from unittest.mock import AsyncMock
except ImportError:
Expand All @@ -18,10 +19,7 @@ def device_api(request, feature):
patch("asyncio.get_running_loop", asyncio.new_event_loop):
asyncio.new_event_loop()
request.cls.device_info["_dvl-deviceapi._tcp.local."]["Features"] = feature
yield DeviceApi(request.cls.ip,
AsyncClient(),
request.cls.device_info["_dvl-deviceapi._tcp.local."],
"password")
yield DeviceApi(request.cls.ip, AsyncClient(), request.cls.device_info["_dvl-deviceapi._tcp.local."], "password")


@pytest.fixture()
Expand Down
7 changes: 3 additions & 4 deletions tests/fixtures/plcnet_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
from unittest.mock import patch

import pytest
from devolo_plc_api.plcnet_api.plcnetapi import PlcNetApi
from httpx import AsyncClient, Response

from devolo_plc_api.plcnet_api.plcnetapi import PlcNetApi

try:
from unittest.mock import AsyncMock
except ImportError:
Expand All @@ -17,9 +18,7 @@ def plcnet_api(request):
patch("devolo_plc_api.clients.protobuf.Protobuf._async_post", new=AsyncMock(return_value=Response)), \
patch("asyncio.get_running_loop", asyncio.new_event_loop):
asyncio.new_event_loop()
yield PlcNetApi(request.cls.ip,
AsyncClient(),
request.cls.device_info["_dvl-plcnetapi._tcp.local."])
yield PlcNetApi(request.cls.ip, AsyncClient(), request.cls.device_info["_dvl-plcnetapi._tcp.local."])


@pytest.fixture()
Expand Down
1 change: 1 addition & 0 deletions tests/mocks/mock_zeroconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@


class Zeroconf:

def get_service_info(self, service_type, name):
service_info = ServiceInfo(service_type, name)
service_info.addresses = [socket.inet_aton(test_data['ip'])]
Expand Down
1 change: 1 addition & 0 deletions tests/stubs/protobuf.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@


class StubProtobuf(Protobuf):

def __init__(self):
self._logger = logging.getLogger("ProtobufMock")
self._loop = asyncio.new_event_loop()
Expand Down
11 changes: 7 additions & 4 deletions tests/test_deviceapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@
from asynctest import CoroutineMock as AsyncMock

from devolo_plc_api.device_api.devolo_idl_proto_deviceapi_ledsettings_pb2 import LedSettingsGet, LedSettingsSetResponse
from devolo_plc_api.device_api.devolo_idl_proto_deviceapi_wifinetwork_pb2 import (
WifiConnectedStationsGet, WifiGuestAccessGet, WifiGuestAccessSetResponse, WifiNeighborAPsGet, WifiRepeatedAPsGet,
WifiWpsPbcStart)
from devolo_plc_api.exceptions.feature import FeatureNotSupported
from devolo_plc_api.device_api.devolo_idl_proto_deviceapi_updatefirmware_pb2 import UpdateFirmwareCheck, UpdateFirmwareStart
from devolo_plc_api.device_api.devolo_idl_proto_deviceapi_wifinetwork_pb2 import (WifiConnectedStationsGet,
WifiGuestAccessGet,
WifiGuestAccessSetResponse,
WifiNeighborAPsGet,
WifiRepeatedAPsGet,
WifiWpsPbcStart)
from devolo_plc_api.exceptions.feature import FeatureNotSupported


class TestDeviceApi:
Expand Down
1 change: 1 addition & 0 deletions tests/test_profobuf.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@


class TestProtobuf:

def test_attribute_error(self, mock_protobuf):
with pytest.raises(AttributeError):
mock_protobuf.test()
Expand Down

0 comments on commit 9b57bbd

Please sign in to comment.