Skip to content

Commit

Permalink
chore: ruff formatting
Browse files Browse the repository at this point in the history
Signed-off-by: Colton Wolkins (Laptop) <[email protected]>
  • Loading branch information
TheTechmage committed Jan 3, 2025
1 parent ebefef9 commit f800a3e
Show file tree
Hide file tree
Showing 14 changed files with 225 additions and 140 deletions.
13 changes: 7 additions & 6 deletions acapy_agent/core/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,9 @@ async def handle_v2_message(
)
to_did = services[0].service_endpoint.uri
found_forwardable_service = (
await routing_service.is_forwardable_service(messaging.resolver, services[0])
await routing_service.is_forwardable_service(
messaging.resolver, services[0]
)
if services
else False
)
Expand All @@ -212,7 +214,7 @@ async def handle_v2_message(
send_outbound,
reply_session_id=inbound_message.session_id,
reply_to_verkey=inbound_message.receipt.sender_verkey,
target_list=reply_destination
target_list=reply_destination,
)

context.injector.bind_instance(BaseResponder, responder)
Expand Down Expand Up @@ -288,8 +290,8 @@ async def make_v2_message(self, profile: Profile, parsed_msg: dict) -> BaseMessa

registry: V2ProtocolRegistry = self.profile.inject(V2ProtocolRegistry)
try:
#message_cls = registry.resolve_message_class(message_type)
#if isinstance(message_cls, DeferLoad):
# message_cls = registry.resolve_message_class(message_type)
# if isinstance(message_cls, DeferLoad):
# message_cls = message_cls.resolved
message_cls = registry.protocols_matching_query(message_type)
except ProtocolMinorVersionNotSupported as e:
Expand All @@ -299,7 +301,7 @@ async def make_v2_message(self, profile: Profile, parsed_msg: dict) -> BaseMessa
raise MessageParseError(f"Unrecognized message type {message_type}")

try:
#instance = message_cls[0] #message_cls.deserialize(parsed_msg)
# instance = message_cls[0] #message_cls.deserialize(parsed_msg)
instance = registry.handlers[message_cls[0]]
if isinstance(instance, DeferLoad):
instance = instance.resolved
Expand All @@ -310,7 +312,6 @@ async def make_v2_message(self, profile: Profile, parsed_msg: dict) -> BaseMessa

return instance


async def handle_v1_message(
self,
profile: Profile,
Expand Down
4 changes: 1 addition & 3 deletions acapy_agent/core/plugin_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,9 +224,7 @@ async def load_protocol_version(
goal_code_registry = context.inject(GoalCodeRegistry)
if hasattr(mod, "HANDLERS"):
for message_type, handler in mod.HANDLERS:
v2_protocol_registry.register_handler(
message_type, handler
)
v2_protocol_registry.register_handler(message_type, handler)
if hasattr(mod, "MESSAGE_TYPES"):
protocol_registry.register_message_types(
mod.MESSAGE_TYPES, version_definition=version_definition
Expand Down
2 changes: 1 addition & 1 deletion acapy_agent/didcomm_v2/protocol_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ def protocols_matching_query(self, query: str) -> Sequence[str]:
def register_handler(self, message_type: str, handler: Union[Coroutine, str]):
"""Register a new message type to handler association."""
if isinstance(handler, str):
handler = DeferLoad(handler)
handler = DeferLoad(handler)
self._type_to_message_handler[message_type] = handler
12 changes: 6 additions & 6 deletions acapy_agent/protocols_v2/basicmessage/v1_0/message_types.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
"""Message type identifiers for Trust Pings."""

#from ...didcomm_prefix import DIDCommPrefix
# from ...didcomm_prefix import DIDCommPrefix
import logging
from ....messaging.v2_agent_message import V2AgentMessage
from ....connections.models.connection_target import ConnectionTarget
from didcomm_messaging import DIDCommMessaging, RoutingService

SPEC_URI = (
"https://didcomm.org/basicmessage/2.0/message"
)
SPEC_URI = "https://didcomm.org/basicmessage/2.0/message"

# Message types
BASIC_MESSAGE = "https://didcomm.org/basicmessage/2.0/message"

PROTOCOL_PACKAGE = "acapy_agent.protocols_v2.basicmessage.v1_0"


class basic_message:
async def __call__(self, *args, **kwargs):
await self.handle(*args, **kwargs)

@staticmethod
async def handle(context, responder, payload):
logger = logging.getLogger(__name__)
their_did = context.message_receipt.sender_verkey.split('#')[0]
our_did = context.message_receipt.recipient_verkey.split('#')[0]
their_did = context.message_receipt.sender_verkey.split("#")[0]
our_did = context.message_receipt.recipient_verkey.split("#")[0]
error_result = V2AgentMessage(
message={
"type": BASIC_MESSAGE,
Expand Down
42 changes: 30 additions & 12 deletions acapy_agent/protocols_v2/basicmessage/v1_0/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,25 @@ class PingConnIdMatchInfoSchema(OpenAPISchema):
metadata={"description": "Connection identifier", "example": UUID4_EXAMPLE},
)


from ....wallet.base import BaseWallet
from ....wallet.did_info import DIDInfo
from ....wallet.did_method import KEY, PEER2, PEER4, SOV, DIDMethod, DIDMethods, HolderDefinedDid
from ....wallet.did_method import (
KEY,
PEER2,
PEER4,
SOV,
DIDMethod,
DIDMethods,
HolderDefinedDid,
)
from ....wallet.did_posture import DIDPosture
from ....wallet.error import WalletError, WalletNotFoundError
from ....messaging.v2_agent_message import V2AgentMessage
from ....connections.models.connection_target import ConnectionTarget
from didcomm_messaging import DIDCommMessaging, RoutingService


def format_did_info(info: DIDInfo):
"""Serialize a DIDInfo object."""
if info:
Expand All @@ -71,19 +82,20 @@ def format_did_info(info: DIDInfo):
"metadata": info.metadata,
}


async def get_mydid(request: web.BaseRequest):
context: AdminRequestContext = request["context"]
#filter_did = request.query.get("did")
#filter_verkey = request.query.get("verkey")
# filter_did = request.query.get("did")
# filter_verkey = request.query.get("verkey")
filter_posture = DIDPosture.get(request.query.get("posture"))
results = []
async with context.session() as session:
did_methods: DIDMethods = session.inject(DIDMethods)
filter_method: DIDMethod | None = did_methods.from_method(
request.query.get("method") or "did:peer:2"
)
#key_types = session.inject(KeyTypes)
#filter_key_type = key_types.from_key_type(request.query.get("key_type", ""))
# key_types = session.inject(KeyTypes)
# filter_key_type = key_types.from_key_type(request.query.get("key_type", ""))
wallet: BaseWallet | None = session.inject_or(BaseWallet)
if not wallet:
raise web.HTTPForbidden(reason="No wallet available")
Expand All @@ -97,13 +109,14 @@ async def get_mydid(request: web.BaseRequest):
or DIDPosture.get(info.metadata) is DIDPosture.WALLET_ONLY
)
and (not filter_method or info.method == filter_method)
#and (not filter_key_type or info.key_type == filter_key_type)
# and (not filter_key_type or info.key_type == filter_key_type)
]

results.sort(key=lambda info: (DIDPosture.get(info["posture"]).ordinal, info["did"]))
our_did = results[0]["did"]
return our_did


async def get_target(request: web.BaseRequest, to_did: str, from_did: str):
context: AdminRequestContext = request["context"]

Expand Down Expand Up @@ -133,7 +146,9 @@ async def get_target(request: web.BaseRequest, to_did: str, from_did: str):
messaging.resolver, services[0]
)
while found_forwardable_service:
services = await routing_service._resolve_services(messaging.resolver, to_target)
services = await routing_service._resolve_services(
messaging.resolver, to_target
)
if services:
chain.append(
{
Expand All @@ -143,7 +158,9 @@ async def get_target(request: web.BaseRequest, to_did: str, from_did: str):
)
to_target = services[0].service_endpoint.uri
found_forwardable_service = (
await routing_service.is_forwardable_service(messaging.resolver, services[0])
await routing_service.is_forwardable_service(
messaging.resolver, services[0]
)
if services
else False
)
Expand Down Expand Up @@ -192,9 +209,7 @@ async def basic_message_send(request: web.BaseRequest):
msg = V2AgentMessage(
message={
"type": "https://didcomm.org/basicmessage/2.0/message",
"body": {
"content": message
},
"body": {"content": message},
"lang": "en",
"to": [their_did],
"from": our_did,
Expand Down Expand Up @@ -227,6 +242,9 @@ def post_process_routes(app: web.Application):
{
"name": "didcommv2",
"description": "DIDComm V2 based protocols for Interop-a-thon",
"externalDocs": {"description": "Specification", "url": "https://didcomm.org"},
"externalDocs": {
"description": "Specification",
"url": "https://didcomm.org",
},
}
)
42 changes: 25 additions & 17 deletions acapy_agent/protocols_v2/basicmessage/v1_0/tests/test_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,15 @@ async def test_connections_send_ping(self):
self.request.json = mock.CoroutineMock(return_value={"comment": "some comment"})
self.request.match_info = {"conn_id": "dummy"}

with mock.patch.object(
test_module.ConnRecord, "retrieve_by_id", mock.CoroutineMock()
) as mock_retrieve, mock.patch.object(
test_module, "Ping", mock.MagicMock()
) as mock_ping, mock.patch.object(
test_module.web, "json_response", mock.MagicMock()
) as json_response:
with (
mock.patch.object(
test_module.ConnRecord, "retrieve_by_id", mock.CoroutineMock()
) as mock_retrieve,
mock.patch.object(test_module, "Ping", mock.MagicMock()) as mock_ping,
mock.patch.object(
test_module.web, "json_response", mock.MagicMock()
) as json_response,
):
mock_ping.return_value = mock.MagicMock(_thread_id="dummy")
mock_retrieve.return_value = mock.MagicMock(is_ready=True)
result = await test_module.connections_send_ping(self.request)
Expand All @@ -49,11 +51,14 @@ async def test_connections_send_ping_no_conn(self):
self.request.json = mock.CoroutineMock(return_value={"comment": "some comment"})
self.request.match_info = {"conn_id": "dummy"}

with mock.patch.object(
test_module.ConnRecord, "retrieve_by_id", mock.CoroutineMock()
) as mock_retrieve, mock.patch.object(
test_module.web, "json_response", mock.MagicMock()
) as json_response:
with (
mock.patch.object(
test_module.ConnRecord, "retrieve_by_id", mock.CoroutineMock()
) as mock_retrieve,
mock.patch.object(
test_module.web, "json_response", mock.MagicMock()
) as json_response,
):
mock_retrieve.side_effect = test_module.StorageNotFoundError()
with self.assertRaises(test_module.web.HTTPNotFound):
await test_module.connections_send_ping(self.request)
Expand All @@ -62,11 +67,14 @@ async def test_connections_send_ping_not_ready(self):
self.request.json = mock.CoroutineMock(return_value={"comment": "some comment"})
self.request.match_info = {"conn_id": "dummy"}

with mock.patch.object(
test_module.ConnRecord, "retrieve_by_id", mock.CoroutineMock()
) as mock_retrieve, mock.patch.object(
test_module.web, "json_response", mock.MagicMock()
) as json_response:
with (
mock.patch.object(
test_module.ConnRecord, "retrieve_by_id", mock.CoroutineMock()
) as mock_retrieve,
mock.patch.object(
test_module.web, "json_response", mock.MagicMock()
) as json_response,
):
mock_retrieve.return_value = mock.MagicMock(is_ready=False)
with self.assertRaises(test_module.web.HTTPBadRequest):
await test_module.connections_send_ping(self.request)
Expand Down
13 changes: 6 additions & 7 deletions acapy_agent/protocols_v2/discovery/v1_0/message_types.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
"""Message type identifiers for Trust Pings."""

#from ...didcomm_prefix import DIDCommPrefix
# from ...didcomm_prefix import DIDCommPrefix
import logging
from ....messaging.v2_agent_message import V2AgentMessage
from ....connections.models.connection_target import ConnectionTarget
from didcomm_messaging import DIDCommMessaging, RoutingService

SPEC_URI = (
"https://didcomm.org/discover-features/2.0/queries"
)
SPEC_URI = "https://didcomm.org/discover-features/2.0/queries"

# Message types
QUERIES = "https://didcomm.org/discover-features/2.0/queries"
DISCLOSE = "https://didcomm.org/discover-features/2.0/disclose"

PROTOCOL_PACKAGE = "acapy_agent.protocols_v2.discovery.v1_0"


class discover_features:
async def __call__(self, *args, **kwargs):
await self.handle(*args, **kwargs)

@staticmethod
async def handle(context, responder, payload):
logger = logging.getLogger(__name__)
their_did = context.message_receipt.sender_verkey.split('#')[0]
our_did = context.message_receipt.recipient_verkey.split('#')[0]
their_did = context.message_receipt.sender_verkey.split("#")[0]
our_did = context.message_receipt.recipient_verkey.split("#")[0]
error_result = V2AgentMessage(
message={
"type": DISCLOSE,
Expand All @@ -44,7 +44,6 @@ async def handle(context, responder, payload):
await responder.send_reply(error_result)



HANDLERS = {
QUERIES: f"{PROTOCOL_PACKAGE}.message_types.discover_features",
}.items()
Expand Down
Loading

0 comments on commit f800a3e

Please sign in to comment.