Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixes #151, add custom solana-py RPC error handling #152

Merged
merged 2 commits into from
Dec 21, 2021
Merged
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
54 changes: 54 additions & 0 deletions src/solana/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""Exceptions native to solana-py."""
from typing import Callable, Any


class SolanaExceptionBase(Exception):
"""Base class for Solana-py exceptions."""

def __init__(self, exc: Exception, func: Callable[[Any], Any], *args: Any, **kwargs: Any) -> None:
"""Init."""
super().__init__()
self.error_msg = self._build_error_message(exc, func, *args, **kwargs)

@staticmethod
def _build_error_message(exc: Exception, func: Callable[[Any], Any], *args: Any, **kwargs: Any) -> str:
return f"{type(exc)} raised in {func} invokation"


class SolanaRpcException(SolanaExceptionBase):
"""Class for Solana-py RPC exceptions."""

@staticmethod
def _build_error_message(exc: Exception, func: Callable[[Any], Any], *args: Any, **kwargs: Any) -> str:
rpc_method = args[1]
return f'{type(exc)} raised in "{rpc_method}" endpoint request'


def handle_exceptions(internal_exception_cls, *exception_types_caught):
"""Decorator for handling non-async exception."""

def func_decorator(func):
def argument_decorator(*args, **kwargs):
try:
return func(*args, **kwargs)
except exception_types_caught as exc:
raise internal_exception_cls(exc, func, *args, **kwargs)

return argument_decorator

return func_decorator


def handle_async_exceptions(internal_exception_cls, *exception_types_caught):
"""Decorator for handling async exception."""

def func_decorator(func):
async def argument_decorator(*args, **kwargs):
try:
return await func(*args, **kwargs)
except exception_types_caught as exc:
raise internal_exception_cls(exc, func, *args, **kwargs)

return argument_decorator

return func_decorator
2 changes: 2 additions & 0 deletions src/solana/rpc/providers/async_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from ..types import RPCMethod, RPCResponse
from .async_base import AsyncBaseProvider
from .core import _HTTPProviderCore, DEFAULT_TIMEOUT
from ...exceptions import handle_async_exceptions, SolanaRpcException


class AsyncHTTPProvider(AsyncBaseProvider, _HTTPProviderCore):
Expand All @@ -20,6 +21,7 @@ def __str__(self) -> str:
"""String definition for HTTPProvider."""
return f"Async HTTP RPC connection {self.endpoint_uri}"

@handle_async_exceptions(SolanaRpcException, Exception)
async def make_request(self, method: RPCMethod, *params: Any) -> RPCResponse:
"""Make an async HTTP request to an http rpc endpoint."""
request_kwargs = self._before_request(method=method, params=params, is_async=True)
Expand Down
2 changes: 2 additions & 0 deletions src/solana/rpc/providers/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from ..types import RPCMethod, RPCResponse
from .base import BaseProvider
from .core import _HTTPProviderCore
from ...exceptions import handle_exceptions, SolanaRpcException


class HTTPProvider(BaseProvider, _HTTPProviderCore):
Expand All @@ -15,6 +16,7 @@ def __str__(self) -> str:
"""String definition for HTTPProvider."""
return f"HTTP RPC connection {self.endpoint_uri}"

@handle_exceptions(SolanaRpcException, requests.exceptions.RequestException)
def make_request(self, method: RPCMethod, *params: Any) -> RPCResponse:
"""Make an HTTP request to an http rpc endpoint."""
request_kwargs = self._before_request(method=method, params=params, is_async=False)
Expand Down
14 changes: 14 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,20 @@ def freeze_authority() -> Keypair:
return Keypair.from_seed(bytes([6] * PublicKey.LENGTH))


@pytest.fixture(scope="session")
def unit_test_http_client() -> Client:
"""Client to be used in unit tests."""
client = Client(commitment=Processed)
return client


@pytest.fixture(scope="session")
def unit_test_http_client_async() -> AsyncClient:
"""Async client to be used in unit tests."""
client = AsyncClient(commitment=Processed)
return client


michaelhly marked this conversation as resolved.
Show resolved Hide resolved
@pytest.mark.integration
@pytest.fixture(scope="session")
def test_http_client(docker_services) -> Client:
Expand Down
21 changes: 21 additions & 0 deletions tests/unit/test_async_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from unittest.mock import patch
from requests.exceptions import ReadTimeout

import pytest

from solana.exceptions import SolanaRpcException


@pytest.mark.asyncio
async def test_async_client_http_exception(unit_test_http_client_async):
"""Test AsyncClient raises native Solana-py exceptions."""

with patch("httpx.AsyncClient.post") as post_mock:
post_mock.side_effect = ReadTimeout()
with pytest.raises(SolanaRpcException) as exc_info:
await unit_test_http_client_async.get_epoch_info()
assert exc_info.type == SolanaRpcException
assert (
exc_info.value.error_msg
== "<class 'requests.exceptions.ReadTimeout'> raised in \"getEpochInfo\" endpoint request"
)
19 changes: 19 additions & 0 deletions tests/unit/test_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from unittest.mock import patch
from requests.exceptions import ReadTimeout
import pytest

from solana.exceptions import SolanaRpcException


def test_client_http_exception(unit_test_http_client):
"""Test AsyncClient raises native Solana-py exceptions."""

with patch("requests.post") as post_mock:
post_mock.side_effect = ReadTimeout()
with pytest.raises(SolanaRpcException) as exc_info:
unit_test_http_client.get_epoch_info()
assert exc_info.type == SolanaRpcException
assert (
exc_info.value.error_msg
== "<class 'requests.exceptions.ReadTimeout'> raised in \"getEpochInfo\" endpoint request"
)