Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions stubs/RouterOS-api/@tests/test_cases/check_resources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from __future__ import annotations

from datetime import timedelta
from typing import Any
from typing_extensions import assert_type

from routeros_api import RouterOsApiPool
from routeros_api.api_structure import BooleanField, IntegerField, StringField, TimedeltaField
from routeros_api.resource import RouterOsResource

api = RouterOsApiPool("192.0.2.1").get_api()

assert_type(api.get_resource("/ip/address"), RouterOsResource[str, str])

# A structure of one field type carries that type into the resource.
flags = api.get_resource("/interface", structure={"disabled": BooleanField(), "running": BooleanField()})
assert_type(flags, RouterOsResource[bool, bool])
assert_type(flags.get(disabled=True)[0]["running"], bool)

# None is sent without a value as an argument, refused as a query, and decoded from "none".
timeouts = api.get_resource("/ip/hotspot/user", structure={"limit-uptime": TimedeltaField()})
timeouts.set(**{"limit-uptime": None})
timeouts.get(**{"limit-uptime": None}) # type: ignore
assert_type(timeouts.get()[0]["limit-uptime"], timedelta | None)

# A structure mixing field types gives a resource whose values' types aren't tracked.
mixed = api.get_resource("/ip/address", structure={"disabled": BooleanField(), "comment": StringField(), "mtu": IntegerField()})
assert_type(mixed, RouterOsResource[Any, Any]) # Any: the stub's type for a mixed structure
6 changes: 6 additions & 0 deletions stubs/RouterOS-api/METADATA.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version = "0.21.*"
upstream-repository = "https://github.com/socialwifi/RouterOS-api"
partial-stub = true

[tool.stubtest]
ignore-missing-stub = true
8 changes: 8 additions & 0 deletions stubs/RouterOS-api/routeros_api/__init__.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from _typeshed import Incomplete

from routeros_api import api_structure as api_structure, query as query
from routeros_api.api import RouterOsApiPool as RouterOsApiPool, connect as connect

__all__ = ["connect", "RouterOsApiPool", "query", "api_structure"]

def __getattr__(name: str) -> Incomplete: ...
81 changes: 81 additions & 0 deletions stubs/RouterOS-api/routeros_api/api.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import ssl
from collections.abc import Mapping
from typing import Any, TypeVar, overload

from routeros_api.api_socket import DummySocket, SocketWrapper
from routeros_api.api_structure import _Field
from routeros_api.communication_exception_parsers import ExceptionHandler
from routeros_api.resource import RouterOsBinaryResource, RouterOsResource, _Communicator

_In = TypeVar("_In")
_Out = TypeVar("_Out")

def connect( # undocumented
host: str,
username: str | bytes = "admin",
password: str | bytes = "",
port: int | None = None,
plaintext_login: bool = False,
use_ssl: bool = False,
ssl_verify: bool = True,
ssl_verify_hostname: bool = True,
ssl_context: ssl.SSLContext | None = None,
) -> RouterOsApi: ...

class RouterOsApiPool:
socket_timeout: float | None # undocumented
host: str # undocumented
username: str | bytes # undocumented
password: str | bytes # undocumented
port: int # undocumented
plaintext_login: bool # undocumented
use_ssl: bool # undocumented
ssl_verify: bool # undocumented
ssl_verify_hostname: bool # undocumented
ssl_context: ssl.SSLContext | None # undocumented
connected: bool # undocumented
# A DummySocket while not connected.
socket: DummySocket | SocketWrapper # undocumented
communication_exception_parser: ExceptionHandler # undocumented
# Set by get_api, absent before its first call.
api: RouterOsApi # undocumented
def __init__(
self,
host: str,
username: str | bytes = "admin",
password: str | bytes = "",
port: int | None = None,
plaintext_login: bool = False,
use_ssl: bool = False,
ssl_verify: bool = True,
ssl_verify_hostname: bool = True,
ssl_context: ssl.SSLContext | None = None,
) -> None: ...
def get_api(self) -> RouterOsApi: ...
def disconnect(self) -> None: ...
def set_timeout(self, socket_timeout: float | None) -> None: ... # undocumented

class RouterOsApi:
communicator: _Communicator # undocumented
def __init__(self, communicator: _Communicator) -> None: ...
def login(self, login: str | bytes, password: str | bytes, plaintext_login: bool) -> None: ... # undocumented

# None selects the default structure, every field text.
@overload
def get_resource(self, path: str, structure: None = None) -> RouterOsResource[str, str]: ...
@overload
def get_resource(self, path: str, structure: Mapping[str, _Field[_In, _Out]]) -> RouterOsResource[_In, _Out]: ...
# A structure whose fields encode and decode different types: each key's type can't be expressed,
# so the resource's arguments and values go unchecked.
@overload
def get_resource(
self, path: str, structure: Mapping[str, _Field[Any, Any]] # Any: the type each key's field encodes and decodes
) -> RouterOsResource[Any, Any]: ... # Any: the type of each key's value

def get_binary_resource(self, path: str) -> RouterOsBinaryResource: ...

# Disconnects the pool on a connection or fatal error.
class CloseConnectionExceptionHandler: # undocumented
pool: RouterOsApiPool
def __init__(self, pool: RouterOsApiPool) -> None: ...
def handle(self, exception: BaseException) -> None: ...
3 changes: 3 additions & 0 deletions stubs/RouterOS-api/routeros_api/api_communicator/__init__.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from _typeshed import Incomplete

def __getattr__(name: str) -> Incomplete: ...
29 changes: 29 additions & 0 deletions stubs/RouterOS-api/routeros_api/api_communicator/base.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from _typeshed import Incomplete
from collections.abc import Callable, Iterable
from typing import TypeVar, overload

from routeros_api.exceptions import RouterOsApiCommunicationError
from routeros_api.sentence import CommandSentence

_T = TypeVar("_T")
_S = TypeVar("_S")

# A reply: the list of its rows, with the done message the router ends it with.
class AsynchronousResponse(list[_T]): # undocumented
# The command the reply answers.
command: CommandSentence
done_message: _T
done: bool
error: bytes | None

@overload
def __init__(self, *, command: CommandSentence) -> None: ...
@overload
def __init__(self, iterable: Iterable[_T], /, *, command: CommandSentence) -> None: ...

@property
def error_as_exception(self) -> RouterOsApiCommunicationError | None: ...
# Applied to each row and to the done message.
def map(self, function: Callable[[_T], _S]) -> AsynchronousResponse[_S]: ...

def __getattr__(name: str) -> Incomplete: ...
35 changes: 35 additions & 0 deletions stubs/RouterOS-api/routeros_api/api_socket.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import socket
import ssl
from _typeshed import ReadableBuffer
from typing import TypeAlias

# SocketWrapper's attribute socket hides the module in its class body.
_Socket: TypeAlias = socket.socket

EINTR: int # undocumented

def get_socket( # undocumented
hostname: str,
port: int,
use_ssl: bool = False,
ssl_verify: bool = True,
ssl_verify_hostname: bool = True,
ssl_context: ssl.SSLContext | None = None,
timeout: float | None = 15.0,
) -> SocketWrapper: ...
def set_keepalive( # undocumented
sock: socket.socket, after_idle_sec: int = 1, interval_sec: int = 3, max_fails: int = 5
) -> None: ...

# A pool's socket while it isn't connected.
class DummySocket: # undocumented
def close(self) -> None: ...
def settimeout(self, timeout: float | None) -> None: ...

class SocketWrapper: # undocumented
socket: _Socket
def __init__(self, socket: _Socket) -> None: ...
def send(self, bytes: ReadableBuffer) -> None: ...
def receive(self, length: int) -> bytes: ...
def close(self) -> None: ...
def settimeout(self, timeout: float | None) -> None: ...
67 changes: 67 additions & 0 deletions stubs/RouterOS-api/routeros_api/api_structure.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
from abc import ABCMeta, abstractmethod
from collections import defaultdict
from collections.abc import Iterable
from datetime import timedelta
from ipaddress import IPv4Network, IPv6Network
from typing import Generic, Protocol, TypeVar, type_check_only

_In = TypeVar("_In")
_Out = TypeVar("_Out")
_In_contra = TypeVar("_In_contra", contravariant=True)
_Out_co = TypeVar("_Out_co", covariant=True)

# What a resource's structure needs of a field: it encodes a value of an argument or a query, and
# decodes a value of a reply's row. A field need not derive from Field.
@type_check_only
class _Field(Protocol[_In_contra, _Out_co]):
def get_mikrotik_value(self, arg: _In_contra, /) -> bytes: ...
def get_python_value(self, bytes: bytes, /) -> _Out_co: ...

class Field(Generic[_In, _Out]): # undocumented
# Python 2's spelling of a metaclass: on Python 3 an ordinary attribute, the class's metaclass
# being type.
__metaclass__: type[ABCMeta]
@abstractmethod
def get_mikrotik_value(self, arg: _In) -> bytes: ...
@abstractmethod
def get_python_value(self, bytes: bytes) -> _Out: ...

class StringField(Field[str, str]):
encoding: str # undocumented
def __init__(self, encoding: str = "utf-8") -> None: ...
def get_mikrotik_value(self, string: str) -> bytes: ... # undocumented
def get_python_value(self, bytes: bytes) -> str: ... # undocumented

class BytesField(Field[bytes, bytes]): # undocumented
def get_mikrotik_value(self, bytes: bytes) -> bytes: ...
def get_python_value(self, bytes: bytes) -> bytes: ...

class BooleanField(Field[bool, bool]): # undocumented
def get_mikrotik_value(self, condition: bool) -> bytes: ...
def get_python_value(self, bytes: bytes) -> bool: ...

class IntegerField(Field[int, int]): # undocumented
def get_mikrotik_value(self, number: int) -> bytes: ...
def get_python_value(self, bytes: bytes) -> int: ...

# The field decodes the router's "none" as None. Through a resource a None argument is sent without a
# value and a None query raises TypeError, so the field takes no None, though get_mikrotik_value
# called directly encodes None as "none".
class TimedeltaField(Field[timedelta, timedelta | None]): # undocumented
def get_mikrotik_value(self, timedelta: timedelta) -> bytes: ...
def get_python_value(self, bytes: bytes) -> timedelta | None: ...
def parse_mikrotik_timedelta(self, time_string: str) -> timedelta: ...

# The field decodes empty as None. It takes no None for the reason TimedeltaField gives, though
# get_mikrotik_value called directly encodes None as empty.
class IpNetworkField(Field[IPv4Network | IPv6Network, IPv4Network | IPv6Network | None]): # undocumented
def get_mikrotik_value(self, ip_network: IPv4Network | IPv6Network) -> bytes: ...
def get_python_value(self, bytes: bytes) -> IPv4Network | IPv6Network | None: ...

class ListField(Field[Iterable[_In], list[_Out]]): # undocumented
subfield: _Field[_In, _Out]
def __init__(self, subfield: _Field[_In, _Out]) -> None: ...
def get_mikrotik_value(self, objects: Iterable[_In]) -> bytes: ...
def get_python_value(self, bytes: bytes) -> list[_Out]: ...

default_structure: defaultdict[str, StringField]
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import re
from collections.abc import Callable
from typing import TypeAlias

from routeros_api.exceptions import RouterOsApiCommunicationError

# What builds the exception raised in an error's place, from the error and its original message;
# each is paired with a pattern searched for in that message.
_ExceptionType: TypeAlias = Callable[[RouterOsApiCommunicationError, bytes], BaseException]

class ExceptionHandler: # undocumented
message_to_class_map: list[tuple[bytes | re.Pattern[bytes], _ExceptionType]]
def __init__(self) -> None: ...
def add_exception_type(self, message_re: bytes | re.Pattern[bytes], exception_class: _ExceptionType) -> None: ...
def handle(self, exception: BaseException) -> None: ...
12 changes: 12 additions & 0 deletions stubs/RouterOS-api/routeros_api/exceptions.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class RouterOsApiError(Exception): ... # undocumented
class RouterOsApiConnectionError(RouterOsApiError): ... # undocumented
class FatalRouterOsApiError(RouterOsApiError): ... # undocumented
class RouterOsApiParsingError(RouterOsApiError): ... # undocumented

class RouterOsApiCommunicationError(RouterOsApiError): # undocumented
original_message: bytes
# The message is text, or the exception a registered exception type replaces.
def __init__(self, message: object, original_message: bytes) -> None: ...

class RouterOsApiFatalCommunicationError(RouterOsApiError): ... # undocumented
class RouterOsApiConnectionClosedError(RouterOsApiConnectionError): ... # undocumented
42 changes: 42 additions & 0 deletions stubs/RouterOS-api/routeros_api/query.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from typing import ClassVar, Protocol, type_check_only

# A query a command filters its rows by.
@type_check_only
class _Query(Protocol):
def get_api_format(self) -> list[bytes]: ...

# A str key or value is encoded.
class BasicQuery: # undocumented
operator: ClassVar[bytes | None]
key: bytes
value: bytes
def __init__(self, key: str | bytes, value: str | bytes) -> None: ...
def get_api_format(self) -> list[bytes]: ...

class IsEqualQuery(BasicQuery): # undocumented
operator: ClassVar[bytes]

class IsLessQuery(BasicQuery): # undocumented
operator: ClassVar[bytes]

class IsGreaterQuery(BasicQuery): # undocumented
operator: ClassVar[bytes]

class HasValueQuery: # undocumented
key: bytes
def __init__(self, key: str | bytes) -> None: ...
def get_api_format(self) -> list[bytes]: ...

class OperatorQuery: # undocumented
operator: ClassVar[bytes | None]
others: tuple[_Query, ...]
def __init__(self, *others: _Query) -> None: ...
def get_api_format(self) -> list[bytes]: ...

class OrQuery(OperatorQuery): # undocumented
operator: ClassVar[bytes]

class AndQuery(OperatorQuery): # undocumented
operator: ClassVar[bytes]

class NandQuery(AndQuery): ... # undocumented
Loading
Loading