Skip to content

Commit

Permalink
increase maximum line length to 120
Browse files Browse the repository at this point in the history
  • Loading branch information
hh-h committed Oct 31, 2020
1 parent 424b4e4 commit 42e1a2e
Show file tree
Hide file tree
Showing 13 changed files with 57 additions and 131 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,9 @@ aiosnmp is developed and distributed under the MIT license.
pip install -r requirements-dev.txt
tox
```

## Before submitting PR
```shell
pip install -r requirements-dev.txt
tox -e format
```
8 changes: 2 additions & 6 deletions aiosnmp/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,11 @@ async def _connect(self) -> None:
lambda: SnmpProtocol(self.timeout, self.retries),
remote_addr=(self.host, self.port),
)
transport, protocol = await asyncio.wait_for(
connect_future, timeout=self.timeout
)
transport, protocol = await asyncio.wait_for(connect_future, timeout=self.timeout)

self._protocol = cast(SnmpProtocol, protocol)
self._transport = cast(asyncio.DatagramTransport, transport)
self._peername = self._transport.get_extra_info(
"peername", default=(self.host, self.port)
)
self._peername = self._transport.get_extra_info("peername", default=(self.host, self.port))

@property
def is_closed(self) -> bool:
Expand Down
28 changes: 6 additions & 22 deletions aiosnmp/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ def __init__(self, index: int, oid: Optional[str] = None) -> None:


class SnmpErrorTooBig(SnmpErrorStatus):
message = (
"The agent could not place the results "
"of the requested SNMP operation in a single SNMP message."
)
message = "The agent could not place the results " "of the requested SNMP operation in a single SNMP message."


class SnmpErrorNoSuchName(SnmpErrorStatus):
Expand All @@ -61,8 +58,7 @@ class SnmpErrorNoSuchName(SnmpErrorStatus):

class SnmpErrorBadValue(SnmpErrorStatus):
message = (
"The requested SNMP operation tried to change a variable "
"but it specified either a syntax or value error."
"The requested SNMP operation tried to change a variable " "but it specified either a syntax or value error."
)


Expand All @@ -75,28 +71,19 @@ class SnmpErrorReadOnly(SnmpErrorStatus):


class SnmpErrorGenErr(SnmpErrorStatus):
message = (
"An error other than one of those listed here "
"occurred during the requested SNMP operation."
)
message = "An error other than one of those listed here " "occurred during the requested SNMP operation."


class SnmpErrorNoAccess(SnmpErrorStatus):
message = "The specified SNMP variable is not accessible."


class SnmpErrorWrongType(SnmpErrorStatus):
message = (
"The value specifies a type that is inconsistent "
"with the type required for the variable."
)
message = "The value specifies a type that is inconsistent " "with the type required for the variable."


class SnmpErrorWrongLength(SnmpErrorStatus):
message = (
"The value specifies a length that is inconsistent "
"with the length required for the variable."
)
message = "The value specifies a length that is inconsistent " "with the length required for the variable."


class SnmpErrorWrongEncoding(SnmpErrorStatus):
Expand All @@ -119,10 +106,7 @@ class SnmpErrorInconsistentValue(SnmpErrorStatus):


class SnmpErrorResourceUnavailable(SnmpErrorStatus):
message = (
"Assigning the value to the variable requires allocation of resources "
"that are currently unavailable."
)
message = "Assigning the value to the variable requires allocation of resources " "that are currently unavailable."


class SnmpErrorCommitFailed(SnmpErrorStatus):
Expand Down
4 changes: 1 addition & 3 deletions aiosnmp/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,7 @@ class BulkPDU:

_PDUType: PDUType

def __init__(
self, varbinds: List[SnmpVarbind], non_repeaters: int, max_repetitions: int
) -> None:
def __init__(self, varbinds: List[SnmpVarbind], non_repeaters: int, max_repetitions: int) -> None:
self.request_id = random.randrange(1, 2_147_483_647)
self.non_repeaters: int = non_repeaters
self.max_repetitions: int = max_repetitions
Expand Down
20 changes: 5 additions & 15 deletions aiosnmp/protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,7 @@ def datagram_received(self, data: Union[bytes, Text], addr: Address) -> None:
logger.warning(f"could not decode received data from {host}:{port}: {exc}")
return

if not message or (
self.communities and message.community not in self.communities
):
if not message or (self.communities and message.community not in self.communities):
return
asyncio.ensure_future(self.handler(host, port, message))

Expand Down Expand Up @@ -114,9 +112,7 @@ def datagram_received(self, data: Union[bytes, Text], addr: Address) -> None:
oid = None
if len(message.data.varbinds) > 0 and index - 1 >= 0:
oid = message.data.varbinds[index - 1].oid
exception = _ERROR_STATUS_TO_EXCEPTION[message.data.error_status](
index, oid
)
exception = _ERROR_STATUS_TO_EXCEPTION[message.data.error_status](index, oid)
try:
if exception:
self.requests[key].set_exception(exception)
Expand All @@ -129,20 +125,14 @@ def datagram_received(self, data: Union[bytes, Text], addr: Address) -> None:
def is_connected(self) -> bool:
return bool(self.transport is not None and not self.transport.is_closing())

async def _send(
self, message: SnmpMessage, host: str, port: int
) -> List[SnmpVarbind]:
async def _send(self, message: SnmpMessage, host: str, port: int) -> List[SnmpVarbind]:
key = (host, port, message.data.request_id)
fut: asyncio.Future = self.loop.create_future()
fut.add_done_callback(
lambda fn: self.requests.pop(key) if key in self.requests else None
)
fut.add_done_callback(lambda fn: self.requests.pop(key) if key in self.requests else None)
self.requests[key] = fut
for _ in range(self.retries):
self.transport.sendto(message.encode())
done, _ = await asyncio.wait(
{fut}, timeout=self.timeout, return_when=asyncio.ALL_COMPLETED
)
done, _ = await asyncio.wait({fut}, timeout=self.timeout, return_when=asyncio.ALL_COMPLETED)
if not done:
continue
r: List[SnmpVarbind] = fut.result()
Expand Down
34 changes: 7 additions & 27 deletions aiosnmp/snmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,7 @@

from .connection import SnmpConnection
from .exceptions import SnmpUnsupportedValueType
from .message import (
GetBulkRequest,
GetNextRequest,
GetRequest,
SetRequest,
SnmpMessage,
SnmpVarbind,
SnmpVersion,
)
from .message import GetBulkRequest, GetNextRequest, GetRequest, SetRequest, SnmpMessage, SnmpVarbind, SnmpVersion


class Snmp(SnmpConnection):
Expand Down Expand Up @@ -77,9 +69,7 @@ async def _send(self, message: SnmpMessage) -> List[SnmpVarbind]:
async def get(self, oids: Union[str, List[str]]) -> List[SnmpVarbind]:
if isinstance(oids, str):
oids = [oids]
message = SnmpMessage(
self.version, self.community, GetRequest([SnmpVarbind(oid) for oid in oids])
)
message = SnmpMessage(self.version, self.community, GetRequest([SnmpVarbind(oid) for oid in oids]))
return await self._send(message)

async def get_next(self, oids: Union[str, List[str]]) -> List[SnmpVarbind]:
Expand Down Expand Up @@ -112,38 +102,28 @@ async def get_bulk(

async def walk(self, oid: str) -> List[SnmpVarbind]:
varbinds: List[SnmpVarbind] = []
message = SnmpMessage(
self.version, self.community, GetNextRequest([SnmpVarbind(oid)])
)
message = SnmpMessage(self.version, self.community, GetNextRequest([SnmpVarbind(oid)]))
base_oid = oid if oid.startswith(".") else f".{oid}"
vbs = await self._send(message)
next_oid = vbs[0].oid
if not next_oid.startswith(f"{base_oid}."):
message = SnmpMessage(
self.version, self.community, GetRequest([SnmpVarbind(base_oid)])
)
message = SnmpMessage(self.version, self.community, GetRequest([SnmpVarbind(base_oid)]))
return await self._send(message)

varbinds.append(vbs[0])
while True:
message = SnmpMessage(
self.version, self.community, GetNextRequest([SnmpVarbind(next_oid)])
)
message = SnmpMessage(self.version, self.community, GetNextRequest([SnmpVarbind(next_oid)]))
vbs = await self._send(message)
next_oid = vbs[0].oid
if not next_oid.startswith(f"{base_oid}."):
break
varbinds.append(vbs[0])
return varbinds

async def set(
self, varbinds: List[Tuple[str, Union[int, str, bytes, ipaddress.IPv4Address]]]
) -> List[SnmpVarbind]:
async def set(self, varbinds: List[Tuple[str, Union[int, str, bytes, ipaddress.IPv4Address]]]) -> List[SnmpVarbind]:
for varbind in varbinds:
if not isinstance(varbind[1], (int, str, bytes, ipaddress.IPv4Address)):
raise SnmpUnsupportedValueType(
f"Only int, str, bytes and ip address supported, got {type(varbind[1])}"
)
raise SnmpUnsupportedValueType(f"Only int, str, bytes and ip address supported, got {type(varbind[1])}")
message = SnmpMessage(
self.version,
self.community,
Expand Down
2 changes: 1 addition & 1 deletion azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ jobs:
- script: isort -q --check --diff aiosnmp tests examples
displayName: 'Run isort'

- script: black -q --check --diff aiosnmp tests examples
- script: black -l 120 -q --check --diff aiosnmp tests examples
displayName: 'Run black'

- script: mypy aiosnmp
Expand Down
4 changes: 1 addition & 3 deletions examples/trap.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ async def handler(host: str, port: int, message: aiosnmp.SnmpV2TrapMessage) -> N


async def main():
p = aiosnmp.SnmpV2TrapServer(
host="127.0.0.1", port=162, communities=("public",), handler=handler
)
p = aiosnmp.SnmpV2TrapServer(host="127.0.0.1", port=162, communities=("public",), handler=handler)
await p.run()


Expand Down
4 changes: 2 additions & 2 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ test = pytest

[flake8]
ignore = E203, E266, E501, W503
max-line-length = 88
max-line-length = 120
max-complexity = 18
select = B,C,E,F,W,T4,B9

[isort]
line_length = 88
line_length = 120
multi_line_output = 3
include_trailing_comma = true
known_first_party = aiosnmp
Expand Down
8 changes: 2 additions & 6 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@


def pytest_addoption(parser):
parser.addoption(
"--event-loop", action="store", default="asyncio", choices=["asyncio", "uvloop"]
)
parser.addoption("--event-loop", action="store", default="asyncio", choices=["asyncio", "uvloop"])


def pytest_configure(config):
Expand All @@ -28,6 +26,4 @@ def pytest_generate_tests(metafunc):
if "host" in metafunc.fixturenames:
metafunc.parametrize("host", ["127.0.0.1", "localhost", "::1"])
if "port" in metafunc.fixturenames:
metafunc.parametrize(
"port", [int(os.environ.get("KOSHH/AIOSNMP_161_UDP", 161))]
)
metafunc.parametrize("port", [int(os.environ.get("KOSHH/AIOSNMP_161_UDP", 161))])
22 changes: 5 additions & 17 deletions tests/test_asn1.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,7 @@ def test_long_integer(self) -> None:
enc = asn1.Encoder()
enc.write(0x0102030405060708090A0B0C0D0E0F)
res = enc.output()
assert (
res
== b"\x02\x0f\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
)
assert res == b"\x02\x0f\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"

def test_negative_integer(self) -> None:
enc = asn1.Encoder()
Expand All @@ -44,10 +41,7 @@ def test_long_negative_integer(self) -> None:
enc = asn1.Encoder()
enc.write(-0x0102030405060708090A0B0C0D0E0F)
res = enc.output()
assert (
res
== b"\x02\x0f\xfe\xfd\xfc\xfb\xfa\xf9\xf8\xf7\xf6\xf5\xf4\xf3\xf2\xf1\xf1"
)
assert res == b"\x02\x0f\xfe\xfd\xfc\xfb\xfa\xf9\xf8\xf7\xf6\xf5\xf4\xf3\xf2\xf1\xf1"

@pytest.mark.parametrize(
("number", "result"),
Expand Down Expand Up @@ -209,9 +203,7 @@ def test_error_stack(self) -> None:
with pytest.raises(asn1.Error):
enc.output()

@pytest.mark.parametrize(
"value", ["1", "40.2.3", "1.40.3", "1.2.3.", ".1.2.3", "foo", "foo.bar"]
)
@pytest.mark.parametrize("value", ["1", "40.2.3", "1.40.3", "1.2.3.", ".1.2.3", "foo", "foo.bar"])
def test_error_object_identifier(self, value) -> None:
enc = asn1.Encoder()
with pytest.raises(asn1.Error):
Expand All @@ -231,9 +223,7 @@ def test_boolean(self, buf: bytes, result: int) -> None:
assert isinstance(val, int)
assert val == result

@pytest.mark.parametrize(
("buf", "result"), ((b"\x02\x01\x01", 1), (b"\x02\x04\xff\xff\xff\xff", -1))
)
@pytest.mark.parametrize(("buf", "result"), ((b"\x02\x01\x01", 1), (b"\x02\x04\xff\xff\xff\xff", -1)))
def test_integer(self, buf: bytes, result: int) -> None:
dec = asn1.Decoder(buf)
tag = dec.peek()
Expand Down Expand Up @@ -591,9 +581,7 @@ def test_error_object_identifier_with_too_large_first_component(self) -> None:
dec.read()

def test_big_negative_integer(self) -> None:
buf = (
b"\x02\x10\xff\x7f\x2b\x3a\x4d\xea\x48\x1e\x1f\x37\x7b\xa8\xbd\x7f\xb0\x16"
)
buf = b"\x02\x10\xff\x7f\x2b\x3a\x4d\xea\x48\x1e\x1f\x37\x7b\xa8\xbd\x7f\xb0\x16"
dec = asn1.Decoder(buf)
tag, val = dec.read()
assert val == -668929531791034950848739021124816874
Expand Down
Loading

0 comments on commit 42e1a2e

Please sign in to comment.