diff --git a/.gitignore b/.gitignore index e5497e6d6c..903fdde8a6 100644 --- a/.gitignore +++ b/.gitignore @@ -189,4 +189,4 @@ _build/ **/*.iml # Open API build -open-api/.build \ No newline at end of file +open-api/.build diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5b48d76c8a..744ce5406b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -12,8 +12,10 @@ repos: hooks: - id: black stages: [commit] - - repo: https://github.com/pycqa/flake8.git - rev: 4.0.1 + - repo: https://github.com/astral-sh/ruff-pre-commit + # Ruff version. + rev: v0.0.285 hooks: - - id: flake8 + - id: ruff stages: [commit] + args: [--fix, --exit-non-zero-on-fix] diff --git a/aries_cloudagent/admin/base_server.py b/aries_cloudagent/admin/base_server.py index a05b238017..2222af3702 100644 --- a/aries_cloudagent/admin/base_server.py +++ b/aries_cloudagent/admin/base_server.py @@ -9,8 +9,7 @@ class BaseAdminServer(ABC): @abstractmethod async def start(self) -> None: - """ - Start the webserver. + """Start the webserver. Raises: AdminSetupError: If there was an error starting the webserver diff --git a/aries_cloudagent/admin/request_context.py b/aries_cloudagent/admin/request_context.py index c7a64a11b0..159334c685 100644 --- a/aries_cloudagent/admin/request_context.py +++ b/aries_cloudagent/admin/request_context.py @@ -1,5 +1,4 @@ -""" -Admin request context class. +"""Admin request context class. A request context provided by the admin server to admin route handlers. """ @@ -63,8 +62,7 @@ def session(self) -> ProfileSession: return self.profile.session(self._context) def transaction(self) -> ProfileSession: - """ - Start a new interactive session with commit and rollback support. + """Start a new interactive session with commit and rollback support. If the current backend does not support transactions, then commit and rollback operations of the session will not have any effect. @@ -76,8 +74,7 @@ def inject( base_cls: Type[InjectType], settings: Mapping[str, object] = None, ) -> InjectType: - """ - Get the provided instance of a given class identifier. + """Get the provided instance of a given class identifier. Args: cls: The base class to retrieve an instance of @@ -95,8 +92,7 @@ def inject_or( settings: Mapping[str, object] = None, default: Optional[InjectType] = None, ) -> Optional[InjectType]: - """ - Get the provided instance of a given class identifier or default if not found. + """Get the provided instance of a given class identifier or default if not found. Args: base_cls: The base class to retrieve an instance of @@ -119,9 +115,7 @@ def test_context( ) -> "AdminRequestContext": """Quickly set up a new admin request context for tests.""" ctx = AdminRequestContext(profile or IN_MEM.resolved.test_profile()) - setattr( - ctx, "session_inject", dict() if session_inject is None else session_inject - ) + setattr(ctx, "session_inject", {} if session_inject is None else session_inject) setattr(ctx, "session", ctx._test_session) return ctx @@ -151,8 +145,7 @@ def _inject_or(base_cls, default=None): return session def __repr__(self) -> str: - """ - Provide a human readable representation of this object. + """Provide a human readable representation of this object. Returns: A human readable representation of this object diff --git a/aries_cloudagent/admin/server.py b/aries_cloudagent/admin/server.py index 23db651566..61b3b61630 100644 --- a/aries_cloudagent/admin/server.py +++ b/aries_cloudagent/admin/server.py @@ -117,8 +117,7 @@ def __init__( send: Coroutine, **kwargs, ): - """ - Initialize an instance of `AdminResponder`. + """Initialize an instance of `AdminResponder`. Args: send: Function to send outbound message @@ -135,8 +134,7 @@ def __init__( async def send_outbound( self, message: OutboundMessage, **kwargs ) -> OutboundSendStatus: - """ - Send outbound message. + """Send outbound message. Args: message: The `OutboundMessage` to be sent @@ -147,8 +145,7 @@ async def send_outbound( return await self._send(profile, message) async def send_webhook(self, topic: str, payload: dict): - """ - Dispatch a webhook. DEPRECATED: use the event bus instead. + """Dispatch a webhook. DEPRECATED: use the event bus instead. Args: topic: the webhook topic identifier @@ -240,8 +237,7 @@ def __init__( task_queue: TaskQueue = None, conductor_stats: Coroutine = None, ): - """ - Initialize an AdminServer instance. + """Initialize an AdminServer instance. Args: host: Host to listen on @@ -510,8 +506,7 @@ async def setup_context(request: web.Request, handler): return app async def start(self) -> None: - """ - Start the webserver. + """Start the webserver. Raises: AdminSetupError: If there was an error starting the webserver @@ -523,7 +518,7 @@ def sort_dict(raw: dict) -> dict: for k, v in raw.items(): if isinstance(v, dict): raw[k] = sort_dict(v) - return dict(sorted([item for item in raw.items()], key=lambda x: x[0])) + return dict(sorted(raw.items(), key=lambda x: x[0])) self.app = await self.make_application() runner = web.AppRunner(self.app) @@ -560,7 +555,7 @@ def sort_dict(raw: dict) -> dict: method_spec["parameters"].sort( key=lambda p: (p["in"], not p["required"], p["name"]) ) - for path in sorted([p for p in swagger_dict["paths"]]): + for path in sorted(swagger_dict["paths"]): swagger_dict["paths"][path] = swagger_dict["paths"].pop(path) # order definitions alphabetically by dict key @@ -622,8 +617,7 @@ async def on_startup(self, app: web.Application): @docs(tags=["server"], summary="Fetch the list of loaded plugins") @response_schema(AdminModulesSchema(), 200, description="") async def plugins_handler(self, request: web.BaseRequest): - """ - Request handler for the loaded plugins list. + """Request handler for the loaded plugins list. Args: request: aiohttp request object @@ -639,8 +633,7 @@ async def plugins_handler(self, request: web.BaseRequest): @docs(tags=["server"], summary="Fetch the server configuration") @response_schema(AdminConfigSchema(), 200, description="") async def config_handler(self, request: web.BaseRequest): - """ - Request handler for the server configuration. + """Request handler for the server configuration. Args: request: aiohttp request object @@ -678,8 +671,7 @@ async def config_handler(self, request: web.BaseRequest): @docs(tags=["server"], summary="Fetch the server status") @response_schema(AdminStatusSchema(), 200, description="") async def status_handler(self, request: web.BaseRequest): - """ - Request handler for the server status information. + """Request handler for the server status information. Args: request: aiohttp request object @@ -700,8 +692,7 @@ async def status_handler(self, request: web.BaseRequest): @docs(tags=["server"], summary="Reset statistics") @response_schema(AdminResetSchema(), 200, description="") async def status_reset_handler(self, request: web.BaseRequest): - """ - Request handler for resetting the timing statistics. + """Request handler for resetting the timing statistics. Args: request: aiohttp request object @@ -722,8 +713,7 @@ async def redirect_handler(self, request: web.BaseRequest): @docs(tags=["server"], summary="Liveliness check") @response_schema(AdminStatusLivelinessSchema(), 200, description="") async def liveliness_handler(self, request: web.BaseRequest): - """ - Request handler for liveliness check. + """Request handler for liveliness check. Args: request: aiohttp request object @@ -741,8 +731,7 @@ async def liveliness_handler(self, request: web.BaseRequest): @docs(tags=["server"], summary="Readiness check") @response_schema(AdminStatusReadinessSchema(), 200, description="") async def readiness_handler(self, request: web.BaseRequest): - """ - Request handler for liveliness check. + """Request handler for liveliness check. Args: request: aiohttp request object @@ -760,8 +749,7 @@ async def readiness_handler(self, request: web.BaseRequest): @docs(tags=["server"], summary="Shut down server") @response_schema(AdminShutdownSchema(), description="") async def shutdown_handler(self, request: web.BaseRequest): - """ - Request handler for server shutdown. + """Request handler for server shutdown. Args: request: aiohttp request object diff --git a/aries_cloudagent/admin/tests/test_request_context.py b/aries_cloudagent/admin/tests/test_request_context.py index e74763004e..8ab5159cf4 100644 --- a/aries_cloudagent/admin/tests/test_request_context.py +++ b/aries_cloudagent/admin/tests/test_request_context.py @@ -1,4 +1,4 @@ -from asynctest import mock as asyn_mock, TestCase as AsyncTestCase +from asynctest import TestCase as AsyncTestCase from ...core.in_memory import InMemoryProfile from ...core.profile import ProfileSession diff --git a/aries_cloudagent/askar/didcomm/v1.py b/aries_cloudagent/askar/didcomm/v1.py index df915efbb0..55400c7ba0 100644 --- a/aries_cloudagent/askar/didcomm/v1.py +++ b/aries_cloudagent/askar/didcomm/v1.py @@ -114,8 +114,7 @@ async def unpack_message(session: Session, enc_message: bytes) -> Tuple[str, str def _extract_payload_key(sender_cek: dict, recip_secret: Key) -> Tuple[bytes, str]: - """ - Extract the payload key from pack recipient details. + """Extract the payload key from pack recipient details. Returns: A tuple of the CEK and sender verkey """ diff --git a/aries_cloudagent/askar/profile.py b/aries_cloudagent/askar/profile.py index 42a8b5c68d..e9b84db4e0 100644 --- a/aries_cloudagent/askar/profile.py +++ b/aries_cloudagent/askar/profile.py @@ -176,8 +176,7 @@ def session(self, context: InjectionContext = None) -> ProfileSession: return AskarProfileSession(self, False, context=context) def transaction(self, context: InjectionContext = None) -> ProfileSession: - """ - Start a new interactive session with commit and rollback support. + """Start a new interactive session with commit and rollback support. If the current backend does not support transactions, then commit and rollback operations of the session will not have any effect. diff --git a/aries_cloudagent/askar/store.py b/aries_cloudagent/askar/store.py index 6c81d6696d..763ea4b077 100644 --- a/aries_cloudagent/askar/store.py +++ b/aries_cloudagent/askar/store.py @@ -25,8 +25,7 @@ class AskarStoreConfig: KEY_DERIVATION_ARGON2I_MOD = "kdf:argon2i:mod" def __init__(self, config: dict = None): - """ - Initialize a `AskarWallet` instance. + """Initialize a `AskarWallet` instance. Args: config: {name, key, seed, did, auto_recreate, auto_remove, @@ -118,8 +117,7 @@ def get_uri(self, create: bool = False) -> str: return uri async def remove_store(self): - """ - Remove an existing store. + """Remove an existing store. Raises: ProfileNotFoundError: If the wallet could not be found @@ -136,8 +134,7 @@ async def remove_store(self): raise ProfileError("Error removing store") from err async def open_store(self, provision: bool = False) -> "AskarOpenStore": - """ - Open a store, removing and/or creating it if so configured. + """Open a store, removing and/or creating it if so configured. Raises: ProfileNotFoundError: If the store is not found diff --git a/aries_cloudagent/askar/tests/test_profile.py b/aries_cloudagent/askar/tests/test_profile.py index 842e627cd8..453952271c 100644 --- a/aries_cloudagent/askar/tests/test_profile.py +++ b/aries_cloudagent/askar/tests/test_profile.py @@ -1,5 +1,4 @@ import asyncio -import logging import pytest from asynctest import mock diff --git a/aries_cloudagent/cache/base.py b/aries_cloudagent/cache/base.py index 9744c275a7..1a1ae68797 100644 --- a/aries_cloudagent/cache/base.py +++ b/aries_cloudagent/cache/base.py @@ -20,8 +20,7 @@ def __init__(self): @abstractmethod async def get(self, key: Text): - """ - Get an item from the cache. + """Get an item from the cache. Args: key: the key to retrieve an item for @@ -35,8 +34,7 @@ async def get(self, key: Text): async def set( self, keys: Union[Text, Sequence[Text]], value: Any, ttl: Optional[int] = None ): - """ - Add an item to the cache with an optional ttl. + """Add an item to the cache with an optional ttl. Args: keys: the key or keys for which to set an item @@ -47,8 +45,7 @@ async def set( @abstractmethod async def clear(self, key: Text): - """ - Remove an item from the cache, if present. + """Remove an item from the cache, if present. Args: key: the key to remove @@ -78,8 +75,7 @@ def __repr__(self) -> str: class CacheKeyLock: - """ - A lock on a particular cache key. + """A lock on a particular cache key. Used to prevent multiple async threads from generating or querying the same semi-expensive data. Not thread safe. @@ -159,8 +155,7 @@ def release(self): self.released = True async def __aexit__(self, exc_type, exc_val, exc_tb): - """ - Async context manager exit. + """Async context manager exit. `None` is returned to any waiters if no value is produced. """ diff --git a/aries_cloudagent/cache/in_memory.py b/aries_cloudagent/cache/in_memory.py index 0feb3328c5..5be9b41e35 100644 --- a/aries_cloudagent/cache/in_memory.py +++ b/aries_cloudagent/cache/in_memory.py @@ -26,8 +26,7 @@ def _remove_expired_cache_items(self): del self._cache[key] async def get(self, key: Text): - """ - Get an item from the cache. + """Get an item from the cache. Args: key: the key to retrieve an item for @@ -40,8 +39,7 @@ async def get(self, key: Text): return self._cache.get(key)["value"] if self._cache.get(key) else None async def set(self, keys: Union[Text, Sequence[Text]], value: Any, ttl: int = None): - """ - Add an item to the cache with an optional ttl. + """Add an item to the cache with an optional ttl. Overwrites existing cache entries. @@ -57,8 +55,7 @@ async def set(self, keys: Union[Text, Sequence[Text]], value: Any, ttl: int = No self._cache[key] = {"expires": expires_ts, "value": value} async def clear(self, key: Text): - """ - Remove an item from the cache, if present. + """Remove an item from the cache, if present. Args: key: the key to remove diff --git a/aries_cloudagent/cache/tests/test_in_memory_cache.py b/aries_cloudagent/cache/tests/test_in_memory_cache.py index 5da6d53843..e805a49df7 100644 --- a/aries_cloudagent/cache/tests/test_in_memory_cache.py +++ b/aries_cloudagent/cache/tests/test_in_memory_cache.py @@ -1,6 +1,6 @@ import pytest -from asyncio import ensure_future, sleep, wait_for +from asyncio import sleep, wait_for from ..base import CacheError from ..in_memory import InMemoryCache diff --git a/aries_cloudagent/commands/tests/test_upgrade.py b/aries_cloudagent/commands/tests/test_upgrade.py index 4e69b99ff5..3cbdda9831 100644 --- a/aries_cloudagent/commands/tests/test_upgrade.py +++ b/aries_cloudagent/commands/tests/test_upgrade.py @@ -3,7 +3,6 @@ from asynctest import mock as async_mock, TestCase as AsyncTestCase from ...core.in_memory import InMemoryProfile -from ...config.error import ArgsParseError from ...connections.models.conn_record import ConnRecord from ...storage.base import BaseStorage from ...storage.record import StorageRecord diff --git a/aries_cloudagent/commands/upgrade.py b/aries_cloudagent/commands/upgrade.py index c91bb4817f..8706c61bcf 100644 --- a/aries_cloudagent/commands/upgrade.py +++ b/aries_cloudagent/commands/upgrade.py @@ -385,8 +385,7 @@ async def upgrade( async def update_existing_records(profile: Profile): - """ - Update existing records. + """Update existing records. Args: profile: Root profile diff --git a/aries_cloudagent/config/argparse.py b/aries_cloudagent/config/argparse.py index eea818fbe2..ac38895254 100644 --- a/aries_cloudagent/config/argparse.py +++ b/aries_cloudagent/config/argparse.py @@ -74,8 +74,7 @@ def create_argument_parser(*, prog: str = None): def load_argument_groups(parser: ArgumentParser, *groups: Type[ArgumentGroup]): - """ - Log a set of argument groups into a parser. + """Log a set of argument groups into a parser. Returns: A callable to convert loaded arguments into a settings dictionary @@ -1469,8 +1468,7 @@ def get_settings(self, args: Namespace): @group(CAT_START, CAT_PROVISION) class MediationInviteGroup(ArgumentGroup): - """ - Mediation invitation settings. + """Mediation invitation settings. These can be provided at provision- and start-time. """ diff --git a/aries_cloudagent/config/base.py b/aries_cloudagent/config/base.py index 00d0c4a31c..10b2d82046 100644 --- a/aries_cloudagent/config/base.py +++ b/aries_cloudagent/config/base.py @@ -120,8 +120,7 @@ def inject( base_cls: Type[InjectType], settings: Optional[Mapping[str, Any]] = None, ) -> InjectType: - """ - Get the provided instance of a given class identifier. + """Get the provided instance of a given class identifier. Args: cls: The base class to retrieve an instance of @@ -139,8 +138,7 @@ def inject_or( settings: Optional[Mapping[str, Any]] = None, default: Optional[InjectType] = None, ) -> Optional[InjectType]: - """ - Get the provided instance of a given class identifier or default if not found. + """Get the provided instance of a given class identifier or default if not found. Args: base_cls: The base class to retrieve an instance of diff --git a/aries_cloudagent/config/base_context.py b/aries_cloudagent/config/base_context.py index 788a91940f..23ebf814dd 100644 --- a/aries_cloudagent/config/base_context.py +++ b/aries_cloudagent/config/base_context.py @@ -11,8 +11,7 @@ class ContextBuilder(ABC): """Base injection context builder class.""" def __init__(self, settings: Optional[Mapping[str, Any]] = None): - """ - Initialize an instance of the context builder. + """Initialize an instance of the context builder. Args: settings: Mapping of configuration settings diff --git a/aries_cloudagent/config/injection_context.py b/aries_cloudagent/config/injection_context.py index 9e5c5e051b..742d38f1d4 100644 --- a/aries_cloudagent/config/injection_context.py +++ b/aries_cloudagent/config/injection_context.py @@ -110,8 +110,7 @@ def inject( base_cls: Type[InjectType], settings: Mapping[str, object] = None, ) -> InjectType: - """ - Get the provided instance of a given class identifier. + """Get the provided instance of a given class identifier. Args: cls: The base class to retrieve an instance of @@ -129,8 +128,7 @@ def inject_or( settings: Mapping[str, object] = None, default: Optional[InjectType] = None, ) -> Optional[InjectType]: - """ - Get the provided instance of a given class identifier or default if not found. + """Get the provided instance of a given class identifier or default if not found. Args: base_cls: The base class to retrieve an instance of diff --git a/aries_cloudagent/config/injector.py b/aries_cloudagent/config/injector.py index 9362df2f2a..4d99f8d09c 100644 --- a/aries_cloudagent/config/injector.py +++ b/aries_cloudagent/config/injector.py @@ -57,8 +57,7 @@ def inject_or( settings: Mapping[str, object] = None, default: Optional[InjectType] = None, ) -> Optional[InjectType]: - """ - Get the provided instance of a given class identifier or default if not found. + """Get the provided instance of a given class identifier or default if not found. Args: base_cls: The base class to retrieve an instance of @@ -95,8 +94,7 @@ def inject( base_cls: Type[InjectType], settings: Mapping[str, object] = None, ) -> InjectType: - """ - Get the provided instance of a given class identifier. + """Get the provided instance of a given class identifier. Args: cls: The base class to retrieve an instance of diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index c156ec9e4b..f3bd59217d 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -28,8 +28,7 @@ def load_resource(path: str, encoding: str = None) -> TextIO: - """ - Open a resource file located in a python package or the local filesystem. + """Open a resource file located in a python package or the local filesystem. Args: path: The resource path in the form of `dir/file` or `package:dir/file` @@ -59,8 +58,7 @@ def configure( log_level: str = None, log_file: str = None, ): - """ - Configure logger. + """Configure logger. :param logging_config_path: str: (Default value = None) Optional path to custom logging config @@ -101,8 +99,7 @@ def print_banner( banner_length=40, border_character=":", ): - """ - Print a startup banner describing the configuration. + """Print a startup banner describing the configuration. Args: agent_label: Agent Label @@ -202,8 +199,7 @@ def print_notices(cls, settings: Settings): # This required the following custom implementation. ###################################################################### class TimedRotatingFileMultiProcessHandler(BaseRotatingHandler): - """ - Handler for logging to a file. + """Handler for logging to a file. Rotating the log file at certain timed with file lock unlock mechanism to support multi-process writing to log file. @@ -220,8 +216,7 @@ def __init__( utc=False, atTime=None, ): - """ - Initialize an instance of `TimedRotatingFileMultiProcessHandler`. + """Initialize an instance of `TimedRotatingFileMultiProcessHandler`. Args: filename: log file name with path diff --git a/aries_cloudagent/config/provider.py b/aries_cloudagent/config/provider.py index 19a2f34ca4..2e37302659 100644 --- a/aries_cloudagent/config/provider.py +++ b/aries_cloudagent/config/provider.py @@ -93,8 +93,7 @@ def __init__(self, provider: BaseProvider, unique_settings_keys: tuple = ()): self._unique_settings_keys = unique_settings_keys def provide(self, config: BaseSettings, injector: BaseInjector): - """ - Provide the object instance given a config and injector. + """Provide the object instance given a config and injector. Instances are cached keyed on a SHA256 digest of the relevant subset of settings. diff --git a/aries_cloudagent/config/tests/test_argparse.py b/aries_cloudagent/config/tests/test_argparse.py index 3554c8b793..32f9de4ebf 100644 --- a/aries_cloudagent/config/tests/test_argparse.py +++ b/aries_cloudagent/config/tests/test_argparse.py @@ -268,7 +268,7 @@ async def test_multitenancy_settings(self): settings = group.get_settings(result) - assert settings.get("multitenant.enabled") == True + assert settings.get("multitenant.enabled") is True assert settings.get("multitenant.jwt_secret") == "secret" assert settings.get("multitenant.wallet_type") == "askar" assert settings.get("multitenant.wallet_name") == "test" @@ -290,7 +290,7 @@ async def test_multitenancy_settings(self): settings = group.get_settings(result) - assert settings.get("multitenant.enabled") == True + assert settings.get("multitenant.enabled") is True assert settings.get("multitenant.jwt_secret") == "secret" assert settings.get("multitenant.wallet_type") == "askar" assert settings.get("multitenant.wallet_name") == "test" @@ -314,10 +314,10 @@ async def test_endorser_settings(self): settings = group.get_settings(result) - assert settings.get("endorser.author") == True - assert settings.get("endorser.endorser") == False + assert settings.get("endorser.author") is True + assert settings.get("endorser.endorser") is False assert settings.get("endorser.endorser_public_did") == "did:sov:12345" - assert settings.get("endorser.auto_endorse") == False + assert settings.get("endorser.auto_endorse") is False async def test_logging(self): """Test logging.""" diff --git a/aries_cloudagent/config/tests/test_injector.py b/aries_cloudagent/config/tests/test_injector.py index 804e328a0e..d44e39fa63 100644 --- a/aries_cloudagent/config/tests/test_injector.py +++ b/aries_cloudagent/config/tests/test_injector.py @@ -142,6 +142,6 @@ def test_inject_cached(self): def test_falsey_still_returns(self): """Test the injector still returns falsey values.""" - self.test_instance.bind_instance(dict, dict()) + self.test_instance.bind_instance(dict, {}) assert self.test_instance.inject_or(dict) is not None assert self.test_instance.inject(dict) is not None diff --git a/aries_cloudagent/config/tests/test_ledger.py b/aries_cloudagent/config/tests/test_ledger.py index 8d72dfded6..dc46041bc0 100644 --- a/aries_cloudagent/config/tests/test_ledger.py +++ b/aries_cloudagent/config/tests/test_ledger.py @@ -1,5 +1,3 @@ -from os import remove -from tempfile import NamedTemporaryFile import pytest from asynctest import TestCase as AsyncTestCase, mock as async_mock @@ -10,7 +8,6 @@ from ...wallet.base import BaseWallet from .. import ledger as test_module -from ..injection_context import InjectionContext TEST_DID = "55GkHamhTU1ZbTbV2ab9DE" TEST_GENESIS = "GENESIS" @@ -698,7 +695,7 @@ async def test_ledger_accept_taa_tty(self, mock_stdout): mock_ledger, mock_profile, taa_info, provision=False ) - async def test_ledger_accept_taa_tty(self): + async def test_ledger_accept_taa(self): taa_info = { "taa_record": {"version": "1.0", "text": "Agreement"}, "aml_record": {"aml": {"wallet_agreement": "", "on_file": ""}}, diff --git a/aries_cloudagent/config/tests/test_provider.py b/aries_cloudagent/config/tests/test_provider.py index e78f9bfffe..6999ddfe1a 100644 --- a/aries_cloudagent/config/tests/test_provider.py +++ b/aries_cloudagent/config/tests/test_provider.py @@ -1,5 +1,5 @@ from tempfile import NamedTemporaryFile -from weakref import ref, ReferenceType +from weakref import ref from asynctest import TestCase as AsyncTestCase, mock as async_mock diff --git a/aries_cloudagent/config/tests/test_settings.py b/aries_cloudagent/config/tests/test_settings.py index 3415d4c260..c5d2c21756 100644 --- a/aries_cloudagent/config/tests/test_settings.py +++ b/aries_cloudagent/config/tests/test_settings.py @@ -4,7 +4,6 @@ from aries_cloudagent.config.plugin_settings import PluginSettings -from ..base import SettingsError from ..settings import Settings from ..plugin_settings import PLUGIN_CONFIG_KEY @@ -39,7 +38,7 @@ def test_get_formats(self): self.test_instance["BOOL"] = "false" assert self.test_instance.get_bool("BOOL") is False self.test_instance["INT"] = "5" - assert self.test_instance.get_int("INT") is 5 + assert self.test_instance.get_int("INT") == 5 assert self.test_instance.get_str("INT") == "5" with self.assertRaises(TypeError): self.test_instance[None] = 1 diff --git a/aries_cloudagent/connections/base_manager.py b/aries_cloudagent/connections/base_manager.py index 5f77559dfb..74a6384356 100644 --- a/aries_cloudagent/connections/base_manager.py +++ b/aries_cloudagent/connections/base_manager.py @@ -1,5 +1,4 @@ -""" -Class to provide some common utilities. +"""Class to provide some common utilities. For Connection, DIDExchange and OutOfBand Manager. """ @@ -66,8 +65,7 @@ class BaseConnectionManager: RECORD_TYPE_DID_KEY = "did_key" def __init__(self, profile: Profile): - """ - Initialize a BaseConnectionManager. + """Initialize a BaseConnectionManager. Args: session: The profile session for this presentation @@ -310,8 +308,7 @@ async def verification_methods_for_service( async def resolve_invitation( self, did: str, service_accept: Optional[Sequence[Text]] = None ) -> Tuple[str, List[str], List[str]]: - """ - Resolve invitation with the DID Resolver. + """Resolve invitation with the DID Resolver. Args: did: Document ID to resolve @@ -686,8 +683,7 @@ async def find_connection( my_verkey: Optional[str] = None, auto_complete=False, ) -> Optional[ConnRecord]: - """ - Look up existing connection information for a sender verkey. + """Look up existing connection information for a sender verkey. Args: their_did: Their DID @@ -739,8 +735,7 @@ async def find_connection( async def find_inbound_connection( self, receipt: MessageReceipt ) -> Optional[ConnRecord]: - """ - Deserialize an incoming message and further populate the request context. + """Deserialize an incoming message and further populate the request context. Args: receipt: The message receipt @@ -790,8 +785,7 @@ async def find_inbound_connection( async def resolve_inbound_connection( self, receipt: MessageReceipt ) -> Optional[ConnRecord]: - """ - Populate the receipt DID information and find the related `ConnRecord`. + """Populate the receipt DID information and find the related `ConnRecord`. Args: receipt: The message receipt @@ -837,8 +831,7 @@ async def resolve_inbound_connection( ) async def get_endpoints(self, conn_id: str) -> Tuple[Optional[str], Optional[str]]: - """ - Get connection endpoints. + """Get connection endpoints. Args: conn_id: connection identifier @@ -874,8 +867,7 @@ async def create_static_connection( alias: Optional[str] = None, mediation_id: Optional[str] = None, ) -> Tuple[DIDInfo, DIDInfo, ConnRecord]: - """ - Register a new static connection (for use by the test suite). + """Register a new static connection (for use by the test suite). Args: my_did: override the DID used in the connection diff --git a/aries_cloudagent/connections/models/conn_record.py b/aries_cloudagent/connections/models/conn_record.py index a75b80e318..693c3eeda8 100644 --- a/aries_cloudagent/connections/models/conn_record.py +++ b/aries_cloudagent/connections/models/conn_record.py @@ -105,8 +105,7 @@ def __eq__(self, other: Union[str, "ConnRecord.Role"]) -> bool: return self is ConnRecord.Role.get(other) class State(Enum): - """ - Collator for equivalent states between RFC 160 and RFC 23. + """Collator for equivalent states between RFC 160 and RFC 23. On the connection record, the state has to serve for both RFCs. Hence, internally, RFC23 requester/responder states collate to diff --git a/aries_cloudagent/connections/models/connection_target.py b/aries_cloudagent/connections/models/connection_target.py index 6795b970ba..99ebb7c1bd 100644 --- a/aries_cloudagent/connections/models/connection_target.py +++ b/aries_cloudagent/connections/models/connection_target.py @@ -31,8 +31,7 @@ def __init__( routing_keys: Optional[Sequence[str]] = None, sender_key: Optional[str] = None, ): - """ - Initialize a ConnectionTarget instance. + """Initialize a ConnectionTarget instance. Args: did: A did for the connection diff --git a/aries_cloudagent/connections/models/diddoc/__init__.py b/aries_cloudagent/connections/models/diddoc/__init__.py index 2210a1b2f3..7cd0bbdd63 100644 --- a/aries_cloudagent/connections/models/diddoc/__init__.py +++ b/aries_cloudagent/connections/models/diddoc/__init__.py @@ -1,5 +1,4 @@ -""" -DID Document model support. +"""DID Document model support. Copyright 2017-2019 Government of Canada Public Services and Procurement Canada - buyandsell.gc.ca diff --git a/aries_cloudagent/connections/models/diddoc/diddoc.py b/aries_cloudagent/connections/models/diddoc/diddoc.py index ea47866487..0970a2fb0b 100644 --- a/aries_cloudagent/connections/models/diddoc/diddoc.py +++ b/aries_cloudagent/connections/models/diddoc/diddoc.py @@ -1,5 +1,4 @@ -""" -DID Document classes. +"""DID Document classes. Copyright 2017-2019 Government of Canada Public Services and Procurement Canada - buyandsell.gc.ca @@ -31,8 +30,7 @@ class DIDDoc: - """ - DID document, grouping a DID with verification keys and services. + """DID document, grouping a DID with verification keys and services. Retains DIDs as raw values (orientated toward indy-facing operations), everything else as URIs (oriented toward W3C-facing operations). @@ -41,8 +39,7 @@ class DIDDoc: CONTEXT = "https://w3id.org/did/v1" def __init__(self, did: str = None) -> None: - """ - Initialize the DIDDoc instance. + """Initialize the DIDDoc instance. Retain DID ('id' in DIDDoc context); initialize verification keys and services to empty lists. @@ -67,8 +64,7 @@ def did(self) -> str: @did.setter def did(self, value: str) -> None: - """ - Set DID ('id' in DIDDoc context). + """Set DID ('id' in DIDDoc context). Args: value: DID @@ -99,8 +95,7 @@ def service(self) -> dict: return self._service def set(self, item: Union[Service, PublicKey]) -> "DIDDoc": - """ - Add or replace service or public key; return current DIDDoc. + """Add or replace service or public key; return current DIDDoc. Raises: ValueError: if input item is neither service nor public key. @@ -122,8 +117,7 @@ def set(self, item: Union[Service, PublicKey]) -> "DIDDoc": ) def serialize(self) -> dict: - """ - Dump current object to a JSON-compatible dictionary. + """Dump current object to a JSON-compatible dictionary. Returns: dict representation of current DIDDoc @@ -146,8 +140,7 @@ def serialize(self) -> dict: } def to_json(self) -> str: - """ - Dump current object as json (JSON-LD). + """Dump current object as json (JSON-LD). Returns: json representation of current DIDDoc @@ -159,8 +152,7 @@ def to_json(self) -> str: def add_service_pubkeys( self, service: dict, tags: Union[Sequence[str], str] ) -> List[PublicKey]: - """ - Add public keys specified in service. Return public keys so discovered. + """Add public keys specified in service. Return public keys so discovered. Args: service: service from DID document @@ -214,8 +206,7 @@ def add_service_pubkeys( @classmethod def deserialize(cls, did_doc: dict) -> "DIDDoc": - """ - Construct DIDDoc object from dict representation. + """Construct DIDDoc object from dict representation. Args: did_doc: DIDDoc dict representation @@ -304,8 +295,7 @@ def deserialize(cls, did_doc: dict) -> "DIDDoc": @classmethod def from_json(cls, did_doc_json: str) -> "DIDDoc": - """ - Construct DIDDoc object from json representation. + """Construct DIDDoc object from json representation. Args: did_doc_json: DIDDoc json representation diff --git a/aries_cloudagent/connections/models/diddoc/publickey.py b/aries_cloudagent/connections/models/diddoc/publickey.py index 25aa8874fb..03492b3a0a 100644 --- a/aries_cloudagent/connections/models/diddoc/publickey.py +++ b/aries_cloudagent/connections/models/diddoc/publickey.py @@ -1,5 +1,4 @@ -""" -DID Document Public Key classes. +"""DID Document Public Key classes. Copyright 2017-2019 Government of Canada Public Services and Procurement Canada - buyandsell.gc.ca @@ -46,8 +45,7 @@ class PublicKeyType(Enum): @staticmethod def get(val: str) -> "PublicKeyType": - """ - Find enum instance corresponding to input value (RsaVerificationKey2018 etc). + """Find enum instance corresponding to input value (RsaVerificationKey2018 etc). Args: val: input value marking public key type @@ -80,8 +78,7 @@ def specifier(self) -> str: return self.value.specifier def specification(self, val: str) -> str: - """ - Return specifier and input value for use in public key specification. + """Return specifier and input value for use in public key specification. Args: val: value of public key @@ -94,8 +91,7 @@ def specification(self, val: str) -> str: class PublicKey: - """ - Public key specification to embed in DID document. + """Public key specification to embed in DID document. Retains DIDs as raw values (orientated toward indy-facing operations), everything else as URIs (oriented toward W3C-facing operations). @@ -110,8 +106,7 @@ def __init__( controller: str = None, authn: bool = False, ) -> None: - """ - Retain key specification particulars. + """Retain key specification particulars. Args: did: DID of DID document embedding public key diff --git a/aries_cloudagent/connections/models/diddoc/service.py b/aries_cloudagent/connections/models/diddoc/service.py index 07dc981758..27d9564d5e 100644 --- a/aries_cloudagent/connections/models/diddoc/service.py +++ b/aries_cloudagent/connections/models/diddoc/service.py @@ -1,5 +1,4 @@ -""" -DID Document Service classes. +"""DID Document Service classes. Copyright 2017-2019 Government of Canada Public Services and Procurement Canada - buyandsell.gc.ca @@ -25,8 +24,7 @@ class Service: - """ - Service specification to embed in DID document. + """Service specification to embed in DID document. Retains DIDs as raw values (orientated toward indy-facing operations), everything else as URIs (oriented toward W3C-facing operations). @@ -42,8 +40,7 @@ def __init__( endpoint: str, priority: int = 0, ): - """ - Initialize the Service instance. + """Initialize the Service instance. Retain service specification particulars. diff --git a/aries_cloudagent/connections/models/diddoc/tests/test_diddoc.py b/aries_cloudagent/connections/models/diddoc/tests/test_diddoc.py index 141a0e6051..bc720acffb 100644 --- a/aries_cloudagent/connections/models/diddoc/tests/test_diddoc.py +++ b/aries_cloudagent/connections/models/diddoc/tests/test_diddoc.py @@ -16,9 +16,7 @@ """ -import json - -from asynctest import TestCase as AsyncTestCase, mock as async_mock +from asynctest import TestCase as AsyncTestCase from .. import DIDDoc, PublicKey, PublicKeyType, Service from ..util import canon_did, canon_ref @@ -81,17 +79,17 @@ async def test_basic(self): dd_copy.authnkey[k].to_dict() == dd.authnkey[k].to_dict() for k in dd_copy.authnkey ) - assert {k for k in dd_copy.authnkey} == {k for k in dd.authnkey} + assert set(dd_copy.authnkey) == set(dd.authnkey) assert all( dd_copy.pubkey[k].to_dict() == dd.pubkey[k].to_dict() for k in dd_copy.pubkey ) - assert {k for k in dd_copy.pubkey} == {k for k in dd.pubkey} + assert set(dd_copy.pubkey) == set(dd.pubkey) assert all( dd_copy.service[k].to_dict() == dd.service[k].to_dict() for k in dd_copy.service ) - assert {k for k in dd_copy.service} == {k for k in dd.service} + assert set(dd_copy.service) == set(dd.service) # print('\n\n== 2 == DID Doc de/serialization operates OK:') # Exercise accessors @@ -99,7 +97,7 @@ async def test_basic(self): assert dd.did == canon_did(dd_out["id"]) with self.assertRaises(ValueError): dd.set(["neither a service", "nor a public key"]) - assert dd.service[[k for k in dd.service][0]].did == dd.did + assert dd.service[list(dd.service)[0]].did == dd.did # print('\n\n== 3 == DID Doc accessors operate OK') def test_embedded_authkey(self): @@ -486,7 +484,7 @@ def test_pubkey_type(self): dd = DIDDoc.deserialize(dd_in) assert PublicKeyType.get("no-such-type") is None - pubkey0 = dd.pubkey[[k for k in dd.pubkey][0]] + pubkey0 = dd.pubkey[list(dd.pubkey)[0]] was_authn = pubkey0.authn pubkey0.authn = not was_authn assert pubkey0.authn != was_authn diff --git a/aries_cloudagent/connections/models/diddoc/util.py b/aries_cloudagent/connections/models/diddoc/util.py index 7d838eff64..e79456ca00 100644 --- a/aries_cloudagent/connections/models/diddoc/util.py +++ b/aries_cloudagent/connections/models/diddoc/util.py @@ -1,5 +1,4 @@ -""" -DIDDoc utility methods. +"""DIDDoc utility methods. Copyright 2017-2019 Government of Canada Public Services and Procurement Canada - buyandsell.gc.ca @@ -23,8 +22,7 @@ def resource(ref: str, delimiter: str = None) -> str: - """ - Extract the resource for an identifier. + """Extract the resource for an identifier. Given a (URI) reference, return up to its delimiter (exclusively), or all of it if there is none. @@ -39,8 +37,7 @@ def resource(ref: str, delimiter: str = None) -> str: def canon_did(uri: str) -> str: - """ - Convert a URI into a DID if need be, left-stripping 'did:sov:' if present. + """Convert a URI into a DID if need be, left-stripping 'did:sov:' if present. Args: uri: input URI or DID @@ -63,8 +60,7 @@ def canon_did(uri: str) -> str: def canon_ref(did: str, ref: str, delimiter: str = None): - """ - Given a reference in a DID document, return it in its canonical form of a URI. + """Given a reference in a DID document, return it in its canonical form of a URI. Args: did: DID acting as the identifier of the DID document @@ -98,8 +94,7 @@ def canon_ref(did: str, ref: str, delimiter: str = None): def ok_did(token: str) -> bool: - """ - Whether input token looks like a valid decentralized identifier. + """Whether input token looks like a valid decentralized identifier. Args: token: candidate string diff --git a/aries_cloudagent/connections/models/tests/test_conn_record.py b/aries_cloudagent/connections/models/tests/test_conn_record.py index e315670729..19f540adda 100644 --- a/aries_cloudagent/connections/models/tests/test_conn_record.py +++ b/aries_cloudagent/connections/models/tests/test_conn_record.py @@ -255,7 +255,7 @@ async def test_completed_is_ready(self): connection_id = await record.save(self.session) fetched = await ConnRecord.retrieve_by_id(self.session, connection_id) - assert fetched.is_ready == True + assert fetched.is_ready is True async def test_response_is_ready(self): record = ConnRecord(my_did=self.test_did, state=ConnRecord.State.RESPONSE) diff --git a/aries_cloudagent/connections/tests/test_base_manager.py b/aries_cloudagent/connections/tests/test_base_manager.py index f960933699..20d3d21f0e 100644 --- a/aries_cloudagent/connections/tests/test_base_manager.py +++ b/aries_cloudagent/connections/tests/test_base_manager.py @@ -13,7 +13,6 @@ JsonWebKey2020, ) -from .. import base_manager as test_module from ...cache.base import BaseCache from ...cache.in_memory import InMemoryCache from ...config.base import InjectionError diff --git a/aries_cloudagent/core/conductor.py b/aries_cloudagent/core/conductor.py index 2e71f853bf..5e4887930f 100644 --- a/aries_cloudagent/core/conductor.py +++ b/aries_cloudagent/core/conductor.py @@ -1,5 +1,4 @@ -""" -The Conductor. +"""The Conductor. The conductor is responsible for coordinating messages that are received over the network, communicating with the ledger, passing messages to handlers, @@ -86,16 +85,14 @@ class Conductor: - """ - Conductor class. + """Conductor class. Class responsible for initializing concrete implementations of our require interfaces and routing inbound and outbound message data. """ def __init__(self, context_builder: ContextBuilder) -> None: - """ - Initialize an instance of Conductor. + """Initialize an instance of Conductor. Args: inbound_transports: Configuration for inbound transports @@ -546,8 +543,7 @@ def inbound_message_router( message: InboundMessage, can_respond: bool = False, ): - """ - Route inbound messages. + """Route inbound messages. Args: context: The context associated with the inbound message @@ -626,8 +622,7 @@ async def outbound_message_router( outbound: OutboundMessage, inbound: InboundMessage = None, ) -> OutboundSendStatus: - """ - Route an outbound message. + """Route an outbound message. Args: profile: The active profile for the request @@ -646,8 +641,7 @@ async def _outbound_message_router( outbound: OutboundMessage, inbound: InboundMessage = None, ) -> OutboundSendStatus: - """ - Route an outbound message. + """Route an outbound message. Args: profile: The active profile for the request @@ -680,8 +674,7 @@ async def queue_outbound( outbound: OutboundMessage, inbound: Optional[InboundMessage] = None, ) -> OutboundSendStatus: - """ - Queue an outbound message for transport. + """Queue an outbound message for transport. Args: profile: The active profile @@ -749,8 +742,7 @@ def webhook_router( max_attempts: int = None, metadata: dict = None, ): - """ - Route a webhook through the outbound transport manager. + """Route a webhook through the outbound transport manager. Args: topic: The webhook topic diff --git a/aries_cloudagent/core/dispatcher.py b/aries_cloudagent/core/dispatcher.py index 99197ed0f4..66664474fe 100644 --- a/aries_cloudagent/core/dispatcher.py +++ b/aries_cloudagent/core/dispatcher.py @@ -1,5 +1,4 @@ -""" -The Dispatcher. +"""The Dispatcher. The dispatcher is responsible for coordinating data flow between handlers, providing lifecycle hook callbacks storing state for message threads, etc. @@ -42,8 +41,7 @@ class ProblemReportParseError(MessageParseError): class Dispatcher: - """ - Dispatcher class. + """Dispatcher class. Class responsible for dispatching messages to message handlers and responding to other agents. @@ -102,8 +100,7 @@ def queue_message( send_outbound: Coroutine, complete: Callable = None, ) -> PendingTask: - """ - Add a message to the processing queue for handling. + """Add a message to the processing queue for handling. Args: profile: The profile associated with the inbound message @@ -126,8 +123,7 @@ async def handle_message( inbound_message: InboundMessage, send_outbound: Coroutine, ): - """ - Configure responder and message context and invoke the message handler. + """Configure responder and message context and invoke the message handler. Args: profile: The profile associated with the inbound message @@ -270,8 +266,7 @@ async def handle_message( async def make_message( self, profile: Profile, parsed_msg: dict ) -> Tuple[BaseMessage, Optional[str]]: - """ - Deserialize a message dict into the appropriate message instance. + """Deserialize a message dict into the appropriate message instance. Given a dict describing a message, this method returns an instance of the related message class. @@ -332,8 +327,7 @@ def __init__( send_outbound: Coroutine, **kwargs, ): - """ - Initialize an instance of `DispatcherResponder`. + """Initialize an instance of `DispatcherResponder`. Args: context: The request context of the incoming message @@ -352,8 +346,7 @@ def __init__( async def create_outbound( self, message: Union[AgentMessage, BaseMessage, str, bytes], **kwargs ) -> OutboundMessage: - """ - Create an OutboundMessage from a message body. + """Create an OutboundMessage from a message body. Args: message: The message payload @@ -376,8 +369,7 @@ async def create_outbound( async def send_outbound( self, message: OutboundMessage, **kwargs ) -> OutboundSendStatus: - """ - Send outbound message. + """Send outbound message. Args: message: The `OutboundMessage` to be sent @@ -406,8 +398,7 @@ async def send_outbound( return await self._send(context.profile, message, self._inbound_message) async def send_webhook(self, topic: str, payload: dict): - """ - Dispatch a webhook. DEPRECATED: use the event bus instead. + """Dispatch a webhook. DEPRECATED: use the event bus instead. Args: topic: the webhook topic identifier diff --git a/aries_cloudagent/core/error.py b/aries_cloudagent/core/error.py index 168e02154d..0f2fc88074 100644 --- a/aries_cloudagent/core/error.py +++ b/aries_cloudagent/core/error.py @@ -18,8 +18,7 @@ def message(self) -> str: @property def roll_up(self) -> str: - """ - Accessor for nested error messages rolled into one line. + """Accessor for nested error messages rolled into one line. For display: aiohttp.web errors truncate after newline. """ @@ -72,8 +71,7 @@ class ProtocolDefinitionValidationError(BaseError): class ProtocolMinorVersionNotSupported(BaseError): - """ - Minimum minor version protocol error. + """Minimum minor version protocol error. Error raised when protocol support exists but minimum minor version is higher than in @type parameter. diff --git a/aries_cloudagent/core/goal_code_registry.py b/aries_cloudagent/core/goal_code_registry.py index 077634b2b5..3fd8ace900 100644 --- a/aries_cloudagent/core/goal_code_registry.py +++ b/aries_cloudagent/core/goal_code_registry.py @@ -13,8 +13,7 @@ def __init__(self): self.goal_codes = [] def register_controllers(self, *controller_sets): - """ - Add new controllers. + """Add new controllers. Args: controller_sets: Mappings of controller to coroutines diff --git a/aries_cloudagent/core/in_memory/didcomm/tests/test_1pu.py b/aries_cloudagent/core/in_memory/didcomm/tests/test_1pu.py index e57b7bddda..7923c9d6df 100644 --- a/aries_cloudagent/core/in_memory/didcomm/tests/test_1pu.py +++ b/aries_cloudagent/core/in_memory/didcomm/tests/test_1pu.py @@ -2,7 +2,7 @@ from .....wallet.util import b64_to_bytes -from ..derive_1pu import * +from ..derive_1pu import derive_receiver_1pu, derive_sender_1pu def test_1pu_hex_example(): diff --git a/aries_cloudagent/core/in_memory/didcomm/tests/test_ecdh.py b/aries_cloudagent/core/in_memory/didcomm/tests/test_ecdh.py index 943456c7b8..dc1db0bd54 100644 --- a/aries_cloudagent/core/in_memory/didcomm/tests/test_ecdh.py +++ b/aries_cloudagent/core/in_memory/didcomm/tests/test_ecdh.py @@ -1,6 +1,10 @@ from ecdsa import ECDH, NIST256p, SigningKey -from ..derive_ecdh import * +from ..derive_ecdh import ( + derive_shared_secret, + derive_shared_secret_from_key, + concat_kdf, +) # Generate the same shared secret from imported generated keys diff --git a/aries_cloudagent/core/in_memory/profile.py b/aries_cloudagent/core/in_memory/profile.py index 94f78ab68d..ece8c5d00f 100644 --- a/aries_cloudagent/core/in_memory/profile.py +++ b/aries_cloudagent/core/in_memory/profile.py @@ -18,8 +18,7 @@ class InMemoryProfile(Profile): - """ - Provide access to in-memory profile management. + """Provide access to in-memory profile management. Used primarily for testing. """ @@ -54,8 +53,7 @@ def session(self, context: InjectionContext = None) -> "ProfileSession": return InMemoryProfileSession(self, context=context) def transaction(self, context: InjectionContext = None) -> "ProfileSession": - """ - Start a new interactive session with commit and rollback support. + """Start a new interactive session with commit and rollback support. If the current backend does not support transactions, then commit and rollback operations of the session will not have any effect. diff --git a/aries_cloudagent/core/plugin_registry.py b/aries_cloudagent/core/plugin_registry.py index 40ea4fb83f..f286e2e404 100644 --- a/aries_cloudagent/core/plugin_registry.py +++ b/aries_cloudagent/core/plugin_registry.py @@ -37,7 +37,7 @@ def plugins(self) -> Sequence[ModuleType]: def validate_version(self, version_list, module_name): """Validate version dict format.""" - is_list = type(version_list) is list + is_list = isinstance(version_list, list) # Must be a list if not is_list: @@ -51,7 +51,7 @@ def validate_version(self, version_list, module_name): "Versions list must define at least one version module" ) - if not all(type(v) is dict for v in version_list): + if not all(isinstance(v, dict) for v in version_list): raise ProtocolDefinitionValidationError( "Element of versions definition list is not of type dict" ) @@ -60,13 +60,15 @@ def validate_version(self, version_list, module_name): # Dicts must have correct format try: - type(version_dict["major_version"]) is int and type( - version_dict["minimum_minor_version"] - ) is int and type( - version_dict["current_minor_version"] - ) is int and type( - version_dict["path"] - ) is str + if not ( + isinstance(version_dict["major_version"], int) + and isinstance(version_dict["minimum_minor_version"], int) + and isinstance(version_dict["current_minor_version"], int) + and isinstance(version_dict["path"], str) + ): + raise ProtocolDefinitionValidationError( + "Unexpected types in version definition" + ) except KeyError as e: raise ProtocolDefinitionValidationError( f"Element of versions definition list is missing an attribute: {e}" diff --git a/aries_cloudagent/core/profile.py b/aries_cloudagent/core/profile.py index c78ed8d94f..cb8a92c704 100644 --- a/aries_cloudagent/core/profile.py +++ b/aries_cloudagent/core/profile.py @@ -67,8 +67,7 @@ def session(self, context: InjectionContext = None) -> "ProfileSession": @abstractmethod def transaction(self, context: InjectionContext = None) -> "ProfileSession": - """ - Start a new interactive session with commit and rollback support. + """Start a new interactive session with commit and rollback support. If the current backend does not support transactions, then commit and rollback operations of the session will not have any effect. @@ -79,8 +78,7 @@ def inject( base_cls: Type[InjectType], settings: Mapping[str, object] = None, ) -> InjectType: - """ - Get the provided instance of a given class identifier. + """Get the provided instance of a given class identifier. Args: cls: The base class to retrieve an instance of @@ -98,8 +96,7 @@ def inject_or( settings: Mapping[str, object] = None, default: Optional[InjectType] = None, ) -> Optional[InjectType]: - """ - Get the provided instance of a given class identifier or default if not found. + """Get the provided instance of a given class identifier or default if not found. Args: base_cls: The base class to retrieve an instance of @@ -174,8 +171,7 @@ async def _teardown(self, commit: bool = None): """Dispose of the underlying session or transaction.""" def __await__(self): - """ - Coroutine magic method. + """Coroutine magic method. A session must be awaited or used as an async context manager. """ @@ -230,8 +226,7 @@ def profile(self) -> Profile: return self._profile async def commit(self): - """ - Commit any updates performed within the transaction. + """Commit any updates performed within the transaction. If the current session is not a transaction, then nothing is performed. """ @@ -241,8 +236,7 @@ async def commit(self): self._active = False async def rollback(self): - """ - Roll back any updates performed within the transaction. + """Roll back any updates performed within the transaction. If the current session is not a transaction, then nothing is performed. """ @@ -256,8 +250,7 @@ def inject( base_cls: Type[InjectType], settings: Mapping[str, object] = None, ) -> InjectType: - """ - Get the provided instance of a given class identifier. + """Get the provided instance of a given class identifier. Args: cls: The base class to retrieve an instance of @@ -277,8 +270,7 @@ def inject_or( settings: Mapping[str, object] = None, default: Optional[InjectType] = None, ) -> Optional[InjectType]: - """ - Get the provided instance of a given class identifier or default if not found. + """Get the provided instance of a given class identifier or default if not found. Args: base_cls: The base class to retrieve an instance of diff --git a/aries_cloudagent/core/protocol_registry.py b/aries_cloudagent/core/protocol_registry.py index 90175f9109..c322fad2ad 100644 --- a/aries_cloudagent/core/protocol_registry.py +++ b/aries_cloudagent/core/protocol_registry.py @@ -76,8 +76,7 @@ def parse_type_string(self, message_type): } def create_msg_types_for_minor_version(self, typesets, version_definition): - """ - Return mapping of message type to module path for minor versions. + """Return mapping of message type to module path for minor versions. Args: typesets: Mappings of message types to register @@ -149,8 +148,7 @@ def _update_version_map(self, message_type_string, module_path, version_definiti ) def register_message_types(self, *typesets, version_definition=None): - """ - Add new supported message types. + """Add new supported message types. Args: typesets: Mappings of message types to register @@ -183,8 +181,7 @@ def register_message_types(self, *typesets, version_definition=None): ) def register_controllers(self, *controller_sets, version_definition=None): - """ - Add new controllers. + """Add new controllers. Args: controller_sets: Mappings of message families to coroutines @@ -194,8 +191,7 @@ def register_controllers(self, *controller_sets, version_definition=None): self._controllers.update(controlset) def resolve_message_class(self, message_type: str) -> type: - """ - Resolve a message_type to a message class. + """Resolve a message_type to a message class. Given a message type identifier, this method returns the corresponding registered message class. diff --git a/aries_cloudagent/core/tests/test_error.py b/aries_cloudagent/core/tests/test_error.py index 9a7dea11d3..3497b6ca9d 100644 --- a/aries_cloudagent/core/tests/test_error.py +++ b/aries_cloudagent/core/tests/test_error.py @@ -1,5 +1,3 @@ -import asyncio - from asynctest import TestCase as AsyncTestCase from ..error import BaseError diff --git a/aries_cloudagent/core/tests/test_goal_code_registry.py b/aries_cloudagent/core/tests/test_goal_code_registry.py index 688c9e7954..06d161881c 100644 --- a/aries_cloudagent/core/tests/test_goal_code_registry.py +++ b/aries_cloudagent/core/tests/test_goal_code_registry.py @@ -1,4 +1,4 @@ -from asynctest import TestCase as AsyncTestCase, mock as async_mock +from asynctest import TestCase as AsyncTestCase from ...protocols.issue_credential.v1_0.message_types import CONTROLLERS diff --git a/aries_cloudagent/core/tests/test_oob_processor.py b/aries_cloudagent/core/tests/test_oob_processor.py index 7c73a946ad..1db8762c89 100644 --- a/aries_cloudagent/core/tests/test_oob_processor.py +++ b/aries_cloudagent/core/tests/test_oob_processor.py @@ -703,8 +703,8 @@ async def test_handle_message_connection(self): ), ) - assert oob_record.attach_thread_id == None - assert oob_record.their_service == None + assert oob_record.attach_thread_id is None + assert oob_record.their_service is None oob_record.save.assert_not_called() diff --git a/aries_cloudagent/core/tests/test_plugin_registry.py b/aries_cloudagent/core/tests/test_plugin_registry.py index 7d4d86a9e4..0bbe8c9be4 100644 --- a/aries_cloudagent/core/tests/test_plugin_registry.py +++ b/aries_cloudagent/core/tests/test_plugin_registry.py @@ -1,5 +1,4 @@ import pytest -from unittest.mock import call from asynctest import TestCase as AsyncTestCase, mock as async_mock, call @@ -493,7 +492,7 @@ class MODULE: None, # message types None, # definition without versions attr ] - assert self.registry.register_plugin(self.blocked_module) == None + assert self.registry.register_plugin(self.blocked_module) is None assert self.blocked_module not in self.registry._plugins.keys() async def test_register_definitions_malformed(self): @@ -600,4 +599,4 @@ async def test_load_protocols_no_mod_def_message_types(self): assert load_module.call_count == 4 def test_repr(self): - assert type(repr(self.registry)) is str + assert isinstance(repr(self.registry), str) diff --git a/aries_cloudagent/core/tests/test_profile.py b/aries_cloudagent/core/tests/test_profile.py index 32edb646de..72d4c3e0e8 100644 --- a/aries_cloudagent/core/tests/test_profile.py +++ b/aries_cloudagent/core/tests/test_profile.py @@ -39,7 +39,7 @@ async def test_session_active(self): await session.__aenter__() self.assertEqual(session.active, True) - session.context.injector.bind_instance(dict, dict()) + session.context.injector.bind_instance(dict, {}) assert session.inject_or(dict) is not None assert profile.inject_or(dict) is None diff --git a/aries_cloudagent/core/tests/test_protocol_registry.py b/aries_cloudagent/core/tests/test_protocol_registry.py index 623ad1d808..2800f2c46f 100644 --- a/aries_cloudagent/core/tests/test_protocol_registry.py +++ b/aries_cloudagent/core/tests/test_protocol_registry.py @@ -296,4 +296,4 @@ def test_resolve_message_load_class_none(self): assert result is None def test_repr(self): - assert type(repr(self.registry)) is str + assert isinstance(repr(self.registry), str) diff --git a/aries_cloudagent/core/util.py b/aries_cloudagent/core/util.py index dd28347e4e..2b35da9987 100644 --- a/aries_cloudagent/core/util.py +++ b/aries_cloudagent/core/util.py @@ -26,8 +26,7 @@ async def validate_get_response_version( profile: Profile, rec_version: str, msg_class: type ) -> Tuple[str, Optional[str]]: - """ - Return a tuple with version to respond with and warnings. + """Return a tuple with version to respond with and warnings. Process received version and protocol version definition, returns the tuple. diff --git a/aries_cloudagent/holder/routes.py b/aries_cloudagent/holder/routes.py index a7953e0b80..7b7ac9a198 100644 --- a/aries_cloudagent/holder/routes.py +++ b/aries_cloudagent/holder/routes.py @@ -194,8 +194,7 @@ class CredRevokedResultSchema(OpenAPISchema): @match_info_schema(HolderCredIdMatchInfoSchema()) @response_schema(IndyCredInfoSchema(), 200, description="") async def credentials_get(request: web.BaseRequest): - """ - Request handler for retrieving credential. + """Request handler for retrieving credential. Args: request: aiohttp request object @@ -222,8 +221,7 @@ async def credentials_get(request: web.BaseRequest): @querystring_schema(CredRevokedQueryStringSchema()) @response_schema(CredRevokedResultSchema(), 200, description="") async def credentials_revoked(request: web.BaseRequest): - """ - Request handler for querying revocation status of credential. + """Request handler for querying revocation status of credential. Args: request: aiohttp request object @@ -266,8 +264,7 @@ async def credentials_revoked(request: web.BaseRequest): @match_info_schema(HolderCredIdMatchInfoSchema()) @response_schema(AttributeMimeTypesResultSchema(), 200, description="") async def credentials_attr_mime_types_get(request: web.BaseRequest): - """ - Request handler for getting credential attribute MIME types. + """Request handler for getting credential attribute MIME types. Args: request: aiohttp request object @@ -289,8 +286,7 @@ async def credentials_attr_mime_types_get(request: web.BaseRequest): @match_info_schema(HolderCredIdMatchInfoSchema()) @response_schema(HolderModuleResponseSchema(), description="") async def credentials_remove(request: web.BaseRequest): - """ - Request handler for searching connection records. + """Request handler for searching connection records. Args: request: aiohttp request object @@ -321,8 +317,7 @@ async def credentials_remove(request: web.BaseRequest): @querystring_schema(CredentialsListQueryStringSchema()) @response_schema(CredInfoListSchema(), 200, description="") async def credentials_list(request: web.BaseRequest): - """ - Request handler for searching credential records. + """Request handler for searching credential records. Args: request: aiohttp request object @@ -360,8 +355,7 @@ async def credentials_list(request: web.BaseRequest): @match_info_schema(HolderCredIdMatchInfoSchema()) @response_schema(VCRecordSchema(), 200, description="") async def w3c_cred_get(request: web.BaseRequest): - """ - Request handler for retrieving W3C credential. + """Request handler for retrieving W3C credential. Args: request: aiohttp request object @@ -392,8 +386,7 @@ async def w3c_cred_get(request: web.BaseRequest): @match_info_schema(HolderCredIdMatchInfoSchema()) @response_schema(HolderModuleResponseSchema(), 200, description="") async def w3c_cred_remove(request: web.BaseRequest): - """ - Request handler for deleting W3C credential. + """Request handler for deleting W3C credential. Args: request: aiohttp request object @@ -430,8 +423,7 @@ async def w3c_cred_remove(request: web.BaseRequest): @querystring_schema(CredentialsListQueryStringSchema()) @response_schema(VCRecordListSchema(), 200, description="") async def w3c_creds_list(request: web.BaseRequest): - """ - Request handler for searching W3C credential records. + """Request handler for searching W3C credential records. Args: request: aiohttp request object diff --git a/aries_cloudagent/holder/tests/test_routes.py b/aries_cloudagent/holder/tests/test_routes.py index edef758fba..ad92934be5 100644 --- a/aries_cloudagent/holder/tests/test_routes.py +++ b/aries_cloudagent/holder/tests/test_routes.py @@ -2,14 +2,10 @@ from asynctest import mock as async_mock, TestCase as AsyncTestCase -from ...config.injection_context import InjectionContext from ...core.in_memory import InMemoryProfile from ...ledger.base import BaseLedger -from ...wallet.base import BaseWallet -from ...admin.request_context import AdminRequestContext from ...indy.holder import IndyHolder -from ...ledger.base import BaseLedger from ...storage.vc_holder.base import VCHolder from ...storage.vc_holder.vc_record import VCRecord diff --git a/aries_cloudagent/indy/credx/holder.py b/aries_cloudagent/indy/credx/holder.py index 2660528712..d593838319 100644 --- a/aries_cloudagent/indy/credx/holder.py +++ b/aries_cloudagent/indy/credx/holder.py @@ -54,8 +54,7 @@ class IndyCredxHolder(IndyHolder): LINK_SECRET_ID = "default" def __init__(self, profile: AskarProfile): - """ - Initialize an IndyCredxHolder instance. + """Initialize an IndyCredxHolder instance. Args: profile: The active profile instance @@ -107,8 +106,7 @@ async def get_link_secret(self) -> LinkSecret: async def create_credential_request( self, credential_offer: dict, credential_definition: dict, holder_did: str ) -> Tuple[str, str]: - """ - Create a credential request for the given credential offer. + """Create a credential request for the given credential offer. Args: credential_offer: The credential offer to create request for @@ -158,8 +156,7 @@ async def store_credential( credential_id: str = None, rev_reg_def: dict = None, ) -> str: - """ - Store a credential in the wallet. + """Store a credential in the wallet. Args: credential_definition: Credential definition for this credential @@ -242,8 +239,7 @@ async def store_credential( return credential_id async def get_credentials(self, start: int, count: int, wql: dict): - """ - Get credentials stored in the wallet. + """Get credentials stored in the wallet. Args: start: Starting index @@ -280,8 +276,7 @@ async def get_credentials_for_presentation_request_by_referent( count: int, extra_query: dict = {}, ): - """ - Get credentials stored in the wallet. + """Get credentials stored in the wallet. Args: presentation_request: Valid presentation request from issuer @@ -320,7 +315,7 @@ async def get_credentials_for_presentation_request_by_referent( else: raise IndyHolderError(f"Unknown presentation request referent: {reft}") - tag_filter = {"$exist": list(f"attr::{name}::value" for name in names)} + tag_filter = {"$exist": [f"attr::{name}::value" for name in names]} if restr: # FIXME check if restr is a list or dict? validate WQL format tag_filter = {"$and": [tag_filter] + restr} @@ -353,8 +348,7 @@ async def get_credentials_for_presentation_request_by_referent( return list(creds.values()) async def get_credential(self, credential_id: str) -> str: - """ - Get a credential stored in the wallet. + """Get a credential stored in the wallet. Args: credential_id: Credential id to retrieve @@ -384,8 +378,7 @@ async def _get_credential(self, credential_id: str) -> Credential: async def credential_revoked( self, ledger: BaseLedger, credential_id: str, fro: int = None, to: int = None ) -> bool: - """ - Check ledger for revocation status of credential by cred id. + """Check ledger for revocation status of credential by cred id. Args: credential_id: Credential id to check @@ -406,8 +399,7 @@ async def credential_revoked( return False async def delete_credential(self, credential_id: str): - """ - Remove a credential stored in the wallet. + """Remove a credential stored in the wallet. Args: credential_id: Credential id to remove @@ -428,8 +420,7 @@ async def delete_credential(self, credential_id: str): async def get_mime_type( self, credential_id: str, attr: str = None ) -> Union[dict, str]: - """ - Get MIME type per attribute (or for all attributes). + """Get MIME type per attribute (or for all attributes). Args: credential_id: credential id @@ -459,8 +450,7 @@ async def create_presentation( credential_definitions: dict, rev_states: dict = None, ) -> str: - """ - Get credentials stored in the wallet. + """Get credentials stored in the wallet. Args: presentation_request: Valid indy format presentation request @@ -547,8 +537,7 @@ async def create_revocation_state( timestamp: int, tails_file_path: str, ) -> str: - """ - Create current revocation state for a received credential. + """Create current revocation state for a received credential. Args: cred_rev_id: credential revocation id in revocation registry diff --git a/aries_cloudagent/indy/credx/issuer.py b/aries_cloudagent/indy/credx/issuer.py index 26e3a2c890..6150d9d9ca 100644 --- a/aries_cloudagent/indy/credx/issuer.py +++ b/aries_cloudagent/indy/credx/issuer.py @@ -47,8 +47,7 @@ class IndyCredxIssuer(IndyIssuer): """Indy-Credx issuer class.""" def __init__(self, profile: AskarProfile): - """ - Initialize an IndyCredxIssuer instance. + """Initialize an IndyCredxIssuer instance. Args: profile: The active profile instance @@ -68,8 +67,7 @@ async def create_schema( schema_version: str, attribute_names: Sequence[str], ) -> Tuple[str, str]: - """ - Create a new credential schema and store it in the wallet. + """Create a new credential schema and store it in the wallet. Args: origin_did: the DID issuing the credential definition @@ -98,8 +96,7 @@ async def create_schema( async def credential_definition_in_wallet( self, credential_definition_id: str ) -> bool: - """ - Check whether a given credential definition ID is present in the wallet. + """Check whether a given credential definition ID is present in the wallet. Args: credential_definition_id: The credential definition ID to check @@ -122,8 +119,7 @@ async def create_and_store_credential_definition( tag: str = None, support_revocation: bool = False, ) -> Tuple[str, str]: - """ - Create a new credential definition and store it in the wallet. + """Create a new credential definition and store it in the wallet. Args: origin_did: the DID issuing the credential definition @@ -178,8 +174,7 @@ async def create_and_store_credential_definition( return (cred_def_id, cred_def_json) async def create_credential_offer(self, credential_definition_id: str) -> str: - """ - Create a credential offer for the given credential definition id. + """Create a credential offer for the given credential definition id. Args: credential_definition_id: The credential definition to create an offer for @@ -227,10 +222,9 @@ async def create_credential( revoc_reg_id: str = None, tails_file_path: str = None, ) -> Tuple[str, str]: - """ - Create a credential. + """Create a credential. - Args + Args: schema: Schema to create credential for credential_offer: Credential Offer to create credential for credential_request: Credential request to create credential for @@ -367,8 +361,7 @@ async def revoke_credentials( tails_file_path: str, cred_revoc_ids: Sequence[str], ) -> Tuple[str, Sequence[str]]: - """ - Revoke a set of credentials in a revocation registry. + """Revoke a set of credentials in a revocation registry. Args: cred_def_id: ID of the credential definition @@ -538,8 +531,7 @@ async def revoke_credentials( async def merge_revocation_registry_deltas( self, fro_delta: str, to_delta: str ) -> str: - """ - Merge revocation registry deltas. + """Merge revocation registry deltas. Args: fro_delta: original delta in JSON format @@ -573,8 +565,7 @@ async def create_and_store_revocation_registry( max_cred_num: int, tails_base_path: str, ) -> Tuple[str, str, str]: - """ - Create a new revocation registry and store it in the wallet. + """Create a new revocation registry and store it in the wallet. Args: origin_did: the DID issuing the revocation registry diff --git a/aries_cloudagent/indy/credx/verifier.py b/aries_cloudagent/indy/credx/verifier.py index a0945ef035..0911009144 100644 --- a/aries_cloudagent/indy/credx/verifier.py +++ b/aries_cloudagent/indy/credx/verifier.py @@ -18,8 +18,7 @@ class IndyCredxVerifier(IndyVerifier): """Indy-Credx verifier class.""" def __init__(self, profile: Profile): - """ - Initialize an IndyCredxVerifier instance. + """Initialize an IndyCredxVerifier instance. Args: profile: an active profile instance @@ -36,8 +35,7 @@ async def verify_presentation( rev_reg_defs, rev_reg_entries, ) -> Tuple[bool, list]: - """ - Verify a presentation. + """Verify a presentation. Args: pres_req: Presentation request data diff --git a/aries_cloudagent/indy/holder.py b/aries_cloudagent/indy/holder.py index 5cd9a2a249..ad0f8dbc3b 100644 --- a/aries_cloudagent/indy/holder.py +++ b/aries_cloudagent/indy/holder.py @@ -18,8 +18,7 @@ class IndyHolder(ABC, metaclass=ABCMeta): CHUNK = 256 def __repr__(self) -> str: - """ - Return a human readable representation of this class. + """Return a human readable representation of this class. Returns: A human readable string for this class @@ -29,8 +28,7 @@ def __repr__(self) -> str: @abstractmethod async def get_credential(self, credential_id: str) -> str: - """ - Get a credential stored in the wallet. + """Get a credential stored in the wallet. Args: credential_id: Credential id to retrieve @@ -41,8 +39,7 @@ async def get_credential(self, credential_id: str) -> str: async def credential_revoked( self, ledger: BaseLedger, credential_id: str, fro: int = None, to: int = None ) -> bool: - """ - Check ledger for revocation status of credential by cred id. + """Check ledger for revocation status of credential by cred id. Args: credential_id: Credential id to check @@ -51,8 +48,7 @@ async def credential_revoked( @abstractmethod async def delete_credential(self, credential_id: str): - """ - Remove a credential stored in the wallet. + """Remove a credential stored in the wallet. Args: credential_id: Credential id to remove @@ -63,8 +59,7 @@ async def delete_credential(self, credential_id: str): async def get_mime_type( self, credential_id: str, attr: str = None ) -> Union[dict, str]: - """ - Get MIME type per attribute (or for all attributes). + """Get MIME type per attribute (or for all attributes). Args: credential_id: credential id @@ -84,8 +79,7 @@ async def create_presentation( credential_definitions: dict, rev_states: dict = None, ) -> str: - """ - Get credentials stored in the wallet. + """Get credentials stored in the wallet. Args: presentation_request: Valid indy format presentation request @@ -99,8 +93,7 @@ async def create_presentation( async def create_credential_request( self, credential_offer: dict, credential_definition: dict, holder_did: str ) -> Tuple[str, str]: - """ - Create a credential request for the given credential offer. + """Create a credential request for the given credential offer. Args: credential_offer: The credential offer to create request for @@ -122,8 +115,7 @@ async def store_credential( credential_id: str = None, rev_reg_def: dict = None, ): - """ - Store a credential in the wallet. + """Store a credential in the wallet. Args: credential_definition: Credential definition for this credential @@ -149,8 +141,7 @@ async def create_revocation_state( timestamp: int, tails_file_path: str, ) -> str: - """ - Create current revocation state for a received credential. + """Create current revocation state for a received credential. Args: cred_rev_id: credential revocation id in revocation registry diff --git a/aries_cloudagent/indy/issuer.py b/aries_cloudagent/indy/issuer.py index 3cf4990037..d97863737d 100644 --- a/aries_cloudagent/indy/issuer.py +++ b/aries_cloudagent/indy/issuer.py @@ -22,8 +22,7 @@ class IndyIssuer(ABC, metaclass=ABCMeta): """Base class for Indy Issuer.""" def __repr__(self) -> str: - """ - Return a human readable representation of this class. + """Return a human readable representation of this class. Returns: A human readable string for this class @@ -45,8 +44,7 @@ async def create_schema( schema_version: str, attribute_names: Sequence[str], ) -> Tuple[str, str]: - """ - Create a new credential schema and store it in the wallet. + """Create a new credential schema and store it in the wallet. Args: origin_did: the DID issuing the credential definition @@ -71,8 +69,7 @@ def make_credential_definition_id( async def credential_definition_in_wallet( self, credential_definition_id: str ) -> bool: - """ - Check whether a given credential definition ID is present in the wallet. + """Check whether a given credential definition ID is present in the wallet. Args: credential_definition_id: The credential definition ID to check @@ -87,8 +84,7 @@ async def create_and_store_credential_definition( tag: str = None, support_revocation: bool = False, ) -> Tuple[str, str]: - """ - Create a new credential definition and store it in the wallet. + """Create a new credential definition and store it in the wallet. Args: origin_did: the DID issuing the credential definition @@ -104,8 +100,7 @@ async def create_and_store_credential_definition( @abstractmethod async def create_credential_offer(self, credential_definition_id) -> str: - """ - Create a credential offer for the given credential definition id. + """Create a credential offer for the given credential definition id. Args: credential_definition_id: The credential definition to create an offer for @@ -125,10 +120,9 @@ async def create_credential( revoc_reg_id: str = None, tails_file_path: str = None, ) -> Tuple[str, str]: - """ - Create a credential. + """Create a credential. - Args + Args: schema: Schema to create credential for credential_offer: Credential Offer to create credential for credential_request: Credential request to create credential for @@ -149,8 +143,7 @@ async def revoke_credentials( tails_file_path: str, cred_rev_ids: Sequence[str], ) -> Tuple[str, Sequence[str]]: - """ - Revoke a set of credentials in a revocation registry. + """Revoke a set of credentials in a revocation registry. Args: cred_def_id: ID of the credential definition @@ -173,8 +166,7 @@ async def create_and_store_revocation_registry( max_cred_num: int, tails_base_path: str, ) -> Tuple[str, str, str]: - """ - Create a new revocation registry and store it in the wallet. + """Create a new revocation registry and store it in the wallet. Args: origin_did: the DID issuing the revocation registry @@ -193,8 +185,7 @@ async def create_and_store_revocation_registry( async def merge_revocation_registry_deltas( self, fro_delta: str, to_delta: str ) -> str: - """ - Merge revocation registry deltas. + """Merge revocation registry deltas. Args: fro_delta: original delta in JSON format diff --git a/aries_cloudagent/indy/models/cred_abstract.py b/aries_cloudagent/indy/models/cred_abstract.py index c76bcfe354..9abdbd5bb3 100644 --- a/aries_cloudagent/indy/models/cred_abstract.py +++ b/aries_cloudagent/indy/models/cred_abstract.py @@ -98,8 +98,7 @@ def __init__( key_correctness_proof: str = None, **kwargs, ): - """ - Initialize indy cred abstract object. + """Initialize indy cred abstract object. Args: schema_id: schema identifier diff --git a/aries_cloudagent/indy/models/predicate.py b/aries_cloudagent/indy/models/predicate.py index ac80e037fa..29278ad036 100644 --- a/aries_cloudagent/indy/models/predicate.py +++ b/aries_cloudagent/indy/models/predicate.py @@ -70,8 +70,7 @@ def get(relation: str) -> "Predicate": @staticmethod def to_int(value: Any) -> int: - """ - Cast a value as its equivalent int for indy predicate argument. + """Cast a value as its equivalent int for indy predicate argument. Raise ValueError for any input but int, stringified int, or boolean. diff --git a/aries_cloudagent/indy/models/pres_preview.py b/aries_cloudagent/indy/models/pres_preview.py index d2cc78d3ae..678ffebfa1 100644 --- a/aries_cloudagent/indy/models/pres_preview.py +++ b/aries_cloudagent/indy/models/pres_preview.py @@ -46,8 +46,7 @@ def __init__( threshold: int, **kwargs, ): - """ - Initialize preview object. + """Initialize preview object. Args: name: attribute name @@ -135,8 +134,7 @@ def __init__( referent: str = None, **kwargs, ): - """ - Initialize attribute specification object. + """Initialize attribute specification object. Args: name: attribute name @@ -157,8 +155,7 @@ def __init__( @staticmethod def list_plain(plain: dict, cred_def_id: str, referent: str = None): - """ - Return a list of `IndyPresAttrSpec` on input cred def id. + """Return a list of `IndyPresAttrSpec` on input cred def id. Args: plain: dict mapping names to values @@ -275,8 +272,7 @@ def __init__( predicates: Sequence[IndyPresPredSpec] = None, **kwargs, ): - """ - Initialize presentation preview object. + """Initialize presentation preview object. Args: _type: formalism for Marshmallow model creation: ignored @@ -295,8 +291,7 @@ def _type(self): return DIDCommPrefix.qualify_current(IndyPresPreview.Meta.message_type) def has_attr_spec(self, cred_def_id: str, name: str, value: str) -> bool: - """ - Return whether preview contains given attribute specification. + """Return whether preview contains given attribute specification. Args: cred_def_id: credential definition identifier @@ -323,8 +318,7 @@ async def indy_proof_request( nonce: str = None, non_revoc_intervals: Mapping[str, IndyNonRevocationInterval] = None, ) -> dict: - """ - Return indy proof request corresponding to presentation preview. + """Return indy proof request corresponding to presentation preview. Typically the verifier turns the proof preview into a proof request. diff --git a/aries_cloudagent/indy/models/proof_request.py b/aries_cloudagent/indy/models/proof_request.py index 03a1a955db..d73c3ff026 100644 --- a/aries_cloudagent/indy/models/proof_request.py +++ b/aries_cloudagent/indy/models/proof_request.py @@ -93,8 +93,7 @@ class IndyProofReqAttrSpecSchema(OpenAPISchema): @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields. + """Validate schema fields. Data must have exactly one of name or names; if names then restrictions are mandatory. @@ -206,8 +205,7 @@ def __init__( non_revoked: Mapping = None, **kwargs, ): - """ - Initialize indy cred abstract object. + """Initialize indy cred abstract object. Args: schema_id: schema identifier diff --git a/aries_cloudagent/indy/models/tests/test_cred_precis.py b/aries_cloudagent/indy/models/tests/test_cred_precis.py index 3a025a7a82..e7a13ab76a 100644 --- a/aries_cloudagent/indy/models/tests/test_cred_precis.py +++ b/aries_cloudagent/indy/models/tests/test_cred_precis.py @@ -1,6 +1,6 @@ from unittest import TestCase -from ..cred_precis import IndyCredInfo, IndyCredInfoSchema +from ..cred_precis import IndyCredInfo TEST_DID = "LjgpST2rjsoxYegQDRm7EL" SCHEMA_NAME = "preferences" diff --git a/aries_cloudagent/indy/models/tests/test_non_rev_interval.py b/aries_cloudagent/indy/models/tests/test_non_rev_interval.py index bf80447e35..a6f823bd6f 100644 --- a/aries_cloudagent/indy/models/tests/test_non_rev_interval.py +++ b/aries_cloudagent/indy/models/tests/test_non_rev_interval.py @@ -1,9 +1,5 @@ from unittest import TestCase -from asynctest import TestCase as AsyncTestCase -from asynctest import mock as async_mock - -import pytest from ..non_rev_interval import IndyNonRevocationInterval diff --git a/aries_cloudagent/indy/models/tests/test_proof.py b/aries_cloudagent/indy/models/tests/test_proof.py index 195894798f..252db5d17a 100644 --- a/aries_cloudagent/indy/models/tests/test_proof.py +++ b/aries_cloudagent/indy/models/tests/test_proof.py @@ -1,6 +1,6 @@ from unittest import TestCase -from ..proof import IndyProof, IndyPrimaryProof +from ..proof import IndyProof INDY_PROOF = { "proof": { diff --git a/aries_cloudagent/indy/models/tests/test_proof_request.py b/aries_cloudagent/indy/models/tests/test_proof_request.py index a6bb8503c4..4e16e381b4 100644 --- a/aries_cloudagent/indy/models/tests/test_proof_request.py +++ b/aries_cloudagent/indy/models/tests/test_proof_request.py @@ -1,6 +1,5 @@ from unittest import TestCase -from ..non_rev_interval import IndyNonRevocationInterval from ..proof_request import IndyProofRequest TEST_DID = "LjgpST2rjsoxYegQDRm7EL" diff --git a/aries_cloudagent/indy/models/xform.py b/aries_cloudagent/indy/models/xform.py index afcb635fe2..f15587abf4 100644 --- a/aries_cloudagent/indy/models/xform.py +++ b/aries_cloudagent/indy/models/xform.py @@ -11,8 +11,7 @@ async def indy_proof_req_preview2indy_requested_creds( *, holder: IndyHolder, ): - """ - Build indy requested-credentials structure. + """Build indy requested-credentials structure. Given input proof request and presentation preview, use credentials in holder's wallet to build indy requested credentials structure for input diff --git a/aries_cloudagent/indy/sdk/holder.py b/aries_cloudagent/indy/sdk/holder.py index efb1a4f3ba..4152f82f11 100644 --- a/aries_cloudagent/indy/sdk/holder.py +++ b/aries_cloudagent/indy/sdk/holder.py @@ -29,8 +29,7 @@ class IndySdkHolder(IndyHolder): """Indy-SDK holder implementation.""" def __init__(self, wallet: IndyOpenWallet): - """ - Initialize an IndyHolder instance. + """Initialize an IndyHolder instance. Args: wallet: IndyOpenWallet instance @@ -41,8 +40,7 @@ def __init__(self, wallet: IndyOpenWallet): async def create_credential_request( self, credential_offer: dict, credential_definition: dict, holder_did: str ) -> Tuple[str, str]: - """ - Create a credential request for the given credential offer. + """Create a credential request for the given credential offer. Args: credential_offer: The credential offer to create request for @@ -86,8 +84,7 @@ async def store_credential( credential_id: str = None, rev_reg_def: dict = None, ) -> str: - """ - Store a credential in the wallet. + """Store a credential in the wallet. Args: credential_definition: Credential definition for this credential @@ -134,8 +131,7 @@ async def store_credential( return credential_id async def get_credentials(self, start: int, count: int, wql: dict): - """ - Get credentials stored in the wallet. + """Get credentials stored in the wallet. Args: start: Starting index @@ -191,8 +187,7 @@ async def get_credentials_for_presentation_request_by_referent( count: int, extra_query: dict = {}, ): - """ - Get credentials stored in the wallet. + """Get credentials stored in the wallet. Args: presentation_request: Valid presentation request from issuer @@ -267,24 +262,20 @@ async def fetch(reft, limit): cred["presentation_referents"] = list(cred["presentation_referents"]) creds_ordered = tuple( - [ - cred - for cred in sorted( - creds_dict.values(), - key=lambda c: ( - c["cred_info"]["rev_reg_id"] or "", # irrevocable 1st - c["cred_info"][ - "referent" - ], # should be descending by timestamp if we had it - ), - ) - ] + sorted( + creds_dict.values(), + key=lambda c: ( + c["cred_info"]["rev_reg_id"] or "", # irrevocable 1st + c["cred_info"][ + "referent" + ], # should be descending by timestamp if we had it + ), + ) )[:count] return creds_ordered async def get_credential(self, credential_id: str) -> str: - """ - Get a credential stored in the wallet. + """Get a credential stored in the wallet. Args: credential_id: Credential id to retrieve @@ -313,8 +304,7 @@ async def get_credential(self, credential_id: str) -> str: async def credential_revoked( self, ledger: BaseLedger, credential_id: str, fro: int = None, to: int = None ) -> bool: - """ - Check ledger for revocation status of credential by cred id. + """Check ledger for revocation status of credential by cred id. Args: credential_id: Credential id to check @@ -336,8 +326,7 @@ async def credential_revoked( return False async def delete_credential(self, credential_id: str): - """ - Remove a credential stored in the wallet. + """Remove a credential stored in the wallet. Args: credential_id: Credential id to remove @@ -372,8 +361,7 @@ async def delete_credential(self, credential_id: str): async def get_mime_type( self, credential_id: str, attr: str = None ) -> Union[dict, str]: - """ - Get MIME type per attribute (or for all attributes). + """Get MIME type per attribute (or for all attributes). Args: credential_id: credential id @@ -401,8 +389,7 @@ async def create_presentation( credential_definitions: dict, rev_states: dict = None, ) -> str: - """ - Get credentials stored in the wallet. + """Get credentials stored in the wallet. Args: presentation_request: Valid indy format presentation request @@ -456,8 +443,7 @@ async def create_revocation_state( timestamp: int, tails_file_path: str, ) -> str: - """ - Create current revocation state for a received credential. + """Create current revocation state for a received credential. Args: cred_rev_id: credential revocation id in revocation registry diff --git a/aries_cloudagent/indy/sdk/issuer.py b/aries_cloudagent/indy/sdk/issuer.py index d425980766..8ac62b8637 100644 --- a/aries_cloudagent/indy/sdk/issuer.py +++ b/aries_cloudagent/indy/sdk/issuer.py @@ -30,8 +30,7 @@ class IndySdkIssuer(IndyIssuer): """Indy-SDK issuer implementation.""" def __init__(self, profile: IndySdkProfile): - """ - Initialize an IndyIssuer instance. + """Initialize an IndyIssuer instance. Args: profile: IndySdkProfile instance @@ -46,8 +45,7 @@ async def create_schema( schema_version: str, attribute_names: Sequence[str], ) -> Tuple[str, str]: - """ - Create a new credential schema. + """Create a new credential schema. Args: origin_did: the DID issuing the credential definition @@ -72,8 +70,7 @@ async def create_schema( async def credential_definition_in_wallet( self, credential_definition_id: str ) -> bool: - """ - Check whether a given credential definition ID is present in the wallet. + """Check whether a given credential definition ID is present in the wallet. Args: credential_definition_id: The credential definition ID to check @@ -104,8 +101,7 @@ async def create_and_store_credential_definition( tag: str = None, support_revocation: bool = False, ) -> Tuple[str, str]: - """ - Create a new credential definition and store it in the wallet. + """Create a new credential definition and store it in the wallet. Args: origin_did: the DID issuing the credential definition @@ -136,8 +132,7 @@ async def create_and_store_credential_definition( return (credential_definition_id, credential_definition_json) async def create_credential_offer(self, credential_definition_id: str) -> str: - """ - Create a credential offer for the given credential definition id. + """Create a credential offer for the given credential definition id. Args: credential_definition_id: The credential definition to create an offer for @@ -164,10 +159,9 @@ async def create_credential( rev_reg_id: str = None, tails_file_path: str = None, ) -> Tuple[str, str]: - """ - Create a credential. + """Create a credential. - Args + Args: schema: Schema to create credential for credential_offer: Credential Offer to create credential for credential_request: Credential request to create credential for @@ -249,8 +243,7 @@ async def revoke_credentials( tails_file_path: str, cred_rev_ids: Sequence[str], ) -> Tuple[str, Sequence[str]]: - """ - Revoke a set of credentials in a revocation registry. + """Revoke a set of credentials in a revocation registry. Args: cred_def_id: ID of the credential definition @@ -320,8 +313,7 @@ async def revoke_credentials( async def merge_revocation_registry_deltas( self, fro_delta: str, to_delta: str ) -> str: - """ - Merge revocation registry deltas. + """Merge revocation registry deltas. Args: fro_delta: original delta in JSON format @@ -345,8 +337,7 @@ async def create_and_store_revocation_registry( max_cred_num: int, tails_base_path: str, ) -> Tuple[str, str, str]: - """ - Create a new revocation registry and store it in the wallet. + """Create a new revocation registry and store it in the wallet. Args: origin_did: the DID issuing the revocation registry diff --git a/aries_cloudagent/indy/sdk/profile.py b/aries_cloudagent/indy/sdk/profile.py index 1ea02c9051..71b6530b38 100644 --- a/aries_cloudagent/indy/sdk/profile.py +++ b/aries_cloudagent/indy/sdk/profile.py @@ -144,8 +144,7 @@ def session(self, context: InjectionContext = None) -> "ProfileSession": return IndySdkProfileSession(self, context=context) def transaction(self, context: InjectionContext = None) -> "ProfileSession": - """ - Start a new interactive session with commit and rollback support. + """Start a new interactive session with commit and rollback support. If the current backend does not support transactions, then commit and rollback operations of the session will not have any effect. diff --git a/aries_cloudagent/indy/sdk/tests/test_profile.py b/aries_cloudagent/indy/sdk/tests/test_profile.py index 8ebd62dfb9..9440adc605 100644 --- a/aries_cloudagent/indy/sdk/tests/test_profile.py +++ b/aries_cloudagent/indy/sdk/tests/test_profile.py @@ -1,4 +1,3 @@ -import asyncio import logging from asynctest import mock as async_mock diff --git a/aries_cloudagent/indy/sdk/tests/test_wallet_plugin.py b/aries_cloudagent/indy/sdk/tests/test_wallet_plugin.py index d683e7b215..ab5e9dea96 100644 --- a/aries_cloudagent/indy/sdk/tests/test_wallet_plugin.py +++ b/aries_cloudagent/indy/sdk/tests/test_wallet_plugin.py @@ -1,10 +1,5 @@ -import pytest - from asynctest import mock as async_mock, TestCase as AsyncTestCase -from ....ledger.base import BaseLedger -from ....wallet.base import BaseWallet -from ....wallet.did_info import DIDInfo from .. import wallet_plugin as test_module diff --git a/aries_cloudagent/indy/sdk/verifier.py b/aries_cloudagent/indy/sdk/verifier.py index c501932e24..81bdc5a601 100644 --- a/aries_cloudagent/indy/sdk/verifier.py +++ b/aries_cloudagent/indy/sdk/verifier.py @@ -19,8 +19,7 @@ class IndySdkVerifier(IndyVerifier): """Indy-SDK verifier implementation.""" def __init__(self, profile: Profile): - """ - Initialize an IndyVerifier instance. + """Initialize an IndyVerifier instance. Args: profile: Active Profile instance @@ -37,8 +36,7 @@ async def verify_presentation( rev_reg_defs, rev_reg_entries, ) -> Tuple[bool, list]: - """ - Verify a presentation. + """Verify a presentation. Args: pres_req: Presentation request data diff --git a/aries_cloudagent/indy/sdk/wallet_setup.py b/aries_cloudagent/indy/sdk/wallet_setup.py index 280f7abdc9..59e8dc3921 100644 --- a/aries_cloudagent/indy/sdk/wallet_setup.py +++ b/aries_cloudagent/indy/sdk/wallet_setup.py @@ -85,8 +85,7 @@ def wallet_access(self) -> dict: return ret async def create_wallet(self) -> "IndyOpenWallet": - """ - Create a new wallet. + """Create a new wallet. Raises: ProfileDuplicateError: If there was an existing wallet with the same name @@ -125,8 +124,7 @@ async def create_wallet(self) -> "IndyOpenWallet": ) from err async def remove_wallet(self): - """ - Remove an existing wallet. + """Remove an existing wallet. Raises: ProfileNotFoundError: If the wallet could not be found @@ -150,8 +148,7 @@ async def remove_wallet(self): ) from x_indy async def open_wallet(self, created: bool = False) -> "IndyOpenWallet": - """ - Open wallet, removing and/or creating it if so configured. + """Open wallet, removing and/or creating it if so configured. Raises: ProfileError: If wallet not found after creation diff --git a/aries_cloudagent/indy/util.py b/aries_cloudagent/indy/util.py index 2c9a126c46..480e2f9652 100644 --- a/aries_cloudagent/indy/util.py +++ b/aries_cloudagent/indy/util.py @@ -13,8 +13,7 @@ async def generate_pr_nonce() -> str: def indy_client_dir(subpath: str = None, create: bool = False) -> str: - """ - Return '/'-terminated subdirectory of indy-client directory. + """Return '/'-terminated subdirectory of indy-client directory. Args: subpath: subpath within indy-client structure diff --git a/aries_cloudagent/indy/verifier.py b/aries_cloudagent/indy/verifier.py index 76eca04051..0b7dd5f536 100644 --- a/aries_cloudagent/indy/verifier.py +++ b/aries_cloudagent/indy/verifier.py @@ -36,8 +36,7 @@ class IndyVerifier(ABC, metaclass=ABCMeta): """Base class for Indy Verifier.""" def __repr__(self) -> str: - """ - Return a human readable representation of this class. + """Return a human readable representation of this class. Returns: A human readable string for this class @@ -46,8 +45,7 @@ def __repr__(self) -> str: return "<{}>".format(self.__class__.__name__) def non_revoc_intervals(self, pres_req: dict, pres: dict, cred_defs: dict) -> list: - """ - Remove superfluous non-revocation intervals in presentation request. + """Remove superfluous non-revocation intervals in presentation request. Irrevocable credentials constitute proof of non-revocation, but indy rejects proof requests with non-revocation intervals lining up @@ -114,8 +112,7 @@ async def check_timestamps( pres: Mapping, rev_reg_defs: Mapping, ) -> list: - """ - Check for suspicious, missing, and superfluous timestamps. + """Check for suspicious, missing, and superfluous timestamps. Raises ValueError on timestamp in the future, prior to rev reg creation, superfluous or missing. @@ -289,8 +286,7 @@ async def check_timestamps( return msgs async def pre_verify(self, pres_req: dict, pres: dict) -> list: - """ - Check for essential components and tampering in presentation. + """Check for essential components and tampering in presentation. Visit encoded attribute values against raw, and predicate bounds, in presentation, cross-reference against presentation request. @@ -398,8 +394,7 @@ def verify_presentation( rev_reg_defs, rev_reg_entries, ) -> Tuple[bool, list]: - """ - Verify a presentation. + """Verify a presentation. Args: presentation_request: Presentation request data diff --git a/aries_cloudagent/ledger/base.py b/aries_cloudagent/ledger/base.py index cbde6f8b7c..8d39aa0a23 100644 --- a/aries_cloudagent/ledger/base.py +++ b/aries_cloudagent/ledger/base.py @@ -27,8 +27,7 @@ class BaseLedger(ABC, metaclass=ABCMeta): BACKEND_NAME: str = None async def __aenter__(self) -> "BaseLedger": - """ - Context manager entry. + """Context manager entry. Returns: The current instance @@ -139,8 +138,7 @@ async def register_nym( write_ledger: bool = True, endorser_did: str = None, ) -> Tuple[bool, dict]: - """ - Register a nym on the ledger. + """Register a nym on the ledger. Args: did: DID to register on the ledger. @@ -151,8 +149,7 @@ async def register_nym( @abstractmethod async def get_nym_role(self, did: str): - """ - Return the role registered to input public DID on the ledger. + """Return the role registered to input public DID on the ledger. Args: did: DID to register on the ledger. @@ -164,8 +161,7 @@ def nym_to_did(self, nym: str) -> str: @abstractmethod async def rotate_public_did_keypair(self, next_seed: str = None) -> None: - """ - Rotate keypair for public DID: create new key, submit to ledger, update wallet. + """Rotate keypair for public DID: create new key, submit to ledger, update wallet. Args: next_seed: seed for incoming ed25519 keypair (default random) @@ -226,8 +222,7 @@ async def txn_submit( @abstractmethod async def fetch_schema_by_id(self, schema_id: str) -> dict: - """ - Get schema from ledger. + """Get schema from ledger. Args: schema_id: The schema id (or stringified sequence number) to retrieve @@ -239,8 +234,7 @@ async def fetch_schema_by_id(self, schema_id: str) -> dict: @abstractmethod async def fetch_schema_by_seq_no(self, seq_no: int) -> dict: - """ - Fetch a schema by its sequence number. + """Fetch a schema by its sequence number. Args: seq_no: schema ledger sequence number @@ -281,8 +275,7 @@ async def create_and_send_schema( write_ledger: bool = True, endorser_did: str = None, ) -> Tuple[str, dict]: - """ - Send schema to ledger. + """Send schema to ledger. Args: issuer: The issuer instance to use for schema creation @@ -419,8 +412,7 @@ async def create_and_send_credential_definition( write_ledger: bool = True, endorser_did: str = None, ) -> Tuple[str, dict, bool]: - """ - Send credential definition to ledger and store relevant key matter in wallet. + """Send credential definition to ledger and store relevant key matter in wallet. Args: issuer: The issuer instance to use for credential definition creation @@ -535,8 +527,7 @@ async def _create_credential_definition_request( @abstractmethod async def get_credential_definition(self, credential_definition_id: str) -> dict: - """ - Get a credential definition from the cache if available, otherwise the ledger. + """Get a credential definition from the cache if available, otherwise the ledger. Args: credential_definition_id: The schema id of the schema to fetch cred def for @@ -551,8 +542,7 @@ async def get_revoc_reg_delta( @abstractmethod async def get_schema(self, schema_id: str) -> dict: - """ - Get a schema from the cache if available, otherwise fetch from the ledger. + """Get a schema from the cache if available, otherwise fetch from the ledger. Args: schema_id: The schema id (or stringified sequence number) to retrieve @@ -578,8 +568,7 @@ class Role(Enum): @staticmethod def get(token: Union[str, int] = None) -> "Role": - """ - Return enum instance corresponding to input token. + """Return enum instance corresponding to input token. Args: token: token identifying role to indy-sdk: @@ -599,8 +588,7 @@ def get(token: Union[str, int] = None) -> "Role": return None def to_indy_num_str(self) -> str: - """ - Return (typically, numeric) string value that indy-sdk associates with role. + """Return (typically, numeric) string value that indy-sdk associates with role. Recall that None signifies USER and "" signifies a role undergoing reset. """ diff --git a/aries_cloudagent/ledger/indy.py b/aries_cloudagent/ledger/indy.py index a127f8c028..34e216339a 100644 --- a/aries_cloudagent/ledger/indy.py +++ b/aries_cloudagent/ledger/indy.py @@ -99,8 +99,7 @@ def __init__( read_only: bool = False, socks_proxy: str = None, ): - """ - Initialize an IndySdkLedgerPool instance. + """Initialize an IndySdkLedgerPool instance. Args: name: The Indy pool ledger configuration name @@ -269,8 +268,7 @@ def __init__( pool: IndySdkLedgerPool, profile: "IndySdkProfile", ): - """ - Initialize an IndySdkLedger instance. + """Initialize an IndySdkLedger instance. Args: pool: The pool instance handling the raw ledger connection @@ -307,8 +305,7 @@ async def is_ledger_read_only(self) -> bool: return self.read_only async def __aenter__(self) -> "IndySdkLedger": - """ - Context manager entry. + """Context manager entry. Returns: The current instance @@ -357,8 +354,7 @@ async def _submit( sign_did: DIDInfo = sentinel, write_ledger: bool = True, ) -> str: - """ - Sign and submit request to ledger. + """Sign and submit request to ledger. Args: request_json: The json string to submit @@ -488,8 +484,7 @@ async def _create_schema_request( return request_json async def get_schema(self, schema_id: str) -> dict: - """ - Get a schema from the cache if available, otherwise fetch from the ledger. + """Get a schema from the cache if available, otherwise fetch from the ledger. Args: schema_id: The schema id (or stringified sequence number) to retrieve @@ -506,8 +501,7 @@ async def get_schema(self, schema_id: str) -> dict: return await self.fetch_schema_by_id(schema_id) async def fetch_schema_by_id(self, schema_id: str) -> dict: - """ - Get schema from ledger. + """Get schema from ledger. Args: schema_id: The schema id (or stringified sequence number) to retrieve @@ -547,8 +541,7 @@ async def fetch_schema_by_id(self, schema_id: str) -> dict: return parsed_response async def fetch_schema_by_seq_no(self, seq_no: int) -> dict: - """ - Fetch a schema by its sequence number. + """Fetch a schema by its sequence number. Args: seq_no: schema ledger sequence number @@ -599,8 +592,7 @@ async def _create_credential_definition_request( return request_json async def get_credential_definition(self, credential_definition_id: str) -> dict: - """ - Get a credential definition from the cache if available, otherwise the ledger. + """Get a credential definition from the cache if available, otherwise the ledger. Args: credential_definition_id: The schema id of the schema to fetch cred def for @@ -616,8 +608,7 @@ async def get_credential_definition(self, credential_definition_id: str) -> dict return await self.fetch_credential_definition(credential_definition_id) async def fetch_credential_definition(self, credential_definition_id: str) -> dict: - """ - Get a credential definition from the ledger by id. + """Get a credential definition from the ledger by id. Args: credential_definition_id: The cred def id of the cred def to fetch @@ -657,8 +648,7 @@ async def fetch_credential_definition(self, credential_definition_id: str) -> di return parsed_response async def credential_definition_id2schema_id(self, credential_definition_id): - """ - From a credential definition, get the identifier for its schema. + """From a credential definition, get the identifier for its schema. Args: credential_definition_id: The identifier of the credential definition @@ -817,8 +807,7 @@ async def register_nym( write_ledger: bool = True, endorser_did: str = None, ) -> Tuple[bool, dict]: - """ - Register a nym on the ledger. + """Register a nym on the ledger. Args: did: DID to register on the ledger. @@ -862,8 +851,7 @@ async def register_nym( return True, None async def get_nym_role(self, did: str) -> Role: - """ - Return the role of the input public DID's NYM on the ledger. + """Return the role of the input public DID's NYM on the ledger. Args: did: DID to query for role on the ledger. @@ -905,8 +893,7 @@ async def submit_get_nym_request(self, request_json: str) -> str: return response_json async def rotate_public_did_keypair(self, next_seed: str = None) -> None: - """ - Rotate keypair for public DID: create new key, submit to ledger, update wallet. + """Rotate keypair for public DID: create new key, submit to ledger, update wallet. Args: next_seed: seed for incoming ed25519 keypair (default random) @@ -1043,7 +1030,7 @@ async def get_latest_txn_author_acceptance(self) -> dict: tag_filter = {"pool_name": self.pool.name} found = await storage.find_all_records(TAA_ACCEPTED_RECORD_TYPE, tag_filter) if found: - records = list(json.loads(record.value) for record in found) + records = [json.loads(record.value) for record in found] records.sort(key=lambda v: v["time"], reverse=True) acceptance = records[0] else: @@ -1105,8 +1092,7 @@ async def get_revoc_reg_entry(self, revoc_reg_id: str, timestamp: int): async def get_revoc_reg_delta( self, revoc_reg_id: str, fro=0, to=None ) -> Tuple[dict, int]: - """ - Look up a revocation registry delta by ID. + """Look up a revocation registry delta by ID. :param revoc_reg_id revocation registry id :param fro earliest EPOCH time of interest diff --git a/aries_cloudagent/ledger/indy_vdr.py b/aries_cloudagent/ledger/indy_vdr.py index ef2e403a71..c6a3da3b1b 100644 --- a/aries_cloudagent/ledger/indy_vdr.py +++ b/aries_cloudagent/ledger/indy_vdr.py @@ -79,8 +79,7 @@ def __init__( read_only: bool = False, socks_proxy: str = None, ): - """ - Initialize an IndyLedger instance. + """Initialize an IndyLedger instance. Args: name: The pool ledger configuration name @@ -259,8 +258,7 @@ def __init__( pool: IndyVdrLedgerPool, profile: Profile, ): - """ - Initialize an IndyVdrLedger instance. + """Initialize an IndyVdrLedger instance. Args: pool: The pool instance handling the raw ledger connection @@ -297,8 +295,7 @@ async def is_ledger_read_only(self) -> bool: return self.read_only async def __aenter__(self) -> "IndyVdrLedger": - """ - Context manager entry. + """Context manager entry. Returns: The current instance @@ -321,8 +318,7 @@ async def _submit( sign_did: DIDInfo = sentinel, write_ledger: bool = True, ) -> dict: - """ - Sign and submit request to ledger. + """Sign and submit request to ledger. Args: request_json: The json string to submit @@ -398,8 +394,7 @@ async def _create_schema_request( return schema_req async def get_schema(self, schema_id: str) -> dict: - """ - Get a schema from the cache if available, otherwise fetch from the ledger. + """Get a schema from the cache if available, otherwise fetch from the ledger. Args: schema_id: The schema id (or stringified sequence number) to retrieve @@ -416,8 +411,7 @@ async def get_schema(self, schema_id: str) -> dict: return await self.fetch_schema_by_id(schema_id) async def fetch_schema_by_id(self, schema_id: str) -> dict: - """ - Get schema from ledger. + """Get schema from ledger. Args: schema_id: The schema id (or stringified sequence number) to retrieve @@ -463,8 +457,7 @@ async def fetch_schema_by_id(self, schema_id: str) -> dict: return schema_data async def fetch_schema_by_seq_no(self, seq_no: int) -> dict: - """ - Fetch a schema by its sequence number. + """Fetch a schema by its sequence number. Args: seq_no: schema ledger sequence number @@ -517,8 +510,7 @@ async def _create_credential_definition_request( return cred_def_req async def get_credential_definition(self, credential_definition_id: str) -> dict: - """ - Get a credential definition from the cache if available, otherwise the ledger. + """Get a credential definition from the cache if available, otherwise the ledger. Args: credential_definition_id: The schema id of the schema to fetch cred def for @@ -540,8 +532,7 @@ async def get_credential_definition(self, credential_definition_id: str) -> dict return await self.fetch_credential_definition(credential_definition_id) async def fetch_credential_definition(self, credential_definition_id: str) -> dict: - """ - Get a credential definition from the ledger by id. + """Get a credential definition from the ledger by id. Args: credential_definition_id: The cred def id of the cred def to fetch @@ -580,8 +571,7 @@ async def fetch_credential_definition(self, credential_definition_id: str) -> di } async def credential_definition_id2schema_id(self, credential_definition_id): - """ - From a credential definition, get the identifier for its schema. + """From a credential definition, get the identifier for its schema. Args: credential_definition_id: The identifier of the credential definition @@ -754,8 +744,7 @@ async def register_nym( write_ledger: bool = True, endorser_did: str = None, ) -> Tuple[bool, dict]: - """ - Register a nym on the ledger. + """Register a nym on the ledger. Args: did: DID to register on the ledger. @@ -799,8 +788,7 @@ async def register_nym( return True, None async def get_nym_role(self, did: str) -> Role: - """ - Return the role of the input public DID's NYM on the ledger. + """Return the role of the input public DID's NYM on the ledger. Args: did: DID to query for role on the ledger. @@ -843,8 +831,7 @@ async def submit_get_nym_request(self, request_json: str) -> str: return response_json async def rotate_public_did_keypair(self, next_seed: str = None) -> None: - """ - Rotate keypair for public DID: create new key, submit to ledger, update wallet. + """Rotate keypair for public DID: create new key, submit to ledger, update wallet. Args: next_seed: seed for incoming ed25519 keypair (default random) @@ -973,7 +960,7 @@ async def get_latest_txn_author_acceptance(self) -> dict: TAA_ACCEPTED_RECORD_TYPE, tag_filter ) if found: - records = list(json.loads(record.value) for record in found) + records = [json.loads(record.value) for record in found] records.sort(key=lambda v: v["time"], reverse=True) acceptance = records[0] else: @@ -1036,8 +1023,7 @@ async def get_revoc_reg_entry( async def get_revoc_reg_delta( self, revoc_reg_id: str, timestamp_from=0, timestamp_to=None ) -> Tuple[dict, int]: - """ - Look up a revocation registry delta by ID. + """Look up a revocation registry delta by ID. :param revoc_reg_id revocation registry id :param timestamp_from from time. a total number of seconds from Unix Epoch diff --git a/aries_cloudagent/ledger/merkel_validation/tests/test_trie.py b/aries_cloudagent/ledger/merkel_validation/tests/test_trie.py index c522b915bc..bf2f27f1da 100644 --- a/aries_cloudagent/ledger/merkel_validation/tests/test_trie.py +++ b/aries_cloudagent/ledger/merkel_validation/tests/test_trie.py @@ -1,12 +1,10 @@ -import json - from asynctest import TestCase from ..domain_txn_handler import ( prepare_for_state_read, get_proof_nodes, ) -from ..hasher import TreeHasher, HexTreeHasher +from ..hasher import HexTreeHasher from ..trie import SubTrie from ..merkel_verifier import MerkleVerifier diff --git a/aries_cloudagent/ledger/merkel_validation/tests/test_utils.py b/aries_cloudagent/ledger/merkel_validation/tests/test_utils.py index 94ad55a0ec..50ec93f492 100644 --- a/aries_cloudagent/ledger/merkel_validation/tests/test_utils.py +++ b/aries_cloudagent/ledger/merkel_validation/tests/test_utils.py @@ -1,5 +1,4 @@ """Tests for Merkel Validation Utils.""" -import json from unittest import TestCase diff --git a/aries_cloudagent/ledger/routes.py b/aries_cloudagent/ledger/routes.py index 952c350095..46aa2612fe 100644 --- a/aries_cloudagent/ledger/routes.py +++ b/aries_cloudagent/ledger/routes.py @@ -263,8 +263,7 @@ class WriteLedgerRequestSchema(OpenAPISchema): @querystring_schema(SchemaConnIdMatchInfoSchema()) @response_schema(TxnOrRegisterLedgerNymResponseSchema(), 200, description="") async def register_ledger_nym(request: web.BaseRequest): - """ - Request handler for registering a NYM with the ledger. + """Request handler for registering a NYM with the ledger. Args: request: aiohttp request object @@ -429,8 +428,7 @@ async def register_ledger_nym(request: web.BaseRequest): @querystring_schema(QueryStringDIDSchema) @response_schema(GetNymRoleResponseSchema(), 200, description="") async def get_nym_role(request: web.BaseRequest): - """ - Request handler for getting the role from the NYM registration of a public DID. + """Request handler for getting the role from the NYM registration of a public DID. Args: request: aiohttp request object @@ -476,8 +474,7 @@ async def get_nym_role(request: web.BaseRequest): @docs(tags=["ledger"], summary="Rotate key pair for public DID.") @response_schema(LedgerModulesResultSchema(), 200, description="") async def rotate_public_did_keypair(request: web.BaseRequest): - """ - Request handler for rotating key pair associated with public DID. + """Request handler for rotating key pair associated with public DID. Args: request: aiohttp request object @@ -506,8 +503,7 @@ async def rotate_public_did_keypair(request: web.BaseRequest): @querystring_schema(QueryStringDIDSchema()) @response_schema(GetDIDVerkeyResponseSchema(), 200, description="") async def get_did_verkey(request: web.BaseRequest): - """ - Request handler for getting a verkey for a DID from the ledger. + """Request handler for getting a verkey for a DID from the ledger. Args: request: aiohttp request object @@ -555,8 +551,7 @@ async def get_did_verkey(request: web.BaseRequest): @querystring_schema(QueryStringEndpointSchema()) @response_schema(GetDIDEndpointResponseSchema(), 200, description="") async def get_did_endpoint(request: web.BaseRequest): - """ - Request handler for getting a verkey for a DID from the ledger. + """Request handler for getting a verkey for a DID from the ledger. Args: request: aiohttp request object @@ -601,8 +596,7 @@ async def get_did_endpoint(request: web.BaseRequest): @docs(tags=["ledger"], summary="Fetch the current transaction author agreement, if any") @response_schema(TAAResultSchema, 200, description="") async def ledger_get_taa(request: web.BaseRequest): - """ - Request handler for fetching the transaction author agreement. + """Request handler for fetching the transaction author agreement. Args: request: aiohttp request object @@ -642,8 +636,7 @@ async def ledger_get_taa(request: web.BaseRequest): @request_schema(TAAAcceptSchema) @response_schema(LedgerModulesResultSchema(), 200, description="") async def ledger_accept_taa(request: web.BaseRequest): - """ - Request handler for accepting the current transaction author agreement. + """Request handler for accepting the current transaction author agreement. Args: request: aiohttp request object @@ -703,8 +696,7 @@ async def ledger_accept_taa(request: web.BaseRequest): @docs(tags=["ledger"], summary="Fetch list of available write ledgers") @response_schema(ConfigurableWriteLedgersSchema, 200, description="") async def get_write_ledgers(request: web.BaseRequest): - """ - Request handler for fetching the list of available write ledgers. + """Request handler for fetching the list of available write ledgers. Args: request: aiohttp request object @@ -725,8 +717,7 @@ async def get_write_ledgers(request: web.BaseRequest): @docs(tags=["ledger"], summary="Fetch the current write ledger") @response_schema(WriteLedgerSchema, 200, description="") async def get_write_ledger(request: web.BaseRequest): - """ - Request handler for fetching the currently set write ledger. + """Request handler for fetching the currently set write ledger. Args: request: aiohttp request object @@ -751,8 +742,7 @@ async def get_write_ledger(request: web.BaseRequest): @match_info_schema(WriteLedgerRequestSchema()) @response_schema(WriteLedgerSchema, 200, description="") async def set_write_ledger(request: web.BaseRequest): - """ - Request handler for setting write ledger. + """Request handler for setting write ledger. Args: request: aiohttp request object @@ -782,8 +772,7 @@ async def set_write_ledger(request: web.BaseRequest): ) @response_schema(LedgerConfigListSchema, 200, description="") async def get_ledger_config(request: web.BaseRequest): - """ - Request handler for fetching the ledger configuration list in use. + """Request handler for fetching the ledger configuration list in use. Args: request: aiohttp request object diff --git a/aries_cloudagent/ledger/tests/test_indy.py b/aries_cloudagent/ledger/tests/test_indy.py index fe9c8216ee..7b3012a9d6 100644 --- a/aries_cloudagent/ledger/tests/test_indy.py +++ b/aries_cloudagent/ledger/tests/test_indy.py @@ -1054,9 +1054,9 @@ async def test_get_schema_by_seq_no( ), json.dumps({"result": {"seqNo": 999}}), ] # need to subscript these in assertions later - mock_submit.side_effect = [ - sub for sub in submissions - ] # becomes list iterator, unsubscriptable, in mock object + mock_submit.side_effect = list( + submissions + ) # becomes list iterator, unsubscriptable, in mock object with async_mock.patch.object( IndySdkWallet, "get_public_did" ) as mock_wallet_get_public_did: @@ -1121,9 +1121,9 @@ async def test_get_schema_by_wrong_seq_no( ), # not a schema json.dumps({"result": {"seqNo": 999}}), ] # need to subscript these in assertions later - mock_submit.side_effect = [ - sub for sub in submissions - ] # becomes list iterator, unsubscriptable, in mock object + mock_submit.side_effect = list( + submissions + ) # becomes list iterator, unsubscriptable, in mock object ledger = IndySdkLedger(IndySdkLedgerPool("name", checked=True), self.profile) with async_mock.patch.object( IndySdkWallet, "get_public_did" diff --git a/aries_cloudagent/ledger/tests/test_indy_vdr.py b/aries_cloudagent/ledger/tests/test_indy_vdr.py index 6bae1f4abb..335c856efb 100644 --- a/aries_cloudagent/ledger/tests/test_indy_vdr.py +++ b/aries_cloudagent/ledger/tests/test_indy_vdr.py @@ -4,10 +4,6 @@ import pytest from asynctest import mock as async_mock -from aries_cloudagent.messaging.valid import ( - ENDPOINT_TYPE_EXAMPLE, - ENDPOINT_TYPE_VALIDATE, -) from ...core.in_memory import InMemoryProfile from ...indy.issuer import IndyIssuer @@ -15,7 +11,7 @@ from ...wallet.did_info import DIDInfo from ...wallet.did_method import SOV, DIDMethod, DIDMethods, HolderDefinedDid from ...wallet.did_posture import DIDPosture -from ...wallet.key_type import ED25519, KeyType +from ...wallet.key_type import ED25519 from ..endpoint_type import EndpointType from ..indy_vdr import ( BadLedgerRequestError, @@ -813,7 +809,7 @@ async def test_register_nym_local( async with ledger: await ledger.register_nym(post_did.did, post_did.verkey) did = await wallet.get_local_did(post_did.did) - assert did.metadata["posted"] == True + assert did.metadata["posted"] is True @pytest.mark.asyncio async def test_register_nym_non_local( @@ -1008,7 +1004,7 @@ async def test_send_revoc_reg_entry( @pytest.mark.asyncio async def test_credential_definition_id2schema_id(self, ledger: IndyVdrLedger): - S_ID = f"55GkHamhTU1ZbTbV2ab9DE:2:favourite_drink:1.0" + S_ID = "55GkHamhTU1ZbTbV2ab9DE:2:favourite_drink:1.0" SEQ_NO = "9999" async with ledger: diff --git a/aries_cloudagent/messaging/agent_message.py b/aries_cloudagent/messaging/agent_message.py index 15f95d57bb..08e6ec94e9 100644 --- a/aries_cloudagent/messaging/agent_message.py +++ b/aries_cloudagent/messaging/agent_message.py @@ -60,8 +60,7 @@ def __init__( _version: Optional[Text] = None, _decorators: BaseDecoratorSet = None, ): - """ - Initialize base agent message object. + """Initialize base agent message object. Args: _id: Agent message id @@ -101,8 +100,7 @@ def __init__( @classmethod def _get_handler_class(cls): - """ - Get handler class. + """Get handler class. Returns: The resolved class defined on `Meta.handler_class` @@ -112,8 +110,7 @@ def _get_handler_class(cls): @property def Handler(self) -> type: - """ - Accessor for the agent message's handler class. + """Accessor for the agent message's handler class. Returns: Handler class @@ -123,8 +120,7 @@ def Handler(self) -> type: @property def _type(self) -> str: - """ - Accessor for the message type identifier. + """Accessor for the message type identifier. Returns: Current DIDComm prefix, slash, message type defined on `Meta.message_type` @@ -139,8 +135,7 @@ def _type(self, msg_type: str): @property def _id(self) -> str: - """ - Accessor for the unique message identifier. + """Accessor for the unique message identifier. Returns: The id of this message @@ -168,8 +163,7 @@ def get_updated_msg_type(self, version: str) -> str: return sub(r"(\d+\.)?(\*|\d+)", version, self.Meta.message_type) def get_signature(self, field_name: str) -> SignatureDecorator: - """ - Get the signature for a named field. + """Get the signature for a named field. Args: field_name: Field name to get the signature for @@ -181,8 +175,7 @@ def get_signature(self, field_name: str) -> SignatureDecorator: return self._decorators.field(field_name).get("sig") def set_signature(self, field_name: str, signature: SignatureDecorator): - """ - Add or replace the signature for a named field. + """Add or replace the signature for a named field. Args: field_name: Field to set signature on @@ -194,8 +187,7 @@ def set_signature(self, field_name: str, signature: SignatureDecorator): async def sign_field( # TODO migrate to signed-attachment per RFC 17 self, field_name: str, signer_verkey: str, wallet: BaseWallet, timestamp=None ) -> SignatureDecorator: - """ - Create and store a signature for a named field. + """Create and store a signature for a named field. Args: field_name: Field to sign @@ -224,8 +216,7 @@ async def sign_field( # TODO migrate to signed-attachment per RFC 17 async def verify_signed_field( # TODO migrate to signed-attachment per RFC 17 self, field_name: str, wallet: BaseWallet, signer_verkey: str = None ) -> str: - """ - Verify a specific field signature. + """Verify a specific field signature. Args: field_name: The field name to verify @@ -256,8 +247,7 @@ async def verify_signed_field( # TODO migrate to signed-attachment per RFC 17 return sig.signer async def verify_signatures(self, wallet: BaseWallet) -> bool: - """ - Verify all associated field signatures. + """Verify all associated field signatures. Args: wallet: Wallet to use in verification @@ -273,8 +263,7 @@ async def verify_signatures(self, wallet: BaseWallet) -> bool: @property def _service(self) -> ServiceDecorator: - """ - Accessor for the message's service decorator. + """Accessor for the message's service decorator. Returns: The ServiceDecorator for this message @@ -284,8 +273,7 @@ def _service(self) -> ServiceDecorator: @_service.setter def _service(self, val: Union[ServiceDecorator, dict]): - """ - Setter for the message's service decorator. + """Setter for the message's service decorator. Args: val: ServiceDecorator or dict to set as the service @@ -297,8 +285,7 @@ def _service(self, val: Union[ServiceDecorator, dict]): @property def _thread(self) -> ThreadDecorator: - """ - Accessor for the message's thread decorator. + """Accessor for the message's thread decorator. Returns: The ThreadDecorator for this message @@ -308,8 +295,7 @@ def _thread(self) -> ThreadDecorator: @_thread.setter def _thread(self, val: Union[ThreadDecorator, dict]): - """ - Setter for the message's thread decorator. + """Setter for the message's thread decorator. Args: val: ThreadDecorator or dict to set as the thread @@ -327,8 +313,7 @@ def _thread_id(self) -> str: return self._message_id def assign_thread_from(self, msg: "AgentMessage"): - """ - Copy thread information from a previous message. + """Copy thread information from a previous message. Args: msg: The received message containing optional thread information @@ -340,8 +325,7 @@ def assign_thread_from(self, msg: "AgentMessage"): self.assign_thread_id(thid, pthid) def assign_thread_id(self, thid: str, pthid: str = None): - """ - Assign a specific thread ID. + """Assign a specific thread ID. Args: thid: The thread identifier @@ -354,8 +338,7 @@ def assign_thread_id(self, thid: str, pthid: str = None): @property def _trace(self) -> TraceDecorator: - """ - Accessor for the message's trace decorator. + """Accessor for the message's trace decorator. Returns: The TraceDecorator for this message @@ -365,8 +348,7 @@ def _trace(self) -> TraceDecorator: @_trace.setter def _trace(self, val: Union[TraceDecorator, dict]): - """ - Setter for the message's trace decorator. + """Setter for the message's trace decorator. Args: val: TraceDecorator or dict to set as the trace @@ -377,8 +359,7 @@ def _trace(self, val: Union[TraceDecorator, dict]): self._decorators["trace"] = val def assign_trace_from(self, msg: "AgentMessage"): - """ - Copy trace information from a previous message. + """Copy trace information from a previous message. Args: msg: The received message containing optional trace information @@ -389,8 +370,7 @@ def assign_trace_from(self, msg: "AgentMessage"): self._trace = msg._trace def assign_trace_decorator(self, context, trace): - """ - Copy trace from a json structure. + """Copy trace from a json structure. Args: trace: string containing trace json stucture @@ -404,8 +384,7 @@ def assign_trace_decorator(self, context, trace): def add_trace_decorator( self, target: str = TRACE_LOG_TARGET, full_thread: bool = True ): - """ - Create a new trace decorator. + """Create a new trace decorator. Args: target: The trace target @@ -420,8 +399,7 @@ def add_trace_decorator( self._trace = TraceDecorator(target=target, full_thread=full_thread) def add_trace_report(self, val: Union[TraceReport, dict]): - """ - Append a new trace report. + """Append a new trace report. Args: val: The trace target @@ -475,8 +453,7 @@ class Meta: ) def __init__(self, *args, **kwargs): - """ - Initialize an instance of AgentMessageSchema. + """Initialize an instance of AgentMessageSchema. Raises: TypeError: If Meta.model_class has not been set @@ -489,8 +466,7 @@ def __init__(self, *args, **kwargs): @pre_load def extract_decorators(self, data: Mapping, **kwargs): - """ - Pre-load hook to extract the decorators and check the signed fields. + """Pre-load hook to extract the decorators and check the signed fields. Args: data: Incoming data to parse @@ -529,8 +505,7 @@ def extract_decorators(self, data: Mapping, **kwargs): @post_load def populate_decorators(self, obj, **kwargs): - """ - Post-load hook to populate decorators on the message. + """Post-load hook to populate decorators on the message. Args: obj: The AgentMessage object @@ -544,8 +519,7 @@ def populate_decorators(self, obj, **kwargs): @pre_dump def check_dump_decorators(self, obj, **kwargs): - """ - Pre-dump hook to validate and load the message decorators. + """Pre-dump hook to validate and load the message decorators. Args: obj: The AgentMessage object @@ -575,8 +549,7 @@ def check_dump_decorators(self, obj, **kwargs): @post_dump def dump_decorators(self, data, **kwargs): - """ - Post-dump hook to write the decorators to the serialized output. + """Post-dump hook to write the decorators to the serialized output. Args: obj: The serialized data @@ -595,8 +568,7 @@ def dump_decorators(self, data, **kwargs): @post_dump def replace_signatures(self, data, **kwargs): - """ - Post-dump hook to write the signatures to the serialized output. + """Post-dump hook to write the signatures to the serialized output. Args: obj: The serialized data diff --git a/aries_cloudagent/messaging/base_handler.py b/aries_cloudagent/messaging/base_handler.py index 3418a7b096..cd1181330f 100644 --- a/aries_cloudagent/messaging/base_handler.py +++ b/aries_cloudagent/messaging/base_handler.py @@ -22,8 +22,7 @@ def __init__(self) -> None: @abstractmethod async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Abstract method for handler logic. + """Abstract method for handler logic. Args: context: Request context object diff --git a/aries_cloudagent/messaging/credential_definitions/routes.py b/aries_cloudagent/messaging/credential_definitions/routes.py index 97a917cab5..d058c1cf5d 100644 --- a/aries_cloudagent/messaging/credential_definitions/routes.py +++ b/aries_cloudagent/messaging/credential_definitions/routes.py @@ -183,8 +183,7 @@ class CredDefConnIdMatchInfoSchema(OpenAPISchema): @querystring_schema(CredDefConnIdMatchInfoSchema()) @response_schema(TxnOrCredentialDefinitionSendResultSchema(), 200, description="") async def credential_definitions_send_credential_definition(request: web.BaseRequest): - """ - Request handler for sending a credential definition to the ledger. + """Request handler for sending a credential definition to the ledger. Args: request: aiohttp request object @@ -371,8 +370,7 @@ async def credential_definitions_send_credential_definition(request: web.BaseReq @querystring_schema(CredDefQueryStringSchema()) @response_schema(CredentialDefinitionsCreatedResultSchema(), 200, description="") async def credential_definitions_created(request: web.BaseRequest): - """ - Request handler for retrieving credential definitions that current agent created. + """Request handler for retrieving credential definitions that current agent created. Args: request: aiohttp request object @@ -404,8 +402,7 @@ async def credential_definitions_created(request: web.BaseRequest): @match_info_schema(CredDefIdMatchInfoSchema()) @response_schema(CredentialDefinitionGetResultSchema(), 200, description="") async def credential_definitions_get_credential_definition(request: web.BaseRequest): - """ - Request handler for getting a credential definition from the ledger. + """Request handler for getting a credential definition from the ledger. Args: request: aiohttp request object @@ -451,8 +448,7 @@ async def credential_definitions_get_credential_definition(request: web.BaseRequ @match_info_schema(CredDefIdMatchInfoSchema()) @response_schema(CredentialDefinitionGetResultSchema(), 200, description="") async def credential_definitions_fix_cred_def_wallet_record(request: web.BaseRequest): - """ - Request handler for fixing a credential definition wallet non-secret record. + """Request handler for fixing a credential definition wallet non-secret record. Args: request: aiohttp request object @@ -560,8 +556,7 @@ async def on_cred_def_event(profile: Profile, event: Event): async def add_cred_def_non_secrets_record( profile: Profile, schema_id: str, issuer_did: str, credential_definition_id: str ): - """ - Write the wallet non-secrets record for cred def (already written to the ledger). + """Write the wallet non-secrets record for cred def (already written to the ledger). Note that the cred def private key signing informtion must already exist in the wallet. diff --git a/aries_cloudagent/messaging/credential_definitions/util.py b/aries_cloudagent/messaging/credential_definitions/util.py index 2d91e00c64..fb732ecd44 100644 --- a/aries_cloudagent/messaging/credential_definitions/util.py +++ b/aries_cloudagent/messaging/credential_definitions/util.py @@ -59,9 +59,7 @@ class CredDefQueryStringSchema(OpenAPISchema): ) -CRED_DEF_TAGS = [ - tag for tag in vars(CredDefQueryStringSchema).get("_declared_fields", []) -] +CRED_DEF_TAGS = list(vars(CredDefQueryStringSchema).get("_declared_fields", [])) CRED_DEF_EVENT_PREFIX = "acapy::CRED_DEF::" EVENT_LISTENER_PATTERN = re.compile(f"^{CRED_DEF_EVENT_PREFIX}(.*)?$") diff --git a/aries_cloudagent/messaging/decorators/attach_decorator.py b/aries_cloudagent/messaging/decorators/attach_decorator.py index 1cb34ff7aa..d27d9a9924 100644 --- a/aries_cloudagent/messaging/decorators/attach_decorator.py +++ b/aries_cloudagent/messaging/decorators/attach_decorator.py @@ -1,5 +1,4 @@ -""" -A message decorator for attachments. +"""A message decorator for attachments. An attach decorator embeds content or specifies appended content. """ @@ -136,8 +135,7 @@ class Meta: class AttachDecoratorDataJWS(BaseModel): - """ - Detached JSON Web Signature for inclusion in attach decorator data. + """Detached JSON Web Signature for inclusion in attach decorator data. May hold one signature in flattened format, or multiple signatures in the "signatures" member. @@ -247,8 +245,7 @@ def __init__( base64_: str = None, json_: Union[Sequence[dict], dict] = None, ): - """ - Initialize decorator data. + """Initialize decorator data. Specify content for one of: @@ -310,8 +307,7 @@ def signed(self) -> bytes: ) def header_map(self, idx: int = 0, jose: bool = True) -> Mapping: - """ - Accessor for header info at input index, default 0 or unique for singly-signed. + """Accessor for header info at input index, default 0 or unique for singly-signed. Args: idx: index of interest, zero-based (default 0) @@ -354,8 +350,7 @@ async def sign( verkeys: Union[str, Sequence[str]], wallet: BaseWallet, ): - """ - Sign base64 data value of attachment. + """Sign base64 data value of attachment. Args: verkeys: verkey(s) of the signing party (in raw or DID key format) @@ -432,8 +427,7 @@ def build_protected(verkey: str): self.jws_ = AttachDecoratorDataJWS.deserialize(jws) async def verify(self, wallet: BaseWallet, signer_verkey: str = None) -> bool: - """ - Verify the signature(s). + """Verify the signature(s). Args: wallet: Wallet to use to verify signature @@ -553,8 +547,7 @@ def __init__( data: AttachDecoratorData, **kwargs, ): - """ - Initialize an AttachDecorator instance. + """Initialize an AttachDecorator instance. The attachment decorator allows for embedding or appending content to a message. @@ -579,8 +572,7 @@ def __init__( @property def content(self) -> Union[Mapping, Tuple[Sequence[str], str]]: - """ - Return attachment content. + """Return attachment content. Returns: data attachment, decoded if necessary and json-loaded, or data links @@ -610,8 +602,7 @@ def data_base64( lastmod_time: str = None, byte_count: int = None, ): - """ - Create `AttachDecorator` instance on base64-encoded data from input mapping. + """Create `AttachDecorator` instance on base64-encoded data from input mapping. Given mapping, JSON dump, base64-encode, and embed it as data; mark `application/json` MIME type. @@ -648,8 +639,7 @@ def data_json( lastmod_time: str = None, byte_count: int = None, ): - """ - Create `AttachDecorator` instance on json-encoded data from input mapping. + """Create `AttachDecorator` instance on json-encoded data from input mapping. Given message object (dict), JSON dump, and embed it as data; mark `application/json` MIME type. @@ -686,8 +676,7 @@ def data_links( lastmod_time: str = None, byte_count: int = None, ): - """ - Create `AttachDecorator` instance on json-encoded data from input mapping. + """Create `AttachDecorator` instance on json-encoded data from input mapping. Given message object (dict), JSON dump, and embed it as data; mark `application/json` MIME type. diff --git a/aries_cloudagent/messaging/decorators/localization_decorator.py b/aries_cloudagent/messaging/decorators/localization_decorator.py index 221461ba18..38815b20ce 100644 --- a/aries_cloudagent/messaging/decorators/localization_decorator.py +++ b/aries_cloudagent/messaging/decorators/localization_decorator.py @@ -22,8 +22,7 @@ def __init__( localizable: Sequence[str] = None, catalogs: Sequence[str] = None, ): - """ - Initialize a LocalizationDecorator instance. + """Initialize a LocalizationDecorator instance. Args: locale: The locale of this message diff --git a/aries_cloudagent/messaging/decorators/please_ack_decorator.py b/aries_cloudagent/messaging/decorators/please_ack_decorator.py index 428893cb58..578e2613b8 100644 --- a/aries_cloudagent/messaging/decorators/please_ack_decorator.py +++ b/aries_cloudagent/messaging/decorators/please_ack_decorator.py @@ -21,8 +21,7 @@ def __init__( message_id: str = None, on: Sequence[str] = None, ): - """ - Initialize a PleaseAckDecorator instance. + """Initialize a PleaseAckDecorator instance. Args: message_id: identifier of message to acknowledge, if not current message diff --git a/aries_cloudagent/messaging/decorators/service_decorator.py b/aries_cloudagent/messaging/decorators/service_decorator.py index f29bc5f0c5..0a4695a01c 100644 --- a/aries_cloudagent/messaging/decorators/service_decorator.py +++ b/aries_cloudagent/messaging/decorators/service_decorator.py @@ -1,5 +1,4 @@ -""" -A message decorator for services. +"""A message decorator for services. A service decorator adds routing information to a message so agent can respond without needing to perform a handshake. @@ -28,8 +27,7 @@ def __init__( recipient_keys: List[str], routing_keys: Optional[List[str]] = None, ): - """ - Initialize a ServiceDecorator instance. + """Initialize a ServiceDecorator instance. Args: endpoint: Endpoint which this agent can be reached at @@ -44,8 +42,7 @@ def __init__( @property def endpoint(self): - """ - Accessor for service endpoint. + """Accessor for service endpoint. Returns: This service's `serviceEndpoint` @@ -55,8 +52,7 @@ def endpoint(self): @property def recipient_keys(self): - """ - Accessor for recipient keys. + """Accessor for recipient keys. Returns: This service's `recipientKeys` @@ -66,8 +62,7 @@ def recipient_keys(self): @property def routing_keys(self): - """ - Accessor for routing keys. + """Accessor for routing keys. Returns: This service's `routingKeys` diff --git a/aries_cloudagent/messaging/decorators/signature_decorator.py b/aries_cloudagent/messaging/decorators/signature_decorator.py index 56a24950aa..0abcef259f 100644 --- a/aries_cloudagent/messaging/decorators/signature_decorator.py +++ b/aries_cloudagent/messaging/decorators/signature_decorator.py @@ -37,8 +37,7 @@ def __init__( sig_data: str = None, signer: str = None, ): - """ - Initialize a FieldSignature instance. + """Initialize a FieldSignature instance. Args: signature_type: Type of signature @@ -55,8 +54,7 @@ def __init__( async def create( cls, value, signer: str, wallet: BaseWallet, timestamp=None ) -> "SignatureDecorator": - """ - Create a Signature. + """Create a Signature. Sign a field value and return a newly constructed `SignatureDecorator` representing the resulting signature. @@ -86,8 +84,7 @@ async def create( ) def decode(self) -> (object, int): - """ - Decode the signature to its timestamp and value. + """Decode the signature to its timestamp and value. Returns: A tuple of (decoded message, timestamp) @@ -98,8 +95,7 @@ def decode(self) -> (object, int): return (json.loads(msg_bin[8:]), timestamp) async def verify(self, wallet: BaseWallet) -> bool: - """ - Verify the signature against the signer's public key. + """Verify the signature against the signer's public key. Args: wallet: Wallet to use to verify signature diff --git a/aries_cloudagent/messaging/decorators/tests/test_please_ack_decorator.py b/aries_cloudagent/messaging/decorators/tests/test_please_ack_decorator.py index f75f7f27c3..46b48c78ef 100644 --- a/aries_cloudagent/messaging/decorators/tests/test_please_ack_decorator.py +++ b/aries_cloudagent/messaging/decorators/tests/test_please_ack_decorator.py @@ -1,10 +1,3 @@ -import json -import pytest -import uuid - -from copy import deepcopy -from datetime import datetime, timezone -from time import time from unittest import TestCase from ..please_ack_decorator import PleaseAckDecorator diff --git a/aries_cloudagent/messaging/decorators/tests/test_timing_decorator.py b/aries_cloudagent/messaging/decorators/tests/test_timing_decorator.py index b979f90bec..ea4527674f 100644 --- a/aries_cloudagent/messaging/decorators/tests/test_timing_decorator.py +++ b/aries_cloudagent/messaging/decorators/tests/test_timing_decorator.py @@ -2,7 +2,7 @@ from unittest import TestCase from ...util import datetime_to_str -from ..timing_decorator import TimingDecorator, TimingDecoratorSchema +from ..timing_decorator import TimingDecorator NOW = datetime.now() diff --git a/aries_cloudagent/messaging/decorators/tests/test_transport_decorator.py b/aries_cloudagent/messaging/decorators/tests/test_transport_decorator.py index 3d44b212a4..383e6e3e4a 100644 --- a/aries_cloudagent/messaging/decorators/tests/test_transport_decorator.py +++ b/aries_cloudagent/messaging/decorators/tests/test_transport_decorator.py @@ -1,7 +1,7 @@ from unittest import TestCase from ...valid import UUID4_EXAMPLE -from ..transport_decorator import TransportDecorator, TransportDecoratorSchema +from ..transport_decorator import TransportDecorator class TestTransportDecorator(TestCase): diff --git a/aries_cloudagent/messaging/decorators/thread_decorator.py b/aries_cloudagent/messaging/decorators/thread_decorator.py index 9911df7b0e..cbae0684cc 100644 --- a/aries_cloudagent/messaging/decorators/thread_decorator.py +++ b/aries_cloudagent/messaging/decorators/thread_decorator.py @@ -1,5 +1,4 @@ -""" -A message decorator for threads. +"""A message decorator for threads. A thread decorator identifies a message that may require additional context from previous messages. @@ -29,8 +28,7 @@ def __init__( sender_order: int = None, received_orders: Mapping = None, ): - """ - Initialize a ThreadDecorator instance. + """Initialize a ThreadDecorator instance. Args: thid: The ID of the message that serves as the @@ -55,8 +53,7 @@ def __init__( @property def thid(self): - """ - Accessor for thread identifier. + """Accessor for thread identifier. Returns: This thread's `thid` @@ -66,8 +63,7 @@ def thid(self): @property def pthid(self): - """ - Accessor for parent thread identifier. + """Accessor for parent thread identifier. Returns: This thread's `pthid` @@ -77,8 +73,7 @@ def pthid(self): @pthid.setter def pthid(self, val: str): - """ - Setter for parent thread identifier. + """Setter for parent thread identifier. Args: val: The new pthid @@ -87,8 +82,7 @@ def pthid(self, val: str): @property def received_orders(self) -> dict: - """ - Get received orders. + """Get received orders. Returns: The highest sender_order value that the sender has seen from other @@ -99,8 +93,7 @@ def received_orders(self) -> dict: @property def sender_order(self) -> int: - """ - Get sender order. + """Get sender order. Returns: A number that tells where this message fits in the sequence of all diff --git a/aries_cloudagent/messaging/decorators/timing_decorator.py b/aries_cloudagent/messaging/decorators/timing_decorator.py index 66118ce5c5..0cb1b0300c 100644 --- a/aries_cloudagent/messaging/decorators/timing_decorator.py +++ b/aries_cloudagent/messaging/decorators/timing_decorator.py @@ -1,5 +1,4 @@ -""" -The timing decorator (~timing). +"""The timing decorator (~timing). This decorator allows the timing of agent messages to be communicated and constrained. @@ -33,8 +32,7 @@ def __init__( delay_milli: int = None, wait_until_time: Union[str, datetime] = None, ): - """ - Initialize a TimingDecorator instance. + """Initialize a TimingDecorator instance. Args: in_time: The time the message was received diff --git a/aries_cloudagent/messaging/decorators/trace_decorator.py b/aries_cloudagent/messaging/decorators/trace_decorator.py index ecf4f26d6f..f1a75560d6 100644 --- a/aries_cloudagent/messaging/decorators/trace_decorator.py +++ b/aries_cloudagent/messaging/decorators/trace_decorator.py @@ -1,5 +1,4 @@ -""" -A message decorator for trace events. +"""A message decorator for trace events. A trace decorator identifies a responsibility on the processor to record information on message processing events. @@ -36,8 +35,7 @@ def __init__( ellapsed_milli: int = None, outcome: str = None, ): - """ - Initialize a TraceReport instance. + """Initialize a TraceReport instance. Args: msg_id: ... @@ -61,8 +59,7 @@ def __init__( @property def msg_id(self): - """ - Accessor for msg_id. + """Accessor for msg_id. Returns: The msg_id @@ -72,8 +69,7 @@ def msg_id(self): @property def thread_id(self): - """ - Accessor for thread_id. + """Accessor for thread_id. Returns: The thread_id @@ -83,8 +79,7 @@ def thread_id(self): @property def traced_type(self): - """ - Accessor for traced_type. + """Accessor for traced_type. Returns: The sender traced_type @@ -94,8 +89,7 @@ def traced_type(self): @property def timestamp(self): - """ - Accessor for timestamp. + """Accessor for timestamp. Returns: The sender timestamp @@ -105,8 +99,7 @@ def timestamp(self): @property def str_time(self): - """ - Accessor for str_time. + """Accessor for str_time. Returns: Formatted representation of the sender timestamp @@ -116,8 +109,7 @@ def str_time(self): @property def handler(self): - """ - Accessor for handler. + """Accessor for handler. Returns: The sender handler @@ -127,8 +119,7 @@ def handler(self): @property def ellapsed_milli(self): - """ - Accessor for ellapsed_milli. + """Accessor for ellapsed_milli. Returns: The sender ellapsed_milli @@ -138,8 +129,7 @@ def ellapsed_milli(self): @property def outcome(self): - """ - Accessor for outcome. + """Accessor for outcome. Returns: The sender outcome @@ -163,8 +153,7 @@ def __init__( full_thread: bool = True, trace_reports: Sequence = None, ): - """ - Initialize a TraceDecorator instance. + """Initialize a TraceDecorator instance. Args: target: The "target" can refer to a url (as above) or the term @@ -185,8 +174,7 @@ def __init__( @property def target(self): - """ - Accessor for trace target. + """Accessor for trace target. Returns: The target for tracing messages @@ -196,8 +184,7 @@ def target(self): @property def full_thread(self): - """ - Accessor for full_thread flag. + """Accessor for full_thread flag. Returns: The full_thread flag @@ -207,8 +194,7 @@ def full_thread(self): @property def trace_reports(self): - """ - Set of trace reports for this message. + """Set of trace reports for this message. Returns: The trace reports that have been logged on this message/thread diff --git a/aries_cloudagent/messaging/decorators/transport_decorator.py b/aries_cloudagent/messaging/decorators/transport_decorator.py index 253dda6d73..cd35226473 100644 --- a/aries_cloudagent/messaging/decorators/transport_decorator.py +++ b/aries_cloudagent/messaging/decorators/transport_decorator.py @@ -1,5 +1,4 @@ -""" -The transport decorator (~transport). +"""The transport decorator (~transport). This decorator allows changes to agent response behaviour and queue status updates. """ @@ -25,8 +24,7 @@ def __init__( return_route_thread: str = None, queued_message_count: int = None, ): - """ - Initialize a TransportDecorator instance. + """Initialize a TransportDecorator instance. Args: return_route: Set the return routing mode diff --git a/aries_cloudagent/messaging/jsonld/create_verify_data.py b/aries_cloudagent/messaging/jsonld/create_verify_data.py index 34f6c20d39..26844a627e 100644 --- a/aries_cloudagent/messaging/jsonld/create_verify_data.py +++ b/aries_cloudagent/messaging/jsonld/create_verify_data.py @@ -1,5 +1,4 @@ -""" -Contains the functions needed to produce and verify a json-ld signature. +"""Contains the functions needed to produce and verify a json-ld signature. This file was ported from https://github.com/transmute-industries/Ed25519Signature2018/blob/master/src/createVerifyData/index.js diff --git a/aries_cloudagent/messaging/jsonld/routes.py b/aries_cloudagent/messaging/jsonld/routes.py index 484541be1d..b7330f9d83 100644 --- a/aries_cloudagent/messaging/jsonld/routes.py +++ b/aries_cloudagent/messaging/jsonld/routes.py @@ -63,8 +63,7 @@ class SignResponseSchema(OpenAPISchema): @request_schema(SignRequestSchema()) @response_schema(SignResponseSchema(), 200, description="") async def sign(request: web.BaseRequest): - """ - Request handler for signing a jsonld doc. + """Request handler for signing a jsonld doc. Args: request: aiohttp request object @@ -124,8 +123,7 @@ class VerifyResponseSchema(OpenAPISchema): @request_schema(VerifyRequestSchema()) @response_schema(VerifyResponseSchema(), 200, description="") async def verify(request: web.BaseRequest): - """ - Request handler for signing a jsonld doc. + """Request handler for signing a jsonld doc. Args: request: aiohttp request object diff --git a/aries_cloudagent/messaging/jsonld/tests/document_loader.py b/aries_cloudagent/messaging/jsonld/tests/document_loader.py index 327448a0c2..8fb294bda5 100644 --- a/aries_cloudagent/messaging/jsonld/tests/document_loader.py +++ b/aries_cloudagent/messaging/jsonld/tests/document_loader.py @@ -12,12 +12,9 @@ TEST_EURO_HEALTH, TEST_SIGN_OBJ0, TEST_SIGN_OBJ1, - TEST_SIGN_OBJ2, - TEST_VALIDATE_ERROR_OBJ2, TEST_VERIFY_ERROR, TEST_VERIFY_OBJ0, TEST_VERIFY_OBJ1, - TEST_VERIFY_OBJ2, ) DOCUMENTS = { diff --git a/aries_cloudagent/messaging/jsonld/tests/test_credential.py b/aries_cloudagent/messaging/jsonld/tests/test_credential.py index 3046388533..85f0eb2a26 100644 --- a/aries_cloudagent/messaging/jsonld/tests/test_credential.py +++ b/aries_cloudagent/messaging/jsonld/tests/test_credential.py @@ -1,14 +1,10 @@ """Test json-ld credential.""" -import asyncio import json -import pytest -from itertools import cycle from asynctest import mock as async_mock, TestCase as AsyncTestCase -from ....admin.request_context import AdminRequestContext from ....core.in_memory import InMemoryProfile from ....vc.ld_proofs import DocumentLoader from ....wallet.base import BaseWallet @@ -24,7 +20,6 @@ TEST_SEED, TEST_SIGN_ERROR_OBJS, TEST_SIGN_OBJS, - TEST_VALIDATE_ERROR_OBJ2, TEST_VERIFY_ERROR, TEST_VERIFY_OBJS, TEST_VERKEY, diff --git a/aries_cloudagent/messaging/models/base.py b/aries_cloudagent/messaging/models/base.py index a63bdbe718..d9139be964 100644 --- a/aries_cloudagent/messaging/models/base.py +++ b/aries_cloudagent/messaging/models/base.py @@ -19,8 +19,7 @@ def resolve_class(the_cls, relative_cls: Optional[type] = None) -> type: - """ - Resolve a class. + """Resolve a class. Args: the_cls: The class to resolve @@ -47,8 +46,7 @@ def resolve_class(the_cls, relative_cls: Optional[type] = None) -> type: def resolve_meta_property(obj, prop_name: str, defval=None): - """ - Resolve a meta property. + """Resolve a meta property. Args: prop_name: The property to resolve @@ -90,8 +88,7 @@ class Meta: schema_class = None def __init__(self): - """ - Initialize BaseModel. + """Initialize BaseModel. Raises: TypeError: If schema_class is not set on Meta @@ -106,8 +103,7 @@ def __init__(self): @classmethod def _get_schema_class(cls) -> Type["BaseModelSchema"]: - """ - Get the schema class. + """Get the schema class. Returns: The resolved schema class @@ -123,8 +119,7 @@ def _get_schema_class(cls) -> Type["BaseModelSchema"]: @property def Schema(self) -> Type["BaseModelSchema"]: - """ - Accessor for the model's schema class. + """Accessor for the model's schema class. Returns: The schema class @@ -138,7 +133,6 @@ def deserialize( cls: Type[ModelType], obj, ) -> ModelType: - """Convert from JSON representation to a model instance.""" ... @overload @@ -149,7 +143,6 @@ def deserialize( *, unknown: Optional[str] = None, ) -> ModelType: - """Convert from JSON representation to a model instance.""" ... @overload @@ -161,7 +154,6 @@ def deserialize( none2none: Literal[False], unknown: Optional[str] = None, ) -> ModelType: - """Convert from JSON representation to a model instance.""" ... @overload @@ -173,7 +165,6 @@ def deserialize( none2none: Literal[True], unknown: Optional[str] = None, ) -> Optional[ModelType]: - """Convert from JSON representation to a model instance.""" ... @classmethod @@ -184,8 +175,7 @@ def deserialize( unknown: Optional[str] = None, none2none: bool = False, ) -> Optional[ModelType]: - """ - Convert from JSON representation to a model instance. + """Convert from JSON representation to a model instance. Args: obj: The dict to load into a model instance @@ -220,7 +210,6 @@ def serialize( as_string: Literal[True], unknown: Optional[str] = None, ) -> str: - """Create a JSON-compatible dict representation of the model instance.""" ... @overload @@ -229,7 +218,6 @@ def serialize( *, unknown: Optional[str] = None, ) -> dict: - """Create a JSON-compatible dict representation of the model instance.""" ... def serialize( @@ -238,8 +226,7 @@ def serialize( as_string: bool = False, unknown: Optional[str] = None, ) -> Union[str, dict]: - """ - Create a JSON-compatible dict representation of the model instance. + """Create a JSON-compatible dict representation of the model instance. Args: as_string: Return a string of JSON instead of a dict @@ -289,8 +276,7 @@ def from_json( json_repr: Union[str, bytes], unknown: Optional[str] = None, ): - """ - Parse a JSON string into a model instance. + """Parse a JSON string into a model instance. Args: json_repr: JSON string @@ -307,8 +293,7 @@ def from_json( return cls.deserialize(parsed, unknown=unknown) def to_json(self, unknown: str = None) -> str: - """ - Create a JSON representation of the model instance. + """Create a JSON representation of the model instance. Returns: A JSON representation of this message @@ -317,8 +302,7 @@ def to_json(self, unknown: str = None) -> str: return json.dumps(self.serialize(unknown=unknown)) def __repr__(self) -> str: - """ - Return a human readable representation of this class. + """Return a human readable representation of this class. Returns: A human readable string for this class @@ -344,8 +328,7 @@ class Meta: ordered = True def __init__(self, *args, **kwargs): - """ - Initialize BaseModelSchema. + """Initialize BaseModelSchema. Raises: TypeError: If model_class is not set on Meta @@ -361,8 +344,7 @@ def __init__(self, *args, **kwargs): @classmethod def _get_model_class(cls): - """ - Get the model class. + """Get the model class. Returns: The model class @@ -372,8 +354,7 @@ def _get_model_class(cls): @property def Model(self) -> type: - """ - Accessor for the schema's model class. + """Accessor for the schema's model class. Returns: The model class @@ -383,8 +364,7 @@ def Model(self) -> type: @pre_load def skip_dump_only(self, data, **kwargs): - """ - Skip fields that are only expected during serialization. + """Skip fields that are only expected during serialization. Args: data: The incoming data to clean @@ -408,8 +388,7 @@ def skip_dump_only(self, data, **kwargs): @post_load def make_model(self, data: dict, **kwargs): - """ - Return model instance after loading. + """Return model instance after loading. Returns: A model instance @@ -426,8 +405,7 @@ def make_model(self, data: dict, **kwargs): @post_dump def remove_skipped_values(self, data, **kwargs): - """ - Remove values that are are marked to skip. + """Remove values that are are marked to skip. Returns: Returns this modified data diff --git a/aries_cloudagent/messaging/models/base_record.py b/aries_cloudagent/messaging/models/base_record.py index e580127c55..3e94c58a5c 100644 --- a/aries_cloudagent/messaging/models/base_record.py +++ b/aries_cloudagent/messaging/models/base_record.py @@ -30,8 +30,7 @@ def match_post_filter( positive: bool = True, alt: bool = False, ) -> bool: - """ - Determine if a record value matches the post-filter. + """Determine if a record value matches the post-filter. Args: record: record to check @@ -105,8 +104,7 @@ def __init__( @classmethod def from_storage(cls, record_id: str, record: Mapping[str, Any]): - """ - Initialize a record from its stored representation. + """Initialize a record from its stored representation. Args: record_id: The unique record identifier @@ -167,8 +165,7 @@ def tags(self) -> dict: @classmethod async def get_cached_key(cls, session: ProfileSession, cache_key: str): - """ - Shortcut method to fetch a cached key value. + """Shortcut method to fetch a cached key value. Args: session: The profile session to use @@ -184,8 +181,7 @@ async def get_cached_key(cls, session: ProfileSession, cache_key: str): async def set_cached_key( cls, session: ProfileSession, cache_key: str, value: Any, ttl=None ): - """ - Shortcut method to set a cached key value. + """Shortcut method to set a cached key value. Args: session: The profile session to use @@ -202,8 +198,7 @@ async def set_cached_key( @classmethod async def clear_cached_key(cls, session: ProfileSession, cache_key: str): - """ - Shortcut method to clear a cached key value, if any. + """Shortcut method to clear a cached key value, if any. Args: session: The profile session to use @@ -224,8 +219,7 @@ async def retrieve_by_id( *, for_update=False, ) -> RecordType: - """ - Retrieve a stored record by ID. + """Retrieve a stored record by ID. Args: session: The profile session to use @@ -248,8 +242,7 @@ async def retrieve_by_tag_filter( *, for_update=False, ) -> RecordType: - """ - Retrieve a record by tag filter. + """Retrieve a record by tag filter. Args: session: The profile session to use @@ -295,8 +288,7 @@ async def query( post_filter_negative: dict = None, alt: bool = False, ) -> Sequence[RecordType]: - """ - Query stored records. + """Query stored records. Args: session: The profile session to use @@ -342,8 +334,7 @@ async def save( log_override: bool = False, event: bool = None, ) -> str: - """ - Persist the record to storage. + """Persist the record to storage. Args: session: The profile session to use @@ -391,8 +382,7 @@ async def post_save( last_state: Optional[str], event: bool = None, ): - """ - Perform post-save actions. + """Perform post-save actions. Args: session: The profile session to use @@ -407,8 +397,7 @@ async def post_save( await self.emit_event(session, self.serialize()) async def delete_record(self, session: ProfileSession): - """ - Remove the stored record. + """Remove the stored record. Args: session: The profile session to use @@ -423,8 +412,7 @@ async def delete_record(self, session: ProfileSession): await storage.delete_record(self.storage_record) async def emit_event(self, session: ProfileSession, payload: Any = None): - """ - Emit an event. + """Emit an event. Args: session: The profile session to use @@ -497,8 +485,7 @@ def __eq__(self, other: Any) -> bool: @classmethod def get_attributes_by_prefix(cls, prefix: str, walk_mro: bool = True): - """ - List all values for attributes with common prefix. + """List all values for attributes with common prefix. Args: prefix: Common prefix to look for diff --git a/aries_cloudagent/messaging/models/tests/test_base_record.py b/aries_cloudagent/messaging/models/tests/test_base_record.py index 87749e2df8..803c16e023 100644 --- a/aries_cloudagent/messaging/models/tests/test_base_record.py +++ b/aries_cloudagent/messaging/models/tests/test_base_record.py @@ -9,14 +9,13 @@ from ....storage.base import ( BaseStorage, StorageDuplicateError, - StorageError, StorageRecord, ) from ....messaging.models.base import BaseModelError from ...util import time_now -from ..base_record import BaseRecord, BaseRecordSchema, LOGGER +from ..base_record import BaseRecord, BaseRecordSchema class BaseRecordImpl(BaseRecord): diff --git a/aries_cloudagent/messaging/request_context.py b/aries_cloudagent/messaging/request_context.py index 715591cb2d..c96fb2e334 100644 --- a/aries_cloudagent/messaging/request_context.py +++ b/aries_cloudagent/messaging/request_context.py @@ -1,5 +1,4 @@ -""" -Request context class. +"""Request context class. A request context provides everything required by handlers and other parts of the system to process a message. @@ -40,8 +39,7 @@ def __init__( @property def connection_ready(self) -> bool: - """ - Accessor for the flag indicating an active connection with the sender. + """Accessor for the flag indicating an active connection with the sender. Returns: True if the connection is active, else False @@ -51,8 +49,7 @@ def connection_ready(self) -> bool: @connection_ready.setter def connection_ready(self, active: bool): - """ - Setter for the flag indicating an active connection with the sender. + """Setter for the flag indicating an active connection with the sender. Args: active: The new active value @@ -76,8 +73,7 @@ def connection_record(self, record: ConnRecord): @property def default_endpoint(self) -> str: - """ - Accessor for the default agent endpoint (from agent config). + """Accessor for the default agent endpoint (from agent config). Returns: The default agent endpoint @@ -87,8 +83,7 @@ def default_endpoint(self) -> str: @default_endpoint.setter def default_endpoint(self, endpoint: str): - """ - Setter for the default agent endpoint (from agent config). + """Setter for the default agent endpoint (from agent config). Args: endpoint: The new default endpoint @@ -98,8 +93,7 @@ def default_endpoint(self, endpoint: str): @property def default_label(self) -> str: - """ - Accessor for the default agent label (from agent config). + """Accessor for the default agent label (from agent config). Returns: The default label @@ -109,8 +103,7 @@ def default_label(self) -> str: @default_label.setter def default_label(self, label: str): - """ - Setter for the default agent label (from agent config). + """Setter for the default agent label (from agent config). Args: label: The new default label @@ -120,8 +113,7 @@ def default_label(self, label: str): @property def message(self) -> AgentMessage: - """ - Accessor for the deserialized message instance. + """Accessor for the deserialized message instance. Returns: This context's agent message @@ -131,8 +123,7 @@ def message(self) -> AgentMessage: @message.setter def message(self, msg: AgentMessage): - """ - Setter for the deserialized message instance. + """Setter for the deserialized message instance. Args: msg: This context's new agent message @@ -141,8 +132,7 @@ def message(self, msg: AgentMessage): @property def message_receipt(self) -> MessageReceipt: - """ - Accessor for the message receipt information. + """Accessor for the message receipt information. Returns: This context's message receipt information @@ -152,8 +142,7 @@ def message_receipt(self) -> MessageReceipt: @message_receipt.setter def message_receipt(self, receipt: MessageReceipt): - """ - Setter for the message receipt information. + """Setter for the message receipt information. Args: msg: This context's new message receipt information @@ -180,8 +169,7 @@ def session(self) -> ProfileSession: return self.profile.session(self._context) def transaction(self) -> ProfileSession: - """ - Start a new interactive session with commit and rollback support. + """Start a new interactive session with commit and rollback support. If the current backend does not support transactions, then commit and rollback operations of the session will not have any effect. @@ -193,8 +181,7 @@ def inject( base_cls: Type[InjectType], settings: Mapping[str, object] = None, ) -> InjectType: - """ - Get the provided instance of a given class identifier. + """Get the provided instance of a given class identifier. Args: cls: The base class to retrieve an instance of @@ -212,8 +199,7 @@ def inject_or( settings: Mapping[str, object] = None, default: Optional[InjectType] = None, ) -> Optional[InjectType]: - """ - Get the provided instance of a given class identifier or default if not found. + """Get the provided instance of a given class identifier or default if not found. Args: base_cls: The base class to retrieve an instance of @@ -236,8 +222,7 @@ def test_context(cls) -> "RequestContext": return RequestContext(IN_MEM.resolved.test_profile()) def __repr__(self) -> str: - """ - Provide a human readable representation of this object. + """Provide a human readable representation of this object. Returns: A human readable representation of this object diff --git a/aries_cloudagent/messaging/responder.py b/aries_cloudagent/messaging/responder.py index 78f501204e..90f4bb134e 100644 --- a/aries_cloudagent/messaging/responder.py +++ b/aries_cloudagent/messaging/responder.py @@ -1,5 +1,4 @@ -""" -A message responder. +"""A message responder. The responder is provided to message handlers to enable them to send a new message in response to the message being handled. @@ -112,8 +111,7 @@ async def send_reply( target: ConnectionTarget = None, target_list: Sequence[ConnectionTarget] = None, ) -> OutboundSendStatus: - """ - Send a reply to an incoming message. + """Send a reply to an incoming message. Args: message: the `BaseMessage`, or pre-packed str or bytes to reply with @@ -185,8 +183,7 @@ async def _wait_for_state() -> Tuple[bool, Optional[str]]: async def send_outbound( self, message: OutboundMessage, **kwargs ) -> OutboundSendStatus: - """ - Send an outbound message. + """Send an outbound message. Args: message: The `OutboundMessage` to be sent @@ -194,8 +191,7 @@ async def send_outbound( @abstractmethod async def send_webhook(self, topic: str, payload: dict): - """ - Dispatch a webhook. DEPRECATED: use the event bus instead. + """Dispatch a webhook. DEPRECATED: use the event bus instead. Args: topic: the webhook topic identifier diff --git a/aries_cloudagent/messaging/schemas/routes.py b/aries_cloudagent/messaging/schemas/routes.py index a68a0ad055..c1ee83948f 100644 --- a/aries_cloudagent/messaging/schemas/routes.py +++ b/aries_cloudagent/messaging/schemas/routes.py @@ -167,8 +167,7 @@ class SchemaConnIdMatchInfoSchema(OpenAPISchema): @querystring_schema(SchemaConnIdMatchInfoSchema()) @response_schema(TxnOrSchemaSendResultSchema(), 200, description="") async def schemas_send_schema(request: web.BaseRequest): - """ - Request handler for creating a schema. + """Request handler for creating a schema. Args: request: aiohttp request object @@ -340,8 +339,7 @@ async def schemas_send_schema(request: web.BaseRequest): @querystring_schema(SchemaQueryStringSchema()) @response_schema(SchemasCreatedResultSchema(), 200, description="") async def schemas_created(request: web.BaseRequest): - """ - Request handler for retrieving schemas that current agent created. + """Request handler for retrieving schemas that current agent created. Args: request: aiohttp request object @@ -368,8 +366,7 @@ async def schemas_created(request: web.BaseRequest): @match_info_schema(SchemaIdMatchInfoSchema()) @response_schema(SchemaGetResultSchema(), 200, description="") async def schemas_get_schema(request: web.BaseRequest): - """ - Request handler for sending a credential offer. + """Request handler for sending a credential offer. Args: request: aiohttp request object @@ -413,8 +410,7 @@ async def schemas_get_schema(request: web.BaseRequest): @match_info_schema(SchemaIdMatchInfoSchema()) @response_schema(SchemaGetResultSchema(), 200, description="") async def schemas_fix_schema_wallet_record(request: web.BaseRequest): - """ - Request handler for fixing a schema's wallet non-secrets records. + """Request handler for fixing a schema's wallet non-secrets records. Args: request: aiohttp request object @@ -482,8 +478,7 @@ async def on_schema_event(profile: Profile, event: Event): async def add_schema_non_secrets_record(profile: Profile, schema_id: str): - """ - Write the wallet non-secrets record for a schema (already written to the ledger). + """Write the wallet non-secrets record for a schema (already written to the ledger). Args: profile: the current profile (used to determine storage) diff --git a/aries_cloudagent/messaging/schemas/util.py b/aries_cloudagent/messaging/schemas/util.py index bb6f5887ee..35f8ce5bae 100644 --- a/aries_cloudagent/messaging/schemas/util.py +++ b/aries_cloudagent/messaging/schemas/util.py @@ -42,7 +42,7 @@ class SchemaQueryStringSchema(OpenAPISchema): ) -SCHEMA_TAGS = [tag for tag in vars(SchemaQueryStringSchema).get("_declared_fields", [])] +SCHEMA_TAGS = list(vars(SchemaQueryStringSchema).get("_declared_fields", [])) SCHEMA_SENT_RECORD_TYPE = "schema_sent" SCHEMA_EVENT_PREFIX = "acapy::SCHEMA::" diff --git a/aries_cloudagent/messaging/tests/test_agent_message.py b/aries_cloudagent/messaging/tests/test_agent_message.py index 947328da63..bafe0c2703 100644 --- a/aries_cloudagent/messaging/tests/test_agent_message.py +++ b/aries_cloudagent/messaging/tests/test_agent_message.py @@ -134,7 +134,7 @@ async def test_add_tracing(self): msg.add_trace_decorator() tracer = msg._trace assert tracer.target == TRACE_LOG_TARGET - assert tracer.full_thread == True + assert tracer.full_thread is True trace_report = TraceReport( msg_id=msg._id, diff --git a/aries_cloudagent/messaging/tests/test_util.py b/aries_cloudagent/messaging/tests/test_util.py index c1a7e7c82b..834dc26ae7 100644 --- a/aries_cloudagent/messaging/tests/test_util.py +++ b/aries_cloudagent/messaging/tests/test_util.py @@ -1,7 +1,5 @@ -import re - from datetime import datetime, timezone -from unittest import mock, TestCase +from unittest import TestCase from ..util import ( canon, @@ -9,7 +7,6 @@ datetime_to_str, encode, epoch_to_str, - I32_BOUND, str_to_datetime, str_to_epoch, time_now, diff --git a/aries_cloudagent/messaging/util.py b/aries_cloudagent/messaging/util.py index 2c23795a36..67334331dc 100644 --- a/aries_cloudagent/messaging/util.py +++ b/aries_cloudagent/messaging/util.py @@ -104,8 +104,7 @@ def time_now() -> str: def encode(orig: Any) -> str: - """ - Encode a credential value as an int. + """Encode a credential value as an int. Encode credential attribute value, purely stringifying any int32 and leaving numeric int32 strings alone, but mapping any other @@ -137,8 +136,7 @@ def encode(orig: Any) -> str: def canon(raw_attr_name: str) -> str: - """ - Canonicalize input attribute name for indy proofs and credential offers. + """Canonicalize input attribute name for indy proofs and credential offers. Args: raw_attr_name: raw attribute name diff --git a/aries_cloudagent/messaging/valid.py b/aries_cloudagent/messaging/valid.py index 5a8d78aabf..73e66af0d0 100644 --- a/aries_cloudagent/messaging/valid.py +++ b/aries_cloudagent/messaging/valid.py @@ -330,8 +330,7 @@ def __init__(self): class RoutingKey(Regexp): - """ - Validate between indy or did key. + """Validate between indy or did key. Validate value against indy (Ed25519VerificationKey2018) raw public key or DID key specification. diff --git a/aries_cloudagent/multitenant/admin/routes.py b/aries_cloudagent/multitenant/admin/routes.py index e524ba6d92..6ae32f43a3 100644 --- a/aries_cloudagent/multitenant/admin/routes.py +++ b/aries_cloudagent/multitenant/admin/routes.py @@ -151,9 +151,7 @@ class CreateWalletRequestSchema(OpenAPISchema): wallet_type = fields.Str( dump_default="in_memory", - validate=validate.OneOf( - [wallet_type for wallet_type in ProfileManagerProvider.MANAGER_TYPES] - ), + validate=validate.OneOf(list(ProfileManagerProvider.MANAGER_TYPES)), metadata={"description": "Type of the wallet to create", "example": "indy"}, ) @@ -213,8 +211,7 @@ class CreateWalletRequestSchema(OpenAPISchema): @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields. + """Validate schema fields. Args: data: The data to validate @@ -350,8 +347,7 @@ class WalletListQueryStringSchema(OpenAPISchema): @querystring_schema(WalletListQueryStringSchema()) @response_schema(WalletListSchema(), 200, description="") async def wallets_list(request: web.BaseRequest): - """ - Request handler for listing all internal subwallets. + """Request handler for listing all internal subwallets. Args: request: aiohttp request object @@ -380,8 +376,7 @@ async def wallets_list(request: web.BaseRequest): @match_info_schema(WalletIdMatchInfoSchema()) @response_schema(WalletRecordSchema(), 200, description="") async def wallet_get(request: web.BaseRequest): - """ - Request handler for getting a single subwallet. + """Request handler for getting a single subwallet. Args: request: aiohttp request object @@ -411,8 +406,7 @@ async def wallet_get(request: web.BaseRequest): @request_schema(CreateWalletRequestSchema) @response_schema(CreateWalletResponseSchema(), 200, description="") async def wallet_create(request: web.BaseRequest): - """ - Request handler for adding a new subwallet for handling by the agent. + """Request handler for adding a new subwallet for handling by the agent. Args: request: aiohttp request object @@ -473,8 +467,7 @@ async def wallet_create(request: web.BaseRequest): @request_schema(UpdateWalletRequestSchema) @response_schema(WalletRecordSchema(), 200, description="") async def wallet_update(request: web.BaseRequest): - """ - Request handler for updating a existing subwallet for handling by the agent. + """Request handler for updating a existing subwallet for handling by the agent. Args: request: aiohttp request object @@ -531,8 +524,7 @@ async def wallet_update(request: web.BaseRequest): @request_schema(CreateWalletTokenRequestSchema) @response_schema(CreateWalletTokenResponseSchema(), 200, description="") async def wallet_create_token(request: web.BaseRequest): - """ - Request handler for creating an authorization token for a specific subwallet. + """Request handler for creating an authorization token for a specific subwallet. Args: request: aiohttp request object @@ -576,8 +568,7 @@ async def wallet_create_token(request: web.BaseRequest): @request_schema(RemoveWalletRequestSchema) @response_schema(MultitenantModuleResponseSchema(), 200, description="") async def wallet_remove(request: web.BaseRequest): - """ - Request handler to remove a subwallet from agent and storage. + """Request handler to remove a subwallet from agent and storage. Args: request: aiohttp request object. diff --git a/aries_cloudagent/multitenant/base.py b/aries_cloudagent/multitenant/base.py index 6d07b52867..c71eb8ac8c 100644 --- a/aries_cloudagent/multitenant/base.py +++ b/aries_cloudagent/multitenant/base.py @@ -60,8 +60,7 @@ async def get_default_mediator(self) -> Optional[MediationRecord]: async def _wallet_name_exists( self, session: ProfileSession, wallet_name: str ) -> bool: - """ - Check whether wallet with specified wallet name already exists. + """Check whether wallet with specified wallet name already exists. Besides checking for wallet records, it will also check if the base wallet diff --git a/aries_cloudagent/multitenant/manager_provider.py b/aries_cloudagent/multitenant/manager_provider.py index 7988753b36..4c986d2f67 100644 --- a/aries_cloudagent/multitenant/manager_provider.py +++ b/aries_cloudagent/multitenant/manager_provider.py @@ -12,8 +12,7 @@ class MultitenantManagerProvider(BaseProvider): - """ - Multitenant manager provider. + """Multitenant manager provider. Decides which manager to use based on the settings. """ diff --git a/aries_cloudagent/multitenant/tests/test_askar_profile_manager.py b/aries_cloudagent/multitenant/tests/test_askar_profile_manager.py index 5bbc1d926c..5e2c8c1384 100644 --- a/aries_cloudagent/multitenant/tests/test_askar_profile_manager.py +++ b/aries_cloudagent/multitenant/tests/test_askar_profile_manager.py @@ -67,8 +67,8 @@ def side_effect(context, provision): wallet_config_settings_argument.get("wallet.name") == self.DEFAULT_MULTIENANT_WALLET_NAME ) - assert wallet_config_settings_argument.get("wallet.id") == None - assert wallet_config_settings_argument.get("auto_provision") == True + assert wallet_config_settings_argument.get("wallet.id") is None + assert wallet_config_settings_argument.get("auto_provision") is True assert wallet_config_settings_argument.get("wallet.type") == "askar" AskarProfile.assert_called_with( sub_wallet_profile.opened, sub_wallet_profile_context, profile_id="test" @@ -79,7 +79,7 @@ def side_effect(context, provision): ) assert sub_wallet_profile_context.settings.get("wallet.name") == "test_name" assert sub_wallet_profile_context.settings.get("wallet.type") == "test_type" - assert sub_wallet_profile_context.settings.get("mediation.open") == True + assert sub_wallet_profile_context.settings.get("mediation.open") is True assert ( sub_wallet_profile_context.settings.get("mediation.invite") == "http://invite.com" @@ -88,7 +88,7 @@ def side_effect(context, provision): sub_wallet_profile_context.settings.get("mediation.default_id") == "24a96ef5" ) - assert sub_wallet_profile_context.settings.get("mediation.clear") == True + assert sub_wallet_profile_context.settings.get("mediation.clear") is True assert ( sub_wallet_profile_context.settings.get("wallet.id") == wallet_record.wallet_id diff --git a/aries_cloudagent/multitenant/tests/test_base.py b/aries_cloudagent/multitenant/tests/test_base.py index 1e28b90b18..b908b6b0a1 100644 --- a/aries_cloudagent/multitenant/tests/test_base.py +++ b/aries_cloudagent/multitenant/tests/test_base.py @@ -13,7 +13,6 @@ MediationRecord, ) from ...protocols.coordinate_mediation.v1_0.route_manager import RouteManager -from ...protocols.routing.v1_0.manager import RoutingManager from ...protocols.routing.v1_0.models.route_record import RouteRecord from ...storage.error import StorageNotFoundError from ...storage.in_memory import InMemoryStorage diff --git a/aries_cloudagent/multitenant/tests/test_cache.py b/aries_cloudagent/multitenant/tests/test_cache.py index ae7dbcc303..ab59847821 100644 --- a/aries_cloudagent/multitenant/tests/test_cache.py +++ b/aries_cloudagent/multitenant/tests/test_cache.py @@ -59,7 +59,7 @@ def test_cleanup(): cache.put("2", MockProfile()) assert len(cache.profiles) == 1 - assert cache.get("1") == None + assert cache.get("1") is None def test_cleanup_lru(): diff --git a/aries_cloudagent/multitenant/tests/test_manager.py b/aries_cloudagent/multitenant/tests/test_manager.py index c851369c11..8a8dcafe3e 100644 --- a/aries_cloudagent/multitenant/tests/test_manager.py +++ b/aries_cloudagent/multitenant/tests/test_manager.py @@ -125,15 +125,15 @@ def side_effect(context, provision): self.profile.context, wallet_record ) - assert profile.settings.get("wallet.recreate") == False - assert profile.settings.get("wallet.seed") == None - assert profile.settings.get("wallet.rekey") == None - assert profile.settings.get("wallet.name") == None - assert profile.settings.get("wallet.type") == None - assert profile.settings.get("mediation.open") == None - assert profile.settings.get("mediation.invite") == None - assert profile.settings.get("mediation.default_id") == None - assert profile.settings.get("mediation.clear") == None + assert profile.settings.get("wallet.recreate") is False + assert profile.settings.get("wallet.seed") is None + assert profile.settings.get("wallet.rekey") is None + assert profile.settings.get("wallet.name") is None + assert profile.settings.get("wallet.type") is None + assert profile.settings.get("mediation.open") is None + assert profile.settings.get("mediation.invite") is None + assert profile.settings.get("mediation.default_id") is None + assert profile.settings.get("mediation.clear") is None async def test_get_wallet_profile_settings_reset_overwrite(self): wallet_record = WalletRecord( @@ -164,15 +164,15 @@ def side_effect(context, provision): self.profile.context, wallet_record ) - assert profile.settings.get("wallet.recreate") == True + assert profile.settings.get("wallet.recreate") is True assert profile.settings.get("wallet.seed") == "test_seed" assert profile.settings.get("wallet.rekey") == "test_rekey" assert profile.settings.get("wallet.name") == "test_name" assert profile.settings.get("wallet.type") == "test_type" - assert profile.settings.get("mediation.open") == True + assert profile.settings.get("mediation.open") is True assert profile.settings.get("mediation.invite") == "http://invite.com" assert profile.settings.get("mediation.default_id") == "24a96ef5" - assert profile.settings.get("mediation.clear") == True + assert profile.settings.get("mediation.clear") is True async def test_update_wallet_update_wallet_profile(self): with async_mock.patch.object( diff --git a/aries_cloudagent/multitenant/tests/test_route_manager.py b/aries_cloudagent/multitenant/tests/test_route_manager.py index 200bc62a7b..e4a537b7d1 100644 --- a/aries_cloudagent/multitenant/tests/test_route_manager.py +++ b/aries_cloudagent/multitenant/tests/test_route_manager.py @@ -4,7 +4,6 @@ from ...core.in_memory import InMemoryProfile from ...core.profile import Profile from ...messaging.responder import BaseResponder, MockResponder -from ...messaging.responder import BaseResponder, MockResponder from ...protocols.coordinate_mediation.v1_0.models.mediation_record import ( MediationRecord, ) diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/base_service.py b/aries_cloudagent/protocols/actionmenu/v1_0/base_service.py index f5a6959f6f..4b0f2e19d9 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/base_service.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/base_service.py @@ -34,8 +34,7 @@ async def get_active_menu( connection: ConnRecord = None, thread_id: str = None, ) -> Menu: - """ - Render the current menu. + """Render the current menu. Args: profile: The profile @@ -52,8 +51,7 @@ async def perform_menu_action( connection: ConnRecord = None, thread_id: str = None, ) -> AgentMessage: - """ - Perform an action defined by the active menu. + """Perform an action defined by the active menu. Args: profile: The profile diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/driver_service.py b/aries_cloudagent/protocols/actionmenu/v1_0/driver_service.py index 55ce6c6f2b..3133f8135c 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/driver_service.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/driver_service.py @@ -21,8 +21,7 @@ async def get_active_menu( connection: ConnRecord = None, thread_id: str = None, ) -> Menu: - """ - Render the current menu. + """Render the current menu. Args: profile: The profile @@ -46,8 +45,7 @@ async def perform_menu_action( connection: ConnRecord = None, thread_id: str = None, ) -> AgentMessage: - """ - Perform an action defined by the active menu. + """Perform an action defined by the active menu. Args: profile: The profile diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_handler.py index 6eb7a5ebe5..30ddd66fa3 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_handler.py @@ -14,8 +14,7 @@ class MenuHandler(BaseHandler): """Message handler class for action menus.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for action menus. + """Message handler logic for action menus. Args: context: request context diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py index 41414c5b75..905e039ce8 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py @@ -14,8 +14,7 @@ class MenuRequestHandler(BaseHandler): """Message handler class for action menu requests.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for action menu requests. + """Message handler logic for action menu requests. Args: context: request context diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py index e8338111d2..5e38bc90f3 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py @@ -14,8 +14,7 @@ class PerformHandler(BaseHandler): """Message handler class for action menu perform requests.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for action menu perform requests. + """Message handler logic for action menu perform requests. Args: context: request context diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_menu_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_menu_handler.py index ffdcefba34..082dfab66a 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_menu_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_menu_handler.py @@ -1,4 +1,3 @@ -import pytest from asynctest import ( mock as async_mock, TestCase as AsyncTestCase, diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_menu_request_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_menu_request_handler.py index 9e75ddcea5..dcf578581f 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_menu_request_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_menu_request_handler.py @@ -1,4 +1,3 @@ -import pytest from asynctest import ( mock as async_mock, TestCase as AsyncTestCase, diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_perform_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_perform_handler.py index 229fda6882..76d3b38d04 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_perform_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/tests/test_perform_handler.py @@ -1,4 +1,3 @@ -import pytest from asynctest import ( mock as async_mock, TestCase as AsyncTestCase, diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/messages/menu.py b/aries_cloudagent/protocols/actionmenu/v1_0/messages/menu.py index 2594455715..07b2034d4c 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/messages/menu.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/messages/menu.py @@ -30,8 +30,7 @@ def __init__( options: Sequence[MenuOption] = None, **kwargs, ): - """ - Initialize a menu object. + """Initialize a menu object. Args: title: The menu title diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/messages/perform.py b/aries_cloudagent/protocols/actionmenu/v1_0/messages/perform.py index 360718bf11..252387d2a9 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/messages/perform.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/messages/perform.py @@ -21,8 +21,7 @@ class Meta: schema_class = "PerformSchema" def __init__(self, *, name: str = None, params: Mapping[str, str] = None, **kwargs): - """ - Initialize a Perform object. + """Initialize a Perform object. Args: name: The name of the menu option diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_menu.py b/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_menu.py index aff2bf0b35..2e1094b4fb 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_menu.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_menu.py @@ -7,7 +7,7 @@ from ...models.menu_option import MenuOption from ...message_types import MENU, PROTOCOL_PACKAGE -from ..menu import Menu, MenuSchema +from ..menu import Menu class TestConfig: @@ -84,4 +84,4 @@ def test_serialize(self, mock_menu_schema_dump): def test_make_model(self): data = self.menu.serialize() model_instance = Menu.deserialize(data) - assert type(model_instance) is type(self.menu) + assert isinstance(model_instance, type(self.menu)) diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_menu_request.py b/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_menu_request.py index 1a9dfd5fd4..69ce582851 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_menu_request.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_menu_request.py @@ -4,7 +4,7 @@ from ...message_types import MENU_REQUEST, PROTOCOL_PACKAGE -from ..menu_request import MenuRequest, MenuRequestSchema +from ..menu_request import MenuRequest class TestMenuRequest(TestCase): @@ -43,4 +43,4 @@ def test_serialize(self, mock_menu_request_schema_dump): def test_make_model(self): data = self.menu_request.serialize() model_instance = MenuRequest.deserialize(data) - assert type(model_instance) is type(self.menu_request) + assert isinstance(model_instance, type(self.menu_request)) diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_perform.py b/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_perform.py index 3a868701b1..404925e403 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_perform.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/messages/tests/test_perform.py @@ -4,7 +4,7 @@ from ...message_types import PERFORM, PROTOCOL_PACKAGE -from ..perform import Perform, PerformSchema +from ..perform import Perform class TestPerform(TestCase): @@ -47,4 +47,4 @@ def test_serialize(self, mock_perform_schema_dump): def test_make_model(self): data = self.perform.serialize() model_instance = Perform.deserialize(data) - assert type(model_instance) is type(self.perform) + assert isinstance(model_instance, type(self.perform)) diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_form.py b/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_form.py index f829568c38..8856226da8 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_form.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_form.py @@ -24,8 +24,7 @@ def __init__( params: Sequence[MenuFormParam] = None, submit_label: str = None, ): - """ - Initialize a MenuForm instance. + """Initialize a MenuForm instance. Args: title: The menu form title diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_form_param.py b/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_form_param.py index a2d91479d8..9455e5a656 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_form_param.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_form_param.py @@ -23,8 +23,7 @@ def __init__( input_type: str = None, required: bool = None, ): - """ - Initialize a MenuFormParam instance. + """Initialize a MenuFormParam instance. Args: name: The parameter name diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_option.py b/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_option.py index c9544770bb..12b154854b 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_option.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/models/menu_option.py @@ -23,8 +23,7 @@ def __init__( disabled: bool = None, form: MenuForm = None, ): - """ - Initialize a MenuOption instance. + """Initialize a MenuOption instance. Args: name: The menu option name (unique ID) diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/routes.py b/aries_cloudagent/protocols/actionmenu/v1_0/routes.py index 9b35f2ec5c..c9c94af9d6 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/routes.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/routes.py @@ -96,8 +96,7 @@ class ActionMenuFetchResultSchema(OpenAPISchema): @match_info_schema(MenuConnIdMatchInfoSchema()) @response_schema(ActionMenuModulesResultSchema(), 200, description="") async def actionmenu_close(request: web.BaseRequest): - """ - Request handler for closing the menu associated with a connection. + """Request handler for closing the menu associated with a connection. Args: request: aiohttp request object @@ -124,8 +123,7 @@ async def actionmenu_close(request: web.BaseRequest): @match_info_schema(MenuConnIdMatchInfoSchema()) @response_schema(ActionMenuFetchResultSchema(), 200, description="") async def actionmenu_fetch(request: web.BaseRequest): - """ - Request handler for fetching the previously-received menu for a connection. + """Request handler for fetching the previously-received menu for a connection. Args: request: aiohttp request object @@ -144,8 +142,7 @@ async def actionmenu_fetch(request: web.BaseRequest): @request_schema(PerformRequestSchema()) @response_schema(ActionMenuModulesResultSchema(), 200, description="") async def actionmenu_perform(request: web.BaseRequest): - """ - Request handler for performing a menu action. + """Request handler for performing a menu action. Args: request: aiohttp request object @@ -174,8 +171,7 @@ async def actionmenu_perform(request: web.BaseRequest): @match_info_schema(MenuConnIdMatchInfoSchema()) @response_schema(ActionMenuModulesResultSchema(), 200, description="") async def actionmenu_request(request: web.BaseRequest): - """ - Request handler for requesting a menu from the connection target. + """Request handler for requesting a menu from the connection target. Args: request: aiohttp request object @@ -205,8 +201,7 @@ async def actionmenu_request(request: web.BaseRequest): @request_schema(SendMenuSchema()) @response_schema(ActionMenuModulesResultSchema(), 200, description="") async def actionmenu_send(request: web.BaseRequest): - """ - Request handler for requesting a menu from the connection target. + """Request handler for requesting a menu from the connection target. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py b/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py index 6e9798dd7b..93bd91760f 100644 --- a/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py +++ b/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py @@ -13,8 +13,7 @@ class BasicMessageHandler(BaseHandler): """Message handler class for basic messages.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for basic messages. + """Message handler logic for basic messages. Args: context: request context diff --git a/aries_cloudagent/protocols/basicmessage/v1_0/messages/basicmessage.py b/aries_cloudagent/protocols/basicmessage/v1_0/messages/basicmessage.py index c635b394c3..22d867f401 100644 --- a/aries_cloudagent/protocols/basicmessage/v1_0/messages/basicmessage.py +++ b/aries_cloudagent/protocols/basicmessage/v1_0/messages/basicmessage.py @@ -34,8 +34,7 @@ def __init__( localization: str = None, **kwargs, ): - """ - Initialize basic message object. + """Initialize basic message object. Args: sent_time: Time message was sent diff --git a/aries_cloudagent/protocols/basicmessage/v1_0/routes.py b/aries_cloudagent/protocols/basicmessage/v1_0/routes.py index 3ba8557135..7fffa930e1 100644 --- a/aries_cloudagent/protocols/basicmessage/v1_0/routes.py +++ b/aries_cloudagent/protocols/basicmessage/v1_0/routes.py @@ -40,8 +40,7 @@ class BasicConnIdMatchInfoSchema(OpenAPISchema): @request_schema(SendMessageSchema()) @response_schema(BasicMessageModuleResponseSchema(), 200, description="") async def connections_send_message(request: web.BaseRequest): - """ - Request handler for sending a basic message to a connection. + """Request handler for sending a basic message to a connection. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_invitation_handler.py b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_invitation_handler.py index 5c978dacd8..07da95b91e 100644 --- a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_invitation_handler.py +++ b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_invitation_handler.py @@ -14,8 +14,7 @@ class ConnectionInvitationHandler(BaseHandler): """Handler class for connection invitations.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle connection invitation. + """Handle connection invitation. Args: context: Request context diff --git a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py index 82eb79cf81..73efd9ecf8 100644 --- a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py +++ b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py @@ -12,8 +12,7 @@ class ConnectionRequestHandler(BaseHandler): """Handler class for connection requests.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle connection request. + """Handle connection request. Args: context: Request context diff --git a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py index c053282901..5bb79269db 100644 --- a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py +++ b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py @@ -16,8 +16,7 @@ class ConnectionResponseHandler(BaseHandler): """Handler class for connection responses.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle connection response. + """Handle connection response. Args: context: Request context diff --git a/aries_cloudagent/protocols/connections/v1_0/handlers/tests/test_invitation_handler.py b/aries_cloudagent/protocols/connections/v1_0/handlers/tests/test_invitation_handler.py index 12c90fb67c..3e524d9a19 100644 --- a/aries_cloudagent/protocols/connections/v1_0/handlers/tests/test_invitation_handler.py +++ b/aries_cloudagent/protocols/connections/v1_0/handlers/tests/test_invitation_handler.py @@ -1,6 +1,5 @@ import pytest -from ......messaging.base_handler import HandlerException from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder from ......transport.inbound.receipt import MessageReceipt diff --git a/aries_cloudagent/protocols/connections/v1_0/manager.py b/aries_cloudagent/protocols/connections/v1_0/manager.py index 0ec6e75304..20e4c90dfb 100644 --- a/aries_cloudagent/protocols/connections/v1_0/manager.py +++ b/aries_cloudagent/protocols/connections/v1_0/manager.py @@ -35,8 +35,7 @@ class ConnectionManager(BaseConnectionManager): """Class for managing connections.""" def __init__(self, profile: Profile): - """ - Initialize a ConnectionManager. + """Initialize a ConnectionManager. Args: profile: The profile for this connection manager @@ -47,8 +46,7 @@ def __init__(self, profile: Profile): @property def profile(self) -> Profile: - """ - Accessor for the current profile. + """Accessor for the current profile. Returns: The profile for this connection manager @@ -69,8 +67,7 @@ async def create_invitation( metadata: dict = None, mediation_id: str = None, ) -> Tuple[ConnRecord, ConnectionInvitation]: - """ - Generate new connection invitation. + """Generate new connection invitation. This interaction represents an out-of-band communication channel. In the future and in practice, these sort of invitations will be received over any number of @@ -247,8 +244,7 @@ async def receive_invitation( alias: Optional[str] = None, mediation_id: Optional[str] = None, ) -> ConnRecord: - """ - Create a new connection record to track a received invitation. + """Create a new connection record to track a received invitation. Args: invitation: The `ConnectionInvitation` to store @@ -329,8 +325,7 @@ async def create_request( my_endpoint: str = None, mediation_id: str = None, ) -> ConnectionRequest: - """ - Create a new connection request for a previously-received invitation. + """Create a new connection request for a previously-received invitation. Args: connection: The `ConnRecord` representing the invitation to accept @@ -414,8 +409,7 @@ async def receive_request( request: ConnectionRequest, receipt: MessageReceipt, ) -> ConnRecord: - """ - Receive and store a connection request. + """Receive and store a connection request. Args: request: The `ConnectionRequest` to accept @@ -577,8 +571,7 @@ async def create_response( my_endpoint: str = None, mediation_id: str = None, ) -> ConnectionResponse: - """ - Create a connection response for a received connection request. + """Create a connection response for a received connection request. Args: connection: The `ConnRecord` with a pending connection request @@ -692,8 +685,7 @@ async def create_response( async def accept_response( self, response: ConnectionResponse, receipt: MessageReceipt ) -> ConnRecord: - """ - Accept a connection response. + """Accept a connection response. Process a ConnectionResponse message by looking up the connection request and setting up the pairwise connection. diff --git a/aries_cloudagent/protocols/connections/v1_0/messages/connection_invitation.py b/aries_cloudagent/protocols/connections/v1_0/messages/connection_invitation.py index 56acb699c4..79a402b356 100644 --- a/aries_cloudagent/protocols/connections/v1_0/messages/connection_invitation.py +++ b/aries_cloudagent/protocols/connections/v1_0/messages/connection_invitation.py @@ -42,8 +42,7 @@ def __init__( image_url: str = None, **kwargs, ): - """ - Initialize connection invitation object. + """Initialize connection invitation object. Args: label: Optional label for connection invitation @@ -62,8 +61,7 @@ def __init__( self.image_url = image_url def to_url(self, base_url: str = None) -> str: - """ - Convert an invitation to URL format for sharing. + """Convert an invitation to URL format for sharing. Returns: An invite url @@ -76,8 +74,7 @@ def to_url(self, base_url: str = None) -> str: @classmethod def from_url(cls, url: str) -> "ConnectionInvitation": - """ - Parse a URL-encoded invitation into a `ConnectionInvitation` message. + """Parse a URL-encoded invitation into a `ConnectionInvitation` message. Args: url: Url to decode @@ -162,8 +159,7 @@ class Meta: @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields. + """Validate schema fields. Args: data: The data to validate diff --git a/aries_cloudagent/protocols/connections/v1_0/messages/connection_request.py b/aries_cloudagent/protocols/connections/v1_0/messages/connection_request.py index 8ab7deeb2e..38edfe408b 100644 --- a/aries_cloudagent/protocols/connections/v1_0/messages/connection_request.py +++ b/aries_cloudagent/protocols/connections/v1_0/messages/connection_request.py @@ -29,8 +29,7 @@ def __init__( image_url: str = None, **kwargs, ): - """ - Initialize connection request object. + """Initialize connection request object. Args: connection (ConnectionDetail): Connection details object diff --git a/aries_cloudagent/protocols/connections/v1_0/messages/connection_response.py b/aries_cloudagent/protocols/connections/v1_0/messages/connection_response.py index 5472df6439..07824870bf 100644 --- a/aries_cloudagent/protocols/connections/v1_0/messages/connection_response.py +++ b/aries_cloudagent/protocols/connections/v1_0/messages/connection_response.py @@ -24,8 +24,7 @@ class Meta: message_type = CONNECTION_RESPONSE def __init__(self, *, connection: ConnectionDetail = None, **kwargs): - """ - Initialize connection response object. + """Initialize connection response object. Args: connection: Connection details object diff --git a/aries_cloudagent/protocols/connections/v1_0/messages/problem_report.py b/aries_cloudagent/protocols/connections/v1_0/messages/problem_report.py index 815b5b1291..7f118d19cd 100644 --- a/aries_cloudagent/protocols/connections/v1_0/messages/problem_report.py +++ b/aries_cloudagent/protocols/connections/v1_0/messages/problem_report.py @@ -33,8 +33,7 @@ class Meta: schema_class = "ConnectionProblemReportSchema" def __init__(self, *, problem_code: str = None, explain: str = None, **kwargs): - """ - Initialize a ProblemReport message instance. + """Initialize a ProblemReport message instance. Args: explain: The localized error explanation diff --git a/aries_cloudagent/protocols/connections/v1_0/models/connection_detail.py b/aries_cloudagent/protocols/connections/v1_0/models/connection_detail.py index 3c5282a55b..dfe460c464 100644 --- a/aries_cloudagent/protocols/connections/v1_0/models/connection_detail.py +++ b/aries_cloudagent/protocols/connections/v1_0/models/connection_detail.py @@ -11,8 +11,7 @@ class DIDDocWrapper(fields.Field): """Field that loads and serializes DIDDoc.""" def _serialize(self, value, attr, obj, **kwargs): - """ - Serialize the DIDDoc. + """Serialize the DIDDoc. Args: value: The value to serialize @@ -24,8 +23,7 @@ def _serialize(self, value, attr, obj, **kwargs): return value.serialize() def _deserialize(self, value, attr=None, data=None, **kwargs): - """ - Deserialize a value into a DIDDoc. + """Deserialize a value into a DIDDoc. Args: value: The value to deserialize @@ -46,8 +44,7 @@ class Meta: schema_class = "ConnectionDetailSchema" def __init__(self, *, did: str = None, did_doc: DIDDoc = None, **kwargs): - """ - Initialize a ConnectionDetail instance. + """Initialize a ConnectionDetail instance. Args: did: DID for the connection detail @@ -60,8 +57,7 @@ def __init__(self, *, did: str = None, did_doc: DIDDoc = None, **kwargs): @property def did(self) -> str: - """ - Accessor for the connection DID. + """Accessor for the connection DID. Returns: The DID for this connection @@ -71,8 +67,7 @@ def did(self) -> str: @property def did_doc(self) -> DIDDoc: - """ - Accessor for the connection DID Document. + """Accessor for the connection DID Document. Returns: The DIDDoc for this connection diff --git a/aries_cloudagent/protocols/connections/v1_0/routes.py b/aries_cloudagent/protocols/connections/v1_0/routes.py index d87fc124e1..5083a0196a 100644 --- a/aries_cloudagent/protocols/connections/v1_0/routes.py +++ b/aries_cloudagent/protocols/connections/v1_0/routes.py @@ -430,8 +430,7 @@ def connection_sort_key(conn): @querystring_schema(ConnectionsListQueryStringSchema()) @response_schema(ConnectionListSchema(), 200, description="") async def connections_list(request: web.BaseRequest): - """ - Request handler for searching connection records. + """Request handler for searching connection records. Args: request: aiohttp request object @@ -459,13 +458,11 @@ async def connections_list(request: web.BaseRequest): if request.query.get("alias"): post_filter["alias"] = request.query["alias"] if request.query.get("state"): - post_filter["state"] = [ - v for v in ConnRecord.State.get(request.query["state"]).value - ] + post_filter["state"] = list(ConnRecord.State.get(request.query["state"]).value) if request.query.get("their_role"): - post_filter["their_role"] = [ - v for v in ConnRecord.Role.get(request.query["their_role"]).value - ] + post_filter["their_role"] = list( + ConnRecord.Role.get(request.query["their_role"]).value + ) if request.query.get("connection_protocol"): post_filter["connection_protocol"] = request.query["connection_protocol"] @@ -487,8 +484,7 @@ async def connections_list(request: web.BaseRequest): @match_info_schema(ConnectionsConnIdMatchInfoSchema()) @response_schema(ConnRecordSchema(), 200, description="") async def connections_retrieve(request: web.BaseRequest): - """ - Request handler for fetching a single connection record. + """Request handler for fetching a single connection record. Args: request: aiohttp request object @@ -517,8 +513,7 @@ async def connections_retrieve(request: web.BaseRequest): @match_info_schema(ConnectionsConnIdMatchInfoSchema()) @response_schema(EndpointsResultSchema(), 200, description="") async def connections_endpoints(request: web.BaseRequest): - """ - Request handler for fetching connection endpoints. + """Request handler for fetching connection endpoints. Args: request: aiohttp request object @@ -601,8 +596,7 @@ async def connections_metadata_set(request: web.BaseRequest): @request_schema(CreateInvitationRequestSchema()) @response_schema(InvitationResultSchema(), 200, description="") async def connections_create_invitation(request: web.BaseRequest): - """ - Request handler for creating a new connection invitation. + """Request handler for creating a new connection invitation. Args: request: aiohttp request object @@ -675,8 +669,7 @@ async def connections_create_invitation(request: web.BaseRequest): @request_schema(ReceiveInvitationRequestSchema()) @response_schema(ConnRecordSchema(), 200, description="") async def connections_receive_invitation(request: web.BaseRequest): - """ - Request handler for receiving a new connection invitation. + """Request handler for receiving a new connection invitation. Args: request: aiohttp request object @@ -717,8 +710,7 @@ async def connections_receive_invitation(request: web.BaseRequest): @querystring_schema(AcceptInvitationQueryStringSchema()) @response_schema(ConnRecordSchema(), 200, description="") async def connections_accept_invitation(request: web.BaseRequest): - """ - Request handler for accepting a stored connection invitation. + """Request handler for accepting a stored connection invitation. Args: request: aiohttp request object @@ -768,8 +760,7 @@ async def connections_accept_invitation(request: web.BaseRequest): @querystring_schema(AcceptRequestQueryStringSchema()) @response_schema(ConnRecordSchema(), 200, description="") async def connections_accept_request(request: web.BaseRequest): - """ - Request handler for accepting a stored connection request. + """Request handler for accepting a stored connection request. Args: request: aiohttp request object @@ -805,8 +796,7 @@ async def connections_accept_request(request: web.BaseRequest): @match_info_schema(ConnIdRefIdMatchInfoSchema()) @response_schema(ConnectionModuleResponseSchema(), 200, description="") async def connections_establish_inbound(request: web.BaseRequest): - """ - Request handler for setting the inbound connection on a connection record. + """Request handler for setting the inbound connection on a connection record. Args: request: aiohttp request object @@ -836,8 +826,7 @@ async def connections_establish_inbound(request: web.BaseRequest): @match_info_schema(ConnectionsConnIdMatchInfoSchema()) @response_schema(ConnectionModuleResponseSchema, 200, description="") async def connections_remove(request: web.BaseRequest): - """ - Request handler for removing a connection record. + """Request handler for removing a connection record. Args: request: aiohttp request object @@ -865,8 +854,7 @@ async def connections_remove(request: web.BaseRequest): @request_schema(ConnectionStaticRequestSchema()) @response_schema(ConnectionStaticResultSchema(), 200, description="") async def connections_create_static(request: web.BaseRequest): - """ - Request handler for creating a new static connection. + """Request handler for creating a new static connection. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/connections/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/connections/v1_0/tests/test_manager.py index 8bf13a35a9..f8fdc88756 100644 --- a/aries_cloudagent/protocols/connections/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/connections/v1_0/tests/test_manager.py @@ -1,26 +1,12 @@ -from unittest.mock import call - from asynctest import TestCase as AsyncTestCase, mock as async_mock -from multiformats import multibase, multicodec -from pydid import DIDDocument, DIDDocumentBuilder -from pydid.verification_method import ( - Ed25519VerificationKey2018, - Ed25519VerificationKey2020, - JsonWebKey2020, -) - -from .. import manager as test_module + from .....cache.base import BaseCache from .....cache.in_memory import InMemoryCache -from .....config.base import InjectionError -from .....connections.base_manager import BaseConnectionManagerError from .....connections.models.conn_record import ConnRecord -from .....connections.models.connection_target import ConnectionTarget from .....connections.models.diddoc import DIDDoc, PublicKey, PublicKeyType, Service from .....core.in_memory import InMemoryProfile from .....core.oob_processor import OobMessageProcessor from .....core.profile import ProfileSession -from .....did.did_key import DIDKey from .....messaging.responder import BaseResponder, MockResponder from .....multitenant.base import BaseMultitenantManager from .....multitenant.manager import MultitenantManager @@ -31,15 +17,12 @@ from .....transport.inbound.receipt import MessageReceipt from .....wallet.base import DIDInfo from .....wallet.did_method import DIDMethods, SOV -from .....wallet.error import WalletNotFoundError from .....wallet.in_memory import InMemoryWallet from .....wallet.key_type import ED25519 -from .....wallet.util import b58_to_bytes, bytes_to_b64 from ....coordinate_mediation.v1_0.manager import MediationManager from ....coordinate_mediation.v1_0.messages.mediate_request import MediationRequest from ....coordinate_mediation.v1_0.models.mediation_record import MediationRecord from ....coordinate_mediation.v1_0.route_manager import RouteManager -from ....discovery.v2_0.manager import V20DiscoveryMgr from ..manager import ConnectionManager, ConnectionManagerError from ..messages.connection_invitation import ConnectionInvitation from ..messages.connection_request import ConnectionRequest diff --git a/aries_cloudagent/protocols/connections/v1_0/tests/test_routes.py b/aries_cloudagent/protocols/connections/v1_0/tests/test_routes.py index adc23cf242..0dc8800fa6 100644 --- a/aries_cloudagent/protocols/connections/v1_0/tests/test_routes.py +++ b/aries_cloudagent/protocols/connections/v1_0/tests/test_routes.py @@ -100,7 +100,7 @@ async def test_connections_list(self): "invitation_msg_id": "dummy_msg", }, post_filter_positive={ - "their_role": [v for v in ConnRecord.Role.REQUESTER.value], + "their_role": list(ConnRecord.Role.REQUESTER.value), "connection_protocol": ConnRecord.Protocol.RFC_0160.aries_protocol, }, alt=True, diff --git a/aries_cloudagent/protocols/coordinate_mediation/mediation_invite_store.py b/aries_cloudagent/protocols/coordinate_mediation/mediation_invite_store.py index 4c12330f10..0e0eb85078 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/mediation_invite_store.py +++ b/aries_cloudagent/protocols/coordinate_mediation/mediation_invite_store.py @@ -1,5 +1,4 @@ -""" -Storage management for configuration-provided mediation invite. +"""Storage management for configuration-provided mediation invite. Handle storage and retrieval of mediation invites provided through arguments. Enables having the mediation invite config be the same @@ -30,8 +29,7 @@ def from_json(json_invite_record: str) -> "MediationInviteRecord": @staticmethod def unused(invite: str) -> "MediationInviteRecord": - """ - :param invite: invite string as provided by the mediator. + """:param invite: invite string as provided by the mediator. :return: An unused mediation invitation for the given invite string """ @@ -61,8 +59,7 @@ async def __retrieve_record(self, key: str) -> Optional[StorageRecord]: async def store( self, mediation_invite: MediationInviteRecord ) -> MediationInviteRecord: - """ - Store the mediator's invite for further use when starting the agent. + """Store the mediator's invite for further use when starting the agent. Update the currently stored invite if one already exists. This assumes a new invite and as such, marks it as unused. @@ -102,8 +99,7 @@ async def __retrieve(self) -> Optional[MediationInviteRecord]: async def __update_mediation_record( self, provided_mediation_invitation: str ) -> MediationInviteRecord: - """ - Update the stored invitation when a new invitation is provided. + """Update the stored invitation when a new invitation is provided. Stored value is only updated if `provided_mediation_invitation` has changed. Updated record is marked as unused. @@ -121,8 +117,7 @@ async def __update_mediation_record( return default_invite async def mark_default_invite_as_used(self): - """ - Mark the currently stored invitation as used if one exists. + """Mark the currently stored invitation as used if one exists. :raises NoDefaultMediationInviteException: if trying to mark invite as used when there is no invite stored. @@ -141,8 +136,7 @@ async def mark_default_invite_as_used(self): async def get_mediation_invite_record( self, provided_mediation_invitation: Optional[str] ) -> Optional[MediationInviteRecord]: - """ - Provide the MediationInviteRecord to use/that was used for mediation. + """Provide the MediationInviteRecord to use/that was used for mediation. Returned record may have been used already. diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/problem_report_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/problem_report_handler.py index 8a50dbf1c9..f6ae021b80 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/problem_report_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/problem_report_handler.py @@ -8,15 +8,13 @@ class CMProblemReportHandler(BaseHandler): - """ - Handler class for Coordinate Mediation Problem Report Message. + """Handler class for Coordinate Mediation Problem Report Message. Updates the ConnRecord Metadata state. """ async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Coordinate mediation problem report message handler. + """Coordinate mediation problem report message handler. Args: context: Request context diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_query_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_query_handler.py index fd216be4a7..064c06dd4e 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_query_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_query_handler.py @@ -2,7 +2,6 @@ import pytest from asynctest import TestCase as AsyncTestCase -from ......config.injection_context import InjectionContext from ......connections.models.conn_record import ConnRecord from ......messaging.base_handler import HandlerException from ......messaging.request_context import RequestContext diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_update_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_update_handler.py index 141dcfa47f..f2a6830e5d 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_update_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_update_handler.py @@ -2,7 +2,6 @@ import pytest from asynctest import TestCase as AsyncTestCase -from ......config.injection_context import InjectionContext from ......connections.models.conn_record import ConnRecord from ......messaging.base_handler import HandlerException from ......messaging.request_context import RequestContext diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py index edced84569..7ec79632db 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py @@ -1,20 +1,14 @@ """Test Problem Report Handler.""" import pytest -from asynctest import mock as async_mock -from ......connections.models import connection_target from ......connections.models.conn_record import ConnRecord -from ......connections.models.diddoc import DIDDoc, PublicKey, PublicKeyType, Service from ......core.profile import ProfileSession from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder -from ......storage.base import BaseStorage -from ......storage.error import StorageNotFoundError from ......transport.inbound.receipt import MessageReceipt from ...handlers import problem_report_handler as test_module -from ...manager import MediationManagerError, MediationManager from ...messages.problem_report import CMProblemReport, ProblemReportReason diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py index fc76b311a0..426618b4f8 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py @@ -298,9 +298,7 @@ async def create_keylist_query_response( Keylist: message to return to client """ - keys = list( - map(lambda key: KeylistKey(recipient_key=key.recipient_key), keylist) - ) + keys = [KeylistKey(recipient_key=key.recipient_key) for key in keylist] return Keylist(keys=keys, pagination=None) # }}} diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_key.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_key.py index 867c9b60cb..88e7b5f3a3 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_key.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_key.py @@ -23,8 +23,7 @@ def __init__( result: str = None, **kwargs ): - """ - Initialize a KeylistKey instance. + """Initialize a KeylistKey instance. Args: recipient_key: The recipient verkey of the route diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_query_paginate.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_query_paginate.py index b18634f6a8..f7b400ce57 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_query_paginate.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_query_paginate.py @@ -14,8 +14,7 @@ class Meta: schema_class = "KeylistQueryPaginateSchema" def __init__(self, limit: int, offset: int, **kwargs): - """ - Initialize keylist query pagination object. + """Initialize keylist query pagination object. Args: limit: limit for response count diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_update_rule.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_update_rule.py index 258ea2d1ce..d66b5162b5 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_update_rule.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_update_rule.py @@ -24,8 +24,7 @@ class Meta: RULE_REMOVE = "remove" def __init__(self, recipient_key: str, action: str, **kwargs): - """ - Initialize keylist update rule object. + """Initialize keylist update rule object. Args: recipient_key: recipient key for the rule diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_updated.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_updated.py index 41f87ff19a..f151dcdcc8 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_updated.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/inner/keylist_updated.py @@ -31,8 +31,7 @@ def __init__( result: str = None, **kwargs ): - """ - Initialize a KeylistUpdated instance. + """Initialize a KeylistUpdated instance. Args: recipient_key: The recipient verkey of the route diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist.py index b1c251d328..54609028b3 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist.py @@ -32,8 +32,7 @@ def __init__( pagination: KeylistQueryPaginate = None, **kwargs, ): - """ - Initialize keylist query response object. + """Initialize keylist query response object. Args: keys: Found keys by requested query diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_query.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_query.py index f9594a0a39..6273905659 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_query.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_query.py @@ -29,8 +29,7 @@ def __init__( paginate: KeylistQueryPaginate = None, **kwargs, ): - """ - Initialize keylist query object. + """Initialize keylist query object. Args: filter: Filter for query diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_update.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_update.py index 9506ff6a19..bff32ac09d 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_update.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_update.py @@ -29,8 +29,7 @@ def __init__( updates: Sequence[KeylistUpdateRule] = None, **kwargs, ): - """ - Initialize keylist update object. + """Initialize keylist update object. Args: updates: Update rules for keylist update request diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_update_response.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_update_response.py index 1458ccf836..c14d8777f2 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_update_response.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/keylist_update_response.py @@ -30,8 +30,7 @@ def __init__( updated: Sequence[KeylistUpdated] = None, **kwargs, ): - """ - Initialize keylist update object. + """Initialize keylist update object. Args: updates: Update rules for keylist update request diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_deny.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_deny.py index 877c1e92d7..bd6496ab63 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_deny.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_deny.py @@ -29,8 +29,7 @@ def __init__( recipient_terms: Sequence[str] = None, **kwargs, ): - """ - Initialize mediation deny object. + """Initialize mediation deny object. Args: mediator_terms: Terms that were agreed by the recipient diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_grant.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_grant.py index 9c295a3eaf..587f61730a 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_grant.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_grant.py @@ -33,8 +33,7 @@ def __init__( routing_keys: Sequence[str] = None, **kwargs, ): - """ - Initialize mediation grant object. + """Initialize mediation grant object. Args: endpoint: Endpoint address for the mediation route @@ -43,7 +42,7 @@ def __init__( super(MediationGrant, self).__init__(**kwargs) self.endpoint = endpoint self.routing_keys = ( - list(normalize_from_public_key(key) for key in routing_keys) + [normalize_from_public_key(key) for key in routing_keys] if routing_keys else [] ) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_request.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_request.py index 037d4df32e..84417ab830 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_request.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/mediate_request.py @@ -29,8 +29,7 @@ def __init__( recipient_terms: Sequence[str] = None, **kwargs, ): - """ - Initialize mediation request object. + """Initialize mediation request object. Args: mediator_terms: Mediator's terms for granting mediation. diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/tests/test_problem_report.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/tests/test_problem_report.py index 880ae865e6..322ae27f5a 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/tests/test_problem_report.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/tests/test_problem_report.py @@ -2,7 +2,7 @@ import logging import pytest -from unittest import mock, TestCase +from unittest import TestCase from ......messaging.models.base import BaseModelError diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py index 7e93eaa841..5ccab85c5f 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py @@ -1,8 +1,7 @@ """Test MediationManager.""" import logging -from typing import AsyncGenerator, AsyncIterable, Iterable +from typing import AsyncIterable, Iterable -from functools import partial from asynctest import mock as async_mock import pytest @@ -21,7 +20,6 @@ ) from ..messages.inner.keylist_update_rule import KeylistUpdateRule from ..messages.inner.keylist_updated import KeylistUpdated -from ..messages.keylist_update_response import KeylistUpdateResponse from ..messages.mediate_deny import MediationDeny from ..messages.mediate_grant import MediationGrant from ..messages.mediate_request import MediationRequest @@ -251,7 +249,7 @@ async def test_get_set_get_default_mediator( record: MediationRecord, ): await record.save(session) - assert await manager.get_default_mediator() == None + assert await manager.get_default_mediator() is None await manager.set_default_mediator(record) assert await manager.get_default_mediator() == record diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py index 904f0520eb..72122aa62f 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py @@ -14,8 +14,7 @@ class DIDXCompleteHandler(BaseHandler): """Handler class for connection complete message under RFC 23 (DID exchange).""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle connection complete under RFC 23 (DID exchange). + """Handle connection complete under RFC 23 (DID exchange). Args: context: Request context diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/invitation_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/invitation_handler.py index 1ad96afa1b..4bf178512b 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/invitation_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/invitation_handler.py @@ -15,8 +15,7 @@ class InvitationHandler(BaseHandler): """Handler class for connection invitation message under RFC 23 (DID exchange).""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle connection invitation under RFC 23 (DID exchange). + """Handle connection invitation under RFC 23 (DID exchange). Args: context: Request context diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py index 736bf66a7a..b4b85eb1dc 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py @@ -14,8 +14,7 @@ class DIDXRequestHandler(BaseHandler): """Handler class for connection request message under RFC 23 (DID exchange).""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle connection request under RFC 23 (DID exchange). + """Handle connection request under RFC 23 (DID exchange). Args: context: Request context diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py index ccf17e1b60..c2c094320a 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py @@ -19,8 +19,7 @@ class DIDXResponseHandler(BaseHandler): """Handler class for DID exchange response message under RFC 23.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle DID exchange response under RFC 23. + """Handle DID exchange response under RFC 23. Args: context: Request context diff --git a/aries_cloudagent/protocols/didexchange/v1_0/manager.py b/aries_cloudagent/protocols/didexchange/v1_0/manager.py index 31aa8a1085..391ca78a10 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/manager.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/manager.py @@ -48,8 +48,7 @@ class DIDXManager(BaseConnectionManager): """Class for managing connections under RFC 23 (DID exchange).""" def __init__(self, profile: Profile): - """ - Initialize a DIDXManager. + """Initialize a DIDXManager. Args: profile: The profile for this did exchange manager @@ -60,8 +59,7 @@ def __init__(self, profile: Profile): @property def profile(self) -> Profile: - """ - Accessor for the current profile. + """Accessor for the current profile. Returns: The profile for this did exchange manager @@ -77,8 +75,7 @@ async def receive_invitation( alias: Optional[str] = None, mediation_id: Optional[str] = None, ) -> ConnRecord: # leave in didexchange as it uses a responder: not out-of-band - """ - Create a new connection record to track a received invitation. + """Create a new connection record to track a received invitation. Args: invitation: invitation to store @@ -186,8 +183,7 @@ async def create_request_implicit( goal_code: str = None, goal: str = None, ) -> ConnRecord: - """ - Create and send a request against a public DID only (no explicit invitation). + """Create and send a request against a public DID only (no explicit invitation). Args: their_public_did: public DID to which to request a connection @@ -272,8 +268,7 @@ async def create_request( goal: Optional[str] = None, use_public_did: bool = False, ) -> DIDXRequest: - """ - Create a new connection request for a previously-received invitation. + """Create a new connection request for a previously-received invitation. Args: conn_rec: The `ConnRecord` representing the invitation to accept @@ -396,8 +391,7 @@ async def receive_request( alias: Optional[str] = None, auto_accept_implicit: Optional[bool] = None, ) -> ConnRecord: - """ - Receive and store a connection request. + """Receive and store a connection request. Args: request: The `DIDXRequest` to accept @@ -587,8 +581,7 @@ async def create_response( mediation_id: Optional[str] = None, use_public_did: Optional[bool] = None, ) -> DIDXResponse: - """ - Create a connection response for a received connection request. + """Create a connection response for a received connection request. Args: conn_rec: The `ConnRecord` with a pending connection request @@ -716,8 +709,7 @@ async def accept_response( response: DIDXResponse, receipt: MessageReceipt, ) -> ConnRecord: - """ - Accept a connection response under RFC 23 (DID exchange). + """Accept a connection response under RFC 23 (DID exchange). Process a `DIDXResponse` message by looking up the connection request and setting up the pairwise connection. @@ -846,8 +838,7 @@ async def accept_complete( complete: DIDXComplete, receipt: MessageReceipt, ) -> ConnRecord: - """ - Accept a connection complete message under RFC 23 (DID exchange). + """Accept a connection complete message under RFC 23 (DID exchange). Process a `DIDXComplete` message by looking up the connection record and marking the exchange complete. @@ -945,9 +936,9 @@ async def receive_problem_report( if not report.description: raise DIDXManagerError("Missing description in problem report") - if report.description.get("code") in set( + if report.description.get("code") in { reason.value for reason in ProblemReportReason - ): + }: self._logger.info("Problem report indicates connection is abandoned") async with self.profile.session() as session: await conn_rec.abandon( diff --git a/aries_cloudagent/protocols/didexchange/v1_0/messages/request.py b/aries_cloudagent/protocols/didexchange/v1_0/messages/request.py index 501f829f92..1d7dfda0c3 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/messages/request.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/messages/request.py @@ -35,8 +35,7 @@ def __init__( goal: Optional[str] = None, **kwargs, ): - """ - Initialize DID exchange request object under RFC 23. + """Initialize DID exchange request object under RFC 23. Args: label: Label for this request diff --git a/aries_cloudagent/protocols/didexchange/v1_0/messages/response.py b/aries_cloudagent/protocols/didexchange/v1_0/messages/response.py index 6634005e66..ae00ac2181 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/messages/response.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/messages/response.py @@ -31,8 +31,7 @@ def __init__( did_doc_attach: Optional[AttachDecorator] = None, **kwargs, ): - """ - Initialize DID exchange response object under RFC 23. + """Initialize DID exchange response object under RFC 23. Args: image_url: Optional image URL for this response diff --git a/aries_cloudagent/protocols/didexchange/v1_0/routes.py b/aries_cloudagent/protocols/didexchange/v1_0/routes.py index c0a66c6cbb..abfacda882 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/routes.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/routes.py @@ -195,8 +195,7 @@ class DIDXRejectRequestSchema(OpenAPISchema): @querystring_schema(DIDXAcceptInvitationQueryStringSchema()) @response_schema(ConnRecordSchema(), 200, description="") async def didx_accept_invitation(request: web.BaseRequest): - """ - Request handler for accepting a stored connection invitation. + """Request handler for accepting a stored connection invitation. Args: request: aiohttp request object @@ -242,8 +241,7 @@ async def didx_accept_invitation(request: web.BaseRequest): @querystring_schema(DIDXCreateRequestImplicitQueryStringSchema()) @response_schema(ConnRecordSchema(), 200, description="") async def didx_create_request_implicit(request: web.BaseRequest): - """ - Request handler for creating and sending a request to an implicit invitation. + """Request handler for creating and sending a request to an implicit invitation. Args: request: aiohttp request object @@ -292,8 +290,7 @@ async def didx_create_request_implicit(request: web.BaseRequest): @request_schema(DIDXRequestSchema()) @response_schema(ConnRecordSchema(), 200, description="") async def didx_receive_request_implicit(request: web.BaseRequest): - """ - Request handler for receiving a request against public DID's implicit invitation. + """Request handler for receiving a request against public DID's implicit invitation. Args: request: aiohttp request object @@ -339,8 +336,7 @@ async def didx_receive_request_implicit(request: web.BaseRequest): @querystring_schema(DIDXAcceptRequestQueryStringSchema()) @response_schema(ConnRecordSchema(), 200, description="") async def didx_accept_request(request: web.BaseRequest): - """ - Request handler for accepting a stored connection request. + """Request handler for accepting a stored connection request. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/didexchange/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/didexchange/v1_0/tests/test_manager.py index 041fc4a982..8bcbce0603 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/tests/test_manager.py @@ -2082,7 +2082,7 @@ async def test_accept_complete(self): conn_rec = await self.manager.accept_complete(mock_complete, receipt) assert ConnRecord.State.get(conn_rec.state) is ConnRecord.State.COMPLETED - async def test_accept_complete(self): + async def test_accept_complete_with_disclose(self): mock_complete = async_mock.MagicMock() receipt = MessageReceipt(sender_did=TestConfig.test_target_did) self.context.update_settings({"auto_disclose_features": True}) diff --git a/aries_cloudagent/protocols/discovery/v1_0/manager.py b/aries_cloudagent/protocols/discovery/v1_0/manager.py index 304d8ebb0c..c01093f631 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/manager.py +++ b/aries_cloudagent/protocols/discovery/v1_0/manager.py @@ -24,8 +24,7 @@ class V10DiscoveryMgr: """Class for discover feature v1_0 under RFC 31.""" def __init__(self, profile: Profile): - """ - Initialize a V10DiscoveryMgr. + """Initialize a V10DiscoveryMgr. Args: profile: The profile for this manager @@ -35,8 +34,7 @@ def __init__(self, profile: Profile): @property def profile(self) -> Profile: - """ - Accessor for the current Profile. + """Accessor for the current Profile. Returns: The Profile for this manager diff --git a/aries_cloudagent/protocols/discovery/v1_0/messages/disclose.py b/aries_cloudagent/protocols/discovery/v1_0/messages/disclose.py index 44803e8029..45e080144a 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/messages/disclose.py +++ b/aries_cloudagent/protocols/discovery/v1_0/messages/disclose.py @@ -21,8 +21,7 @@ class Meta: schema_class = "DiscloseSchema" def __init__(self, *, protocols: Sequence[Mapping[str, Mapping]] = None, **kwargs): - """ - Initialize disclose message object. + """Initialize disclose message object. Args: protocols: A mapping of protocol names to a dictionary of properties diff --git a/aries_cloudagent/protocols/discovery/v1_0/messages/query.py b/aries_cloudagent/protocols/discovery/v1_0/messages/query.py index 530ef99ae0..0aa9e7f05b 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/messages/query.py +++ b/aries_cloudagent/protocols/discovery/v1_0/messages/query.py @@ -23,8 +23,7 @@ class Meta: schema_class = "QuerySchema" def __init__(self, *, query: str = None, comment: str = None, **kwargs): - """ - Initialize query message object. + """Initialize query message object. Args: query: The query string to match against supported message types diff --git a/aries_cloudagent/protocols/discovery/v1_0/routes.py b/aries_cloudagent/protocols/discovery/v1_0/routes.py index 50f5c9d222..f9d282b4cc 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/routes.py +++ b/aries_cloudagent/protocols/discovery/v1_0/routes.py @@ -67,8 +67,7 @@ class QueryDiscoveryExchRecordsSchema(OpenAPISchema): @querystring_schema(QueryFeaturesQueryStringSchema()) @response_schema(V10DiscoveryRecordSchema(), 200, description="") async def query_features(request: web.BaseRequest): - """ - Request handler for creating and sending feature query. + """Request handler for creating and sending feature query. Args: request: aiohttp request object @@ -98,8 +97,7 @@ async def query_features(request: web.BaseRequest): @querystring_schema(QueryDiscoveryExchRecordsSchema()) @response_schema(V10DiscoveryExchangeListResultSchema(), 200, description="") async def query_records(request: web.BaseRequest): - """ - Request handler for looking up V10DiscoveryExchangeRecord. + """Request handler for looking up V10DiscoveryExchangeRecord. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/discovery/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/discovery/v1_0/tests/test_manager.py index 08e44ff2d1..8864a31e15 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/discovery/v1_0/tests/test_manager.py @@ -10,7 +10,6 @@ from ....didcomm_prefix import DIDCommPrefix -from .. import manager as test_module from ..manager import V10DiscoveryMgr from ..messages.disclose import Disclose from ..messages.query import Query diff --git a/aries_cloudagent/protocols/discovery/v2_0/manager.py b/aries_cloudagent/protocols/discovery/v2_0/manager.py index f116fe8ba9..05609e3c09 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/manager.py +++ b/aries_cloudagent/protocols/discovery/v2_0/manager.py @@ -25,8 +25,7 @@ class V20DiscoveryMgr: """Class for discover feature v1_0 under RFC 31.""" def __init__(self, profile: Profile): - """ - Initialize a V20DiscoveryMgr. + """Initialize a V20DiscoveryMgr. Args: profile: The profile for this manager @@ -36,8 +35,7 @@ def __init__(self, profile: Profile): @property def profile(self) -> Profile: - """ - Accessor for the current Profile. + """Accessor for the current Profile. Returns: The Profile for this manager diff --git a/aries_cloudagent/protocols/discovery/v2_0/messages/disclosures.py b/aries_cloudagent/protocols/discovery/v2_0/messages/disclosures.py index 52c5b24ec0..a48fcb003c 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/messages/disclosures.py +++ b/aries_cloudagent/protocols/discovery/v2_0/messages/disclosures.py @@ -71,8 +71,7 @@ class Meta: schema_class = "DisclosuresSchema" def __init__(self, *, disclosures: Sequence[Mapping] = None, **kwargs): - """ - Initialize disclose message object. + """Initialize disclose message object. Args: disclosures: A mapping of protocol names to a dictionary of properties diff --git a/aries_cloudagent/protocols/discovery/v2_0/messages/queries.py b/aries_cloudagent/protocols/discovery/v2_0/messages/queries.py index b5f7cf5f4d..6811ec3e98 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/messages/queries.py +++ b/aries_cloudagent/protocols/discovery/v2_0/messages/queries.py @@ -62,8 +62,7 @@ class Meta: schema_class = "QueriesSchema" def __init__(self, *, queries: Sequence[QueryItem] = None, **kwargs): - """ - Initialize query message object. + """Initialize query message object. Args: query: The query string to match against supported message types diff --git a/aries_cloudagent/protocols/discovery/v2_0/messages/tests/test_disclosures.py b/aries_cloudagent/protocols/discovery/v2_0/messages/tests/test_disclosures.py index e541662d32..3621d35151 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/messages/tests/test_disclosures.py +++ b/aries_cloudagent/protocols/discovery/v2_0/messages/tests/test_disclosures.py @@ -1,6 +1,5 @@ from unittest import mock, TestCase -from marshmallow.exceptions import ValidationError from ......messaging.models.base import BaseModelError diff --git a/aries_cloudagent/protocols/discovery/v2_0/messages/tests/test_queries.py b/aries_cloudagent/protocols/discovery/v2_0/messages/tests/test_queries.py index 01dfa793f3..e5624a33df 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/messages/tests/test_queries.py +++ b/aries_cloudagent/protocols/discovery/v2_0/messages/tests/test_queries.py @@ -1,5 +1,4 @@ from unittest import mock, TestCase -from marshmallow import ValidationError from .....didcomm_prefix import DIDCommPrefix diff --git a/aries_cloudagent/protocols/discovery/v2_0/routes.py b/aries_cloudagent/protocols/discovery/v2_0/routes.py index 541cebcd14..aeac69a424 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/routes.py +++ b/aries_cloudagent/protocols/discovery/v2_0/routes.py @@ -77,8 +77,7 @@ class QueryDiscoveryExchRecordsSchema(OpenAPISchema): @querystring_schema(QueryFeaturesQueryStringSchema()) @response_schema(V20DiscoveryExchangeResultSchema(), 200, description="") async def query_features(request: web.BaseRequest): - """ - Request handler for creating and sending feature queries. + """Request handler for creating and sending feature queries. Args: request: aiohttp request object @@ -108,8 +107,7 @@ async def query_features(request: web.BaseRequest): @querystring_schema(QueryDiscoveryExchRecordsSchema()) @response_schema(V20DiscoveryExchangeListResultSchema(), 200, description="") async def query_records(request: web.BaseRequest): - """ - Request handler for looking up V20DiscoveryExchangeRecord. + """Request handler for looking up V20DiscoveryExchangeRecord. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/discovery/v2_0/tests/test_manager.py b/aries_cloudagent/protocols/discovery/v2_0/tests/test_manager.py index 17b78c7b94..7d4a47f155 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/discovery/v2_0/tests/test_manager.py @@ -5,16 +5,11 @@ from asynctest import mock as async_mock, TestCase as AsyncTestCase from .....core.in_memory import InMemoryProfile -from .....core.protocol_registry import ProtocolRegistry -from .....core.goal_code_registry import GoalCodeRegistry from .....storage.error import StorageNotFoundError from .....messaging.responder import BaseResponder, MockResponder from ....didcomm_prefix import DIDCommPrefix -from ....issue_credential.v1_0.controller import ISSUE_VC, PARTICIPATE_VC_INTERACTION -from ....issue_credential.v1_0.message_types import CONTROLLERS, MESSAGE_TYPES -from .. import manager as test_module from ..manager import V20DiscoveryMgr, V20DiscoveryMgrError from ..messages.queries import Queries, QueryItem from ..messages.disclosures import Disclosures diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py index 5cdb726d7f..88dff4f6e8 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py @@ -16,8 +16,7 @@ class EndorsedTransactionResponseHandler(BaseHandler): """Handler class for Endorsed transaction response.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle endorsed transaction response. + """Handle endorsed transaction response. Args: context: Request context diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py index 78f3664229..46da51853e 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py @@ -15,8 +15,7 @@ class RefusedTransactionResponseHandler(BaseHandler): """Handler class for Refused transaction response.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle refused transaction response. + """Handle refused transaction response. Args: context: Request context diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py index 1142d909b9..0803a7216b 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py @@ -15,8 +15,7 @@ class TransactionAcknowledgementHandler(BaseHandler): """Message handler class for Acknowledging transaction.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle transaction acknowledgement message. + """Handle transaction acknowledgement message. Args: context: Request context diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py index 178fc0527b..0154b4e723 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py @@ -15,8 +15,7 @@ class TransactionCancelHandler(BaseHandler): """Handler class for Cancel transaction request.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle cancel transaction request. + """Handle cancel transaction request. Args: context: Request context diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py index 68a8ce8ab5..35e1d50bed 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py @@ -14,8 +14,7 @@ class TransactionJobToSendHandler(BaseHandler): """Handler class for sending transaction jobs.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle transaction jobs. + """Handle transaction jobs. Args: context: Request context diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py index d349031cba..bc60a9a69b 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py @@ -18,8 +18,7 @@ class TransactionRequestHandler(BaseHandler): """Handler class for transaction request.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle transaction request. + """Handle transaction request. Args: context: Request context diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py index 3ccab43e89..268b3f85f2 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py @@ -15,8 +15,7 @@ class TransactionResendHandler(BaseHandler): """Handler class for transaction resend.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle transaction resend. + """Handle transaction resend. Args: context: Request context diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/manager.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/manager.py index c41508bd20..2137f23a5d 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/manager.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/manager.py @@ -45,8 +45,7 @@ class TransactionManager: """Class for managing transactions.""" def __init__(self, profile: Profile): - """ - Initialize a TransactionManager. + """Initialize a TransactionManager. Args: session: The Profile Session for this transaction manager @@ -56,8 +55,7 @@ def __init__(self, profile: Profile): @property def profile(self) -> Profile: - """ - Accessor for the current Profile. + """Accessor for the current Profile. Returns: The Profile for this transaction manager @@ -68,8 +66,7 @@ def profile(self) -> Profile: async def create_record( self, messages_attach: str, connection_id: str, meta_data: dict = None ): - """ - Create a new Transaction Record. + """Create a new Transaction Record. Args: messages_attach: messages to attach, JSON-dumped @@ -121,8 +118,7 @@ async def create_request( author_goal_code: str = None, signer_goal_code: str = None, ): - """ - Create a new Transaction Request. + """Create a new Transaction Request. Args: transaction: The transaction from which the request is created. @@ -174,8 +170,7 @@ async def create_request( return transaction, transaction_request async def receive_request(self, request: TransactionRequest, connection_id: str): - """ - Receive a Transaction request. + """Receive a Transaction request. Args: request: A Transaction Request @@ -216,8 +211,7 @@ async def create_endorse_response( state: str, use_endorser_did: str = None, ): - """ - Create a response to endorse a transaction. + """Create a response to endorse a transaction. Args: transaction: The transaction record which would be endorsed. @@ -358,8 +352,7 @@ async def create_endorse_response( return transaction, endorsed_transaction_response async def receive_endorse_response(self, response: EndorsedTransactionResponse): - """ - Update the transaction record with the endorsed response. + """Update the transaction record with the endorsed response. Args: response: The Endorsed Transaction Response @@ -403,8 +396,7 @@ async def receive_endorse_response(self, response: EndorsedTransactionResponse): async def complete_transaction( self, transaction: TransactionRecord, endorser: bool = False ): - """ - Complete a transaction. + """Complete a transaction. This is the final state where the received ledger transaction is written to the ledger. @@ -488,8 +480,7 @@ async def complete_transaction( async def receive_transaction_acknowledgement( self, response: TransactionAcknowledgement, connection_id: str ): - """ - Update the transaction record after receiving the transaction acknowledgement. + """Update the transaction record after receiving the transaction acknowledgement. Args: response: The transaction acknowledgement @@ -541,8 +532,7 @@ async def receive_transaction_acknowledgement( async def create_refuse_response( self, transaction: TransactionRecord, state: str, refuser_did: str ): - """ - Create a response to refuse a transaction. + """Create a response to refuse a transaction. Args: transaction: The transaction record which would be refused @@ -589,8 +579,7 @@ async def create_refuse_response( return transaction, refused_transaction_response async def receive_refuse_response(self, response: RefusedTransactionResponse): - """ - Update the transaction record with a refused response. + """Update the transaction record with a refused response. Args: response: The refused transaction response @@ -614,8 +603,7 @@ async def receive_refuse_response(self, response: RefusedTransactionResponse): return transaction async def cancel_transaction(self, transaction: TransactionRecord, state: str): - """ - Cancel a Transaction Request. + """Cancel a Transaction Request. Args: transaction: The transaction record which would be cancelled @@ -648,8 +636,7 @@ async def cancel_transaction(self, transaction: TransactionRecord, state: str): async def receive_cancel_transaction( self, response: CancelTransaction, connection_id: str ): - """ - Update the transaction record to cancel a transaction request. + """Update the transaction record to cancel a transaction request. Args: response: The cancel transaction response @@ -668,8 +655,7 @@ async def receive_cancel_transaction( return transaction async def transaction_resend(self, transaction: TransactionRecord, state: str): - """ - Resend a transaction request. + """Resend a transaction request. Args: transaction: The transaction record which needs to be resend @@ -703,8 +689,7 @@ async def transaction_resend(self, transaction: TransactionRecord, state: str): async def receive_transaction_resend( self, response: TransactionResend, connection_id: str ): - """ - Update the transaction with a resend request. + """Update the transaction with a resend request. Args: response: The Resend transaction response @@ -723,8 +708,7 @@ async def receive_transaction_resend( return transaction async def set_transaction_my_job(self, record: ConnRecord, transaction_my_job: str): - """ - Set transaction_my_job. + """Set transaction_my_job. Args: record: The connection record in which to set transaction jobs @@ -750,8 +734,7 @@ async def set_transaction_my_job(self, record: ConnRecord, transaction_my_job: s async def set_transaction_their_job( self, tx_job_received: TransactionJobToSend, receipt: MessageReceipt ): - """ - Set transaction_their_job. + """Set transaction_their_job. Args: tx_job_received: The transaction job that is received from the other agent @@ -780,8 +763,7 @@ async def endorsed_txn_post_processing( ledger_response: dict = None, connection_record: ConnRecord = None, ): - """ - Store record in wallet, and kick off any required post-processing. + """Store record in wallet, and kick off any required post-processing. Args: transaction: The transaction from which the schema/cred_def diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/cancel_transaction.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/cancel_transaction.py index 3a32204b5c..6c338f33fb 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/cancel_transaction.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/cancel_transaction.py @@ -28,8 +28,7 @@ def __init__( thread_id: str = None, **kwargs, ): - """ - Initialize a cancel transaction object. + """Initialize a cancel transaction object. Args: state: State of the transaction record diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/endorsed_transaction_response.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/endorsed_transaction_response.py index a90ee7d29b..c51a5fe7a0 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/endorsed_transaction_response.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/endorsed_transaction_response.py @@ -33,8 +33,7 @@ def __init__( ledger_response: dict = None, **kwargs, ): - """ - Initialize an endorsed transaction response object. + """Initialize an endorsed transaction response object. Args: transaction_id: The id of the transaction record diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/messages_attach.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/messages_attach.py index 11b5a00373..b00681c919 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/messages_attach.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/messages_attach.py @@ -31,8 +31,7 @@ def __init__( time: int = None, **kwargs ): - """ - Initialize the attached message object. + """Initialize the attached message object. Args: author_did: The public did of the author who creates the transaction diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/refused_transaction_response.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/refused_transaction_response.py index 6252309cb4..2f585d18b9 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/refused_transaction_response.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/refused_transaction_response.py @@ -32,8 +32,7 @@ def __init__( endorser_did: str = None, **kwargs, ): - """ - Initialize a refused transaction response object. + """Initialize a refused transaction response object. Args: transaction_id: The id of the transaction record diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/tests/test_messages_attach.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/tests/test_messages_attach.py index 0e0d1e5a29..111376b0d2 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/tests/test_messages_attach.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/tests/test_messages_attach.py @@ -1,6 +1,5 @@ from unittest import mock, TestCase -from asynctest import TestCase as AsyncTestCase from .....didcomm_prefix import DIDCommPrefix diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_acknowledgement.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_acknowledgement.py index 16166b9ce8..8328403a79 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_acknowledgement.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_acknowledgement.py @@ -29,8 +29,7 @@ def __init__( ledger_response: dict = None, **kwargs, ): - """ - Initialize a transaction acknowledgement object. + """Initialize a transaction acknowledgement object. Args: thread_id: Thread id of transaction record diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_job_to_send.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_job_to_send.py index ae43cdff56..d4df7cc542 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_job_to_send.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_job_to_send.py @@ -27,8 +27,7 @@ def __init__( job: str = None, **kwargs, ): - """ - Initialize transaction job to send. + """Initialize transaction job to send. Args: job: The job that needs to be send diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_request.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_request.py index 2a4ca89dc4..48864805de 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_request.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_request.py @@ -32,8 +32,7 @@ def __init__( endorser_write_txn: bool = None, **kwargs, ): - """ - Initialize the transaction request object. + """Initialize the transaction request object. Args: transaction_id: The transaction id of the transaction record diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_resend.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_resend.py index 311cca32ae..c38f7154f5 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_resend.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/messages/transaction_resend.py @@ -28,8 +28,7 @@ def __init__( thread_id: str = None, **kwargs, ): - """ - Initialize a transaction resend object. + """Initialize a transaction resend object. Args: state: State of the transaction record diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py index f00f50c407..57c0b054e4 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py @@ -144,8 +144,7 @@ class EndorserInfoSchema(OpenAPISchema): @querystring_schema(TransactionsListQueryStringSchema()) @response_schema(TransactionListSchema(), 200) async def transactions_list(request: web.BaseRequest): - """ - Request handler for searching transaction records. + """Request handler for searching transaction records. Args: request: aiohttp request object @@ -174,8 +173,7 @@ async def transactions_list(request: web.BaseRequest): @match_info_schema(TranIdMatchInfoSchema()) @response_schema(TransactionRecordSchema(), 200) async def transactions_retrieve(request: web.BaseRequest): - """ - Request handler for fetching a single transaction record. + """Request handler for fetching a single transaction record. Args: request: aiohttp request object @@ -209,8 +207,7 @@ async def transactions_retrieve(request: web.BaseRequest): @request_schema(DateSchema()) @response_schema(TransactionRecordSchema(), 200) async def transaction_create_request(request: web.BaseRequest): - """ - Request handler for creating a new transaction record and request. + """Request handler for creating a new transaction record and request. Args: request: aiohttp request object @@ -300,8 +297,7 @@ async def transaction_create_request(request: web.BaseRequest): @match_info_schema(TranIdMatchInfoSchema()) @response_schema(TransactionRecordSchema(), 200) async def endorse_transaction_response(request: web.BaseRequest): - """ - Request handler for creating an endorsed transaction response. + """Request handler for creating an endorsed transaction response. Args: request: aiohttp request object @@ -372,8 +368,7 @@ async def endorse_transaction_response(request: web.BaseRequest): @match_info_schema(TranIdMatchInfoSchema()) @response_schema(TransactionRecordSchema(), 200) async def refuse_transaction_response(request: web.BaseRequest): - """ - Request handler for creating a refused transaction response. + """Request handler for creating a refused transaction response. Args: request: aiohttp request object @@ -439,8 +434,7 @@ async def refuse_transaction_response(request: web.BaseRequest): @match_info_schema(TranIdMatchInfoSchema()) @response_schema(TransactionRecordSchema(), 200) async def cancel_transaction(request: web.BaseRequest): - """ - Request handler for cancelling a Transaction request. + """Request handler for cancelling a Transaction request. Args: request: aiohttp request object @@ -504,8 +498,7 @@ async def cancel_transaction(request: web.BaseRequest): @match_info_schema(TranIdMatchInfoSchema()) @response_schema(TransactionRecordSchema(), 200) async def transaction_resend(request: web.BaseRequest): - """ - Request handler for resending a transaction request. + """Request handler for resending a transaction request. Args: request: aiohttp request object @@ -569,8 +562,7 @@ async def transaction_resend(request: web.BaseRequest): @match_info_schema(TransactionConnIdMatchInfoSchema()) @response_schema(TransactionJobsSchema(), 200) async def set_endorser_role(request: web.BaseRequest): - """ - Request handler for assigning transaction jobs. + """Request handler for assigning transaction jobs. Args: request: aiohttp request object @@ -610,8 +602,7 @@ async def set_endorser_role(request: web.BaseRequest): @match_info_schema(TransactionConnIdMatchInfoSchema()) @response_schema(EndorserInfoSchema(), 200) async def set_endorser_info(request: web.BaseRequest): - """ - Request handler for assigning endorser information. + """Request handler for assigning endorser information. Args: request: aiohttp request object @@ -674,8 +665,7 @@ async def set_endorser_info(request: web.BaseRequest): @match_info_schema(TranIdMatchInfoSchema()) @response_schema(TransactionRecordSchema(), 200) async def transaction_write(request: web.BaseRequest): - """ - Request handler for writing an endorsed transaction to the ledger. + """Request handler for writing an endorsed transaction to the ledger. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/introduction/v0_1/base_service.py b/aries_cloudagent/protocols/introduction/v0_1/base_service.py index 4f700d7857..44aad57051 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/base_service.py +++ b/aries_cloudagent/protocols/introduction/v0_1/base_service.py @@ -37,8 +37,7 @@ async def start_introduction( session: ProfileSession, message: str = None, ): - """ - Start the introduction process between two connections. + """Start the introduction process between two connections. Args: init_connection_id: The connection initiating the request @@ -56,8 +55,7 @@ async def return_invitation( session: ProfileSession, outbound_handler, ): - """ - Handle the forwarding of an invitation to the responder. + """Handle the forwarding of an invitation to the responder. Args: target_connection_id: The ID of the connection sending the Invitation diff --git a/aries_cloudagent/protocols/introduction/v0_1/demo_service.py b/aries_cloudagent/protocols/introduction/v0_1/demo_service.py index 640102eee5..3f54dd6f8c 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/demo_service.py +++ b/aries_cloudagent/protocols/introduction/v0_1/demo_service.py @@ -32,8 +32,7 @@ async def start_introduction( session: ProfileSession, outbound_handler, ): - """ - Start the introduction process between two connections. + """Start the introduction process between two connections. Args: init_connection_id: The connection initiating the request @@ -102,8 +101,7 @@ async def return_invitation( session: ProfileSession, outbound_handler, ): - """ - Handle the forwarding of an invitation to the responder. + """Handle the forwarding of an invitation to the responder. Args: target_connection_id: The ID of the connection sending the Invitation diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py index 49fe5c3f29..7e92953531 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py @@ -4,13 +4,11 @@ from ......messaging.base_handler import HandlerException from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder -from ......storage.base import BaseStorage from ......protocols.connections.v1_0.messages.connection_invitation import ( ConnectionInvitation, ) from ...messages.invitation import Invitation -from ...messages.invitation_request import InvitationRequest from .. import invitation_handler as test_module diff --git a/aries_cloudagent/protocols/introduction/v0_1/messages/forward_invitation.py b/aries_cloudagent/protocols/introduction/v0_1/messages/forward_invitation.py index f26b78ac63..9a310eb506 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/messages/forward_invitation.py +++ b/aries_cloudagent/protocols/introduction/v0_1/messages/forward_invitation.py @@ -27,8 +27,7 @@ class Meta: def __init__( self, *, invitation: ConnectionInvitation = None, message: str = None, **kwargs ): - """ - Initialize invitation object. + """Initialize invitation object. Args: invitation: The connection invitation diff --git a/aries_cloudagent/protocols/introduction/v0_1/messages/invitation.py b/aries_cloudagent/protocols/introduction/v0_1/messages/invitation.py index 5364d210c5..dae4a5e3a9 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/messages/invitation.py +++ b/aries_cloudagent/protocols/introduction/v0_1/messages/invitation.py @@ -25,8 +25,7 @@ class Meta: def __init__( self, *, invitation: ConnectionInvitation = None, message: str = None, **kwargs ): - """ - Initialize invitation object. + """Initialize invitation object. Args: invitation: The connection invitation diff --git a/aries_cloudagent/protocols/introduction/v0_1/messages/invitation_request.py b/aries_cloudagent/protocols/introduction/v0_1/messages/invitation_request.py index dfaa435165..d452219437 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/messages/invitation_request.py +++ b/aries_cloudagent/protocols/introduction/v0_1/messages/invitation_request.py @@ -21,8 +21,7 @@ class Meta: schema_class = "InvitationRequestSchema" def __init__(self, *, responder: str = None, message: str = None, **kwargs): - """ - Initialize invitation request object. + """Initialize invitation request object. Args: responder: The name of the agent initiating the introduction diff --git a/aries_cloudagent/protocols/introduction/v0_1/messages/tests/test_invitation.py b/aries_cloudagent/protocols/introduction/v0_1/messages/tests/test_invitation.py index f3e7d1c132..1e5b848ba9 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/messages/tests/test_invitation.py +++ b/aries_cloudagent/protocols/introduction/v0_1/messages/tests/test_invitation.py @@ -1,12 +1,11 @@ -from unittest import mock, TestCase +from unittest import mock from asynctest import TestCase as AsyncTestCase -from .....connections.v1_0.message_types import CONNECTION_INVITATION from .....connections.v1_0.messages.connection_invitation import ConnectionInvitation from ..invitation import Invitation as IntroInvitation -from ...message_types import INVITATION as INTRO_INVITATION, PROTOCOL_PACKAGE +from ...message_types import PROTOCOL_PACKAGE class TestInvitation(AsyncTestCase): diff --git a/aries_cloudagent/protocols/introduction/v0_1/routes.py b/aries_cloudagent/protocols/introduction/v0_1/routes.py index 1752a02ea6..ed1e9ea226 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/routes.py +++ b/aries_cloudagent/protocols/introduction/v0_1/routes.py @@ -54,8 +54,7 @@ class IntroConnIdMatchInfoSchema(OpenAPISchema): @querystring_schema(IntroStartQueryStringSchema()) @response_schema(IntroModuleResponseSchema, description="") async def introduction_start(request: web.BaseRequest): - """ - Request handler for starting an introduction. + """Request handler for starting an introduction. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/__init__.py b/aries_cloudagent/protocols/issue_credential/v1_0/__init__.py index c17773c596..de80027aaa 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/__init__.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/__init__.py @@ -14,8 +14,7 @@ def problem_report_for_record( record: Union[ConnRecord, V10CredentialExchange], desc_en: str, ) -> CredentialProblemReport: - """ - Create problem report for record. + """Create problem report for record. Args: record: connection or exchange record @@ -43,8 +42,7 @@ async def report_problem( record: Union[ConnRecord, V10CredentialExchange], outbound_handler: Coroutine, ): - """ - Send problem report response and raise corresponding HTTP error. + """Send problem report response and raise corresponding HTTP error. Args: err: error for internal diagnostics diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py index 5229bfef50..1c7f2f7d87 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py @@ -14,8 +14,7 @@ class CredentialAckHandler(BaseHandler): """Message handler class for credential acks.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for credential acks. + """Message handler logic for credential acks. Args: context: request context diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py index 7fe0bd7bf6..778a9985aa 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py @@ -19,8 +19,7 @@ class CredentialIssueHandler(BaseHandler): """Message handler class for credential offers.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for credential offers. + """Message handler logic for credential offers. Args: context: request context diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py index a9e114ee40..f2e1b0e324 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py @@ -22,8 +22,7 @@ class CredentialOfferHandler(BaseHandler): """Message handler class for credential offers.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for credential offers. + """Message handler logic for credential offers. Args: context: request context diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py index 24d2b25079..3936dece50 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py @@ -13,8 +13,7 @@ class CredentialProblemReportHandler(BaseHandler): """Message handler class for problem reports.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for problem reports. + """Message handler logic for problem reports. Args: context: request context diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py index b42338aa10..5b4ff0b1ce 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py @@ -19,8 +19,7 @@ class CredentialProposalHandler(BaseHandler): """Message handler class for credential proposals.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for credential proposals. + """Message handler logic for credential proposals. Args: context: proposal context diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py index f9bc43e70e..02794bca6f 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py @@ -20,8 +20,7 @@ class CredentialRequestHandler(BaseHandler): """Message handler class for credential requests.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for credential requests. + """Message handler logic for credential requests. Args: context: request context diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/manager.py b/aries_cloudagent/protocols/issue_credential/v1_0/manager.py index b2fcc41d2a..f0dabfedff 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/manager.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/manager.py @@ -55,8 +55,7 @@ class CredentialManager: """Class for managing credentials.""" def __init__(self, profile: Profile): - """ - Initialize a CredentialManager. + """Initialize a CredentialManager. Args: profile: The profile instance for this credential manager @@ -65,8 +64,7 @@ def __init__(self, profile: Profile): @property def profile(self) -> Profile: - """ - Accessor for the current profile instance. + """Accessor for the current profile instance. Returns: The profile instance for this credential manager @@ -95,8 +93,7 @@ async def prepare_send( auto_remove: bool = None, comment: str = None, ) -> Tuple[V10CredentialExchange, CredentialOffer]: - """ - Set up a new credential exchange for an automated send. + """Set up a new credential exchange for an automated send. Args: connection_id: Connection to create offer for @@ -141,8 +138,7 @@ async def create_proposal( issuer_did: str = None, trace: bool = False, ) -> V10CredentialExchange: - """ - Create a credential proposal. + """Create a credential proposal. Args: connection_id: Connection to create proposal for @@ -197,8 +193,7 @@ async def create_proposal( async def receive_proposal( self, message: CredentialProposal, connection_id: str ) -> V10CredentialExchange: - """ - Receive a credential proposal. + """Receive a credential proposal. Returns: The resulting credential exchange record, created @@ -232,8 +227,7 @@ async def create_offer( counter_proposal: CredentialProposal = None, comment: str = None, ) -> Tuple[V10CredentialExchange, CredentialOffer]: - """ - Create a credential offer, update credential exchange record. + """Create a credential offer, update credential exchange record. Args: cred_ex_record: Credential exchange to create offer for @@ -282,8 +276,8 @@ async def _create(cred_def_id): async with ledger: schema_id = await ledger.credential_definition_id2schema_id(cred_def_id) schema = await ledger.get_schema(schema_id) - schema_attrs = {attr for attr in schema["attrNames"]} - preview_attrs = {attr for attr in credential_preview.attr_dict()} + schema_attrs = set(schema["attrNames"]) + preview_attrs = set(credential_preview.attr_dict()) if preview_attrs != schema_attrs: raise CredentialManagerError( f"Preview attributes {preview_attrs} " @@ -333,8 +327,7 @@ async def _create(cred_def_id): async def receive_offer( self, message: CredentialOffer, connection_id: Optional[str] ) -> V10CredentialExchange: - """ - Receive a credential offer. + """Receive a credential offer. Returns: The credential exchange record, updated @@ -401,8 +394,7 @@ async def receive_offer( async def create_request( self, cred_ex_record: V10CredentialExchange, holder_did: str ) -> Tuple[V10CredentialExchange, CredentialRequest]: - """ - Create a credential request. + """Create a credential request. Args: cred_ex_record: Credential exchange record @@ -514,8 +506,7 @@ async def receive_request( connection_record: Optional[ConnRecord], oob_record: Optional[OobRecord], ): - """ - Receive a credential request. + """Receive a credential request. Args: credential_request_message: Credential request to receive @@ -574,8 +565,7 @@ async def issue_credential( comment: str = None, retries: int = 5, ) -> Tuple[V10CredentialExchange, CredentialIssue]: - """ - Issue a credential. + """Issue a credential. Args: cred_ex_record: The credential exchange record @@ -731,8 +721,7 @@ async def issue_credential( async def receive_credential( self, message: CredentialIssue, connection_id: Optional[str] ) -> V10CredentialExchange: - """ - Receive a credential from an issuer. + """Receive a credential from an issuer. Hold in storage potentially to be processed by controller before storing. @@ -777,8 +766,7 @@ async def receive_credential( async def store_credential( self, cred_ex_record: V10CredentialExchange, credential_id: str = None ) -> V10CredentialExchange: - """ - Store a credential in holder wallet; send ack to issuer. + """Store a credential in holder wallet; send ack to issuer. Args: cred_ex_record: credential exchange record @@ -872,8 +860,7 @@ async def send_credential_ack( self, cred_ex_record: V10CredentialExchange, ) -> Tuple[V10CredentialExchange, CredentialAck]: - """ - Create, send, and return ack message for input credential exchange record. + """Create, send, and return ack message for input credential exchange record. Delete credential exchange record if set to auto-remove. @@ -944,8 +931,7 @@ async def send_credential_ack( async def receive_credential_ack( self, message: CredentialAck, connection_id: Optional[str] ) -> Optional[V10CredentialExchange]: - """ - Receive credential ack from holder. + """Receive credential ack from holder. Returns: credential exchange record, retrieved and updated @@ -986,8 +972,7 @@ async def receive_credential_ack( async def receive_problem_report( self, message: CredentialProblemReport, connection_id: str ): - """ - Receive problem report. + """Receive problem report. Returns: credential exchange record, retrieved and updated diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_exchange_webhook.py b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_exchange_webhook.py index 52641ff8c7..2f6731f971 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_exchange_webhook.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_exchange_webhook.py @@ -35,8 +35,7 @@ def __init__( self, **kwargs, ): - """ - Initialize webhook object from V10CredentialExchange. + """Initialize webhook object from V10CredentialExchange. from a list of accepted attributes. """ diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_issue.py b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_issue.py index 18d25c8c48..45d2ac5561 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_issue.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_issue.py @@ -34,8 +34,7 @@ def __init__( credentials_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize credential issue object. + """Initialize credential issue object. Args: comment: optional comment @@ -47,8 +46,7 @@ def __init__( self.credentials_attach = list(credentials_attach) if credentials_attach else [] def indy_credential(self, index: int = 0): - """ - Retrieve and decode indy credential from attachment. + """Retrieve and decode indy credential from attachment. Args: index: ordinal in attachment list to decode and return diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_offer.py b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_offer.py index 2940cccd30..6077b7367e 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_offer.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_offer.py @@ -36,8 +36,7 @@ def __init__( offers_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize credential offer object. + """Initialize credential offer object. Args: comment: optional human-readable comment @@ -51,8 +50,7 @@ def __init__( self.offers_attach = list(offers_attach) if offers_attach else [] def indy_offer(self, index: int = 0) -> dict: - """ - Retrieve and decode indy offer from attachment. + """Retrieve and decode indy offer from attachment. Args: index: ordinal in attachment list to decode and return diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_problem_report.py b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_problem_report.py index f022a8aef6..7c7f912684 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_problem_report.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_problem_report.py @@ -50,8 +50,7 @@ class Meta: @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields. + """Validate schema fields. Args: data: The data to validate diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_proposal.py b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_proposal.py index a9e7a7f2d7..d743764cca 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_proposal.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_proposal.py @@ -45,8 +45,7 @@ def __init__( issuer_did: str = None, **kwargs, ): - """ - Initialize credential proposal object. + """Initialize credential proposal object. Args: comment: optional human-readable comment diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_request.py b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_request.py index 10254b7b60..df7b98d5c2 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_request.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/messages/credential_request.py @@ -34,8 +34,7 @@ def __init__( requests_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize credential request object. + """Initialize credential request object. Args: requests_attach: requests attachments @@ -47,8 +46,7 @@ def __init__( self.requests_attach = list(requests_attach) if requests_attach else [] def indy_cred_req(self, index: int = 0): - """ - Retrieve and decode indy credential request from attachment. + """Retrieve and decode indy credential request from attachment. Args: index: ordinal in attachment list to decode and return diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/messages/inner/credential_preview.py b/aries_cloudagent/protocols/issue_credential/v1_0/messages/inner/credential_preview.py index 32b27bce6c..5ec5260c3c 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/messages/inner/credential_preview.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/messages/inner/credential_preview.py @@ -20,8 +20,7 @@ class Meta: schema_class = "CredAttrSpecSchema" def __init__(self, *, name: str, value: str, mime_type: str = None, **kwargs): - """ - Initialize attribute preview object. + """Initialize attribute preview object. Args: name: attribute name @@ -38,8 +37,7 @@ def __init__(self, *, name: str, value: str, mime_type: str = None, **kwargs): @staticmethod def list_plain(plain: dict): - """ - Return a list of `CredAttrSpec` without MIME types from names/values. + """Return a list of `CredAttrSpec` without MIME types from names/values. Args: plain: dict mapping names to values @@ -110,8 +108,7 @@ class Meta: def __init__( self, *, _type: str = None, attributes: Sequence[CredAttrSpec] = None, **kwargs ): - """ - Initialize credential preview object. + """Initialize credential preview object. Args: _type: formalism for Marshmallow model creation: ignored @@ -137,8 +134,7 @@ def _type(self): return DIDCommPrefix.qualify_current(CredentialPreview.Meta.message_type) def attr_dict(self, decode: bool = False): - """ - Return name:value pair per attribute. + """Return name:value pair per attribute. Args: decode: whether first to decode attributes with MIME type @@ -153,8 +149,7 @@ def attr_dict(self, decode: bool = False): } def mime_types(self): - """ - Return per-attribute mapping from name to MIME type. + """Return per-attribute mapping from name to MIME type. Return empty dict if no attribute has MIME type. diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py b/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py index 6cfb9268bc..2137d04986 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py @@ -198,8 +198,7 @@ async def save_error_state( log_params: Mapping[str, Any] = None, log_override: bool = False, ): - """ - Save record error state if need be; log and swallow any storage error. + """Save record error state if need be; log and swallow any storage error. Args: session: The profile session to use @@ -227,8 +226,7 @@ async def save_error_state( # Override async def emit_event(self, session: ProfileSession, payload: Any = None): - """ - Emit an event. + """Emit an event. Args: session: The profile session to use diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/routes.py b/aries_cloudagent/protocols/issue_credential/v1_0/routes.py index d6d84b6d27..e00411efed 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/routes.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/routes.py @@ -382,8 +382,7 @@ class V10CredentialExchangeAutoRemoveRequestSchema(OpenAPISchema): @querystring_schema(V10CredentialExchangeListQueryStringSchema) @response_schema(V10CredentialExchangeListResultSchema(), 200, description="") async def credential_exchange_list(request: web.BaseRequest): - """ - Request handler for searching credential exchange records. + """Request handler for searching credential exchange records. Args: request: aiohttp request object @@ -423,8 +422,7 @@ async def credential_exchange_list(request: web.BaseRequest): @match_info_schema(CredExIdMatchInfoSchema()) @response_schema(V10CredentialExchangeSchema(), 200, description="") async def credential_exchange_retrieve(request: web.BaseRequest): - """ - Request handler for fetching single credential exchange record. + """Request handler for fetching single credential exchange record. Args: request: aiohttp request object @@ -470,8 +468,7 @@ async def credential_exchange_retrieve(request: web.BaseRequest): @request_schema(V10CredentialCreateSchema()) @response_schema(V10CredentialExchangeSchema(), 200, description="") async def credential_exchange_create(request: web.BaseRequest): - """ - Request handler for creating a credential from attr values. + """Request handler for creating a credential from attr values. The internal credential record will be created without the credential being sent to any connection. This can be used in conjunction with @@ -547,8 +544,7 @@ async def credential_exchange_create(request: web.BaseRequest): @request_schema(V10CredentialProposalRequestMandSchema()) @response_schema(V10CredentialExchangeSchema(), 200, description="") async def credential_exchange_send(request: web.BaseRequest): - """ - Request handler for sending credential from issuer to holder from attr values. + """Request handler for sending credential from issuer to holder from attr values. If both issuer and holder are configured for automatic responses, the operation ultimately results in credential issue; otherwise, the result waits on the first @@ -647,8 +643,7 @@ async def credential_exchange_send(request: web.BaseRequest): @request_schema(V10CredentialProposalRequestOptSchema()) @response_schema(V10CredentialExchangeSchema(), 200, description="") async def credential_exchange_send_proposal(request: web.BaseRequest): - """ - Request handler for sending credential proposal. + """Request handler for sending credential proposal. Args: request: aiohttp request object @@ -773,8 +768,7 @@ async def _create_free_offer( @request_schema(V10CredentialConnFreeOfferRequestSchema()) @response_schema(V10CredentialExchangeSchema(), 200, description="") async def credential_exchange_create_free_offer(request: web.BaseRequest): - """ - Request handler for creating free credential offer. + """Request handler for creating free credential offer. Unlike with `send-offer`, this credential exchange is not tied to a specific connection. It must be dispatched out-of-band by the controller. @@ -845,8 +839,7 @@ async def credential_exchange_create_free_offer(request: web.BaseRequest): @request_schema(V10CredentialFreeOfferRequestSchema()) @response_schema(V10CredentialExchangeSchema(), 200, description="") async def credential_exchange_send_free_offer(request: web.BaseRequest): - """ - Request handler for sending free credential offer. + """Request handler for sending free credential offer. An issuer initiates a such a credential offer, free from any holder-initiated corresponding credential proposal with preview. @@ -938,8 +931,7 @@ async def credential_exchange_send_free_offer(request: web.BaseRequest): @request_schema(V10CredentialBoundOfferRequestSchema()) @response_schema(V10CredentialExchangeSchema(), 200, description="") async def credential_exchange_send_bound_offer(request: web.BaseRequest): - """ - Request handler for sending bound credential offer. + """Request handler for sending bound credential offer. A holder initiates this sequence with a credential proposal; this message responds with an offer bound to the proposal. @@ -1038,8 +1030,7 @@ async def credential_exchange_send_bound_offer(request: web.BaseRequest): @request_schema(V10CredentialExchangeAutoRemoveRequestSchema()) @response_schema(V10CredentialExchangeSchema(), 200, description="") async def credential_exchange_send_request(request: web.BaseRequest): - """ - Request handler for sending credential request. + """Request handler for sending credential request. Args: request: aiohttp request object @@ -1154,8 +1145,7 @@ async def credential_exchange_send_request(request: web.BaseRequest): @request_schema(V10CredentialIssueRequestSchema()) @response_schema(V10CredentialExchangeSchema(), 200, description="") async def credential_exchange_issue(request: web.BaseRequest): - """ - Request handler for sending credential. + """Request handler for sending credential. Args: request: aiohttp request object @@ -1250,8 +1240,7 @@ async def credential_exchange_issue(request: web.BaseRequest): @request_schema(V10CredentialStoreRequestSchema()) @response_schema(V10CredentialExchangeSchema(), 200, description="") async def credential_exchange_store(request: web.BaseRequest): - """ - Request handler for storing credential. + """Request handler for storing credential. Args: request: aiohttp request object @@ -1355,8 +1344,7 @@ async def credential_exchange_store(request: web.BaseRequest): @request_schema(V10CredentialProblemReportRequestSchema()) @response_schema(IssueCredentialModuleResponseSchema(), 200, description="") async def credential_exchange_problem_report(request: web.BaseRequest): - """ - Request handler for sending problem report. + """Request handler for sending problem report. Args: request: aiohttp request object @@ -1401,8 +1389,7 @@ async def credential_exchange_problem_report(request: web.BaseRequest): @match_info_schema(CredExIdMatchInfoSchema()) @response_schema(IssueCredentialModuleResponseSchema(), 200, description="") async def credential_exchange_remove(request: web.BaseRequest): - """ - Request handler for removing a credential exchange record. + """Request handler for removing a credential exchange record. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py index 6053bd81f0..66cf6315a5 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py @@ -1,4 +1,3 @@ -import asyncio import json from copy import deepcopy diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/__init__.py b/aries_cloudagent/protocols/issue_credential/v2_0/__init__.py index febf17d8e1..f5b93347d7 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/__init__.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/__init__.py @@ -11,8 +11,7 @@ def problem_report_for_record( record: Union[ConnRecord, V20CredExRecord], desc_en: str, ) -> V20CredProblemReport: - """ - Create problem report for record. + """Create problem report for record. Args: record: connection or exchange record @@ -40,8 +39,7 @@ async def report_problem( record: Union[ConnRecord, V20CredExRecord], outbound_handler: Coroutine, ): - """ - Send problem report response and raise corresponding HTTP error. + """Send problem report response and raise corresponding HTTP error. Args: err: error for internal diagnostics diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py index ee7850376a..183ecbf0a0 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py @@ -38,8 +38,7 @@ def __init__(self, profile: Profile): @property def profile(self) -> Profile: - """ - Accessor for the current profile instance. + """Accessor for the current profile instance. Returns: The profile instance for this credential format diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py index 7ef901260f..d6329cfcb6 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py @@ -214,10 +214,8 @@ async def _create(): async with ledger: schema_id = await ledger.credential_definition_id2schema_id(cred_def_id) schema = await ledger.get_schema(schema_id) - schema_attrs = {attr for attr in schema["attrNames"]} - preview_attrs = { - attr for attr in cred_proposal_message.credential_preview.attr_dict() - } + schema_attrs = set(schema["attrNames"]) + preview_attrs = set(cred_proposal_message.credential_preview.attr_dict()) if preview_attrs != schema_attrs: raise V20CredFormatError( f"Preview attributes {preview_attrs} " diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py index 7366437304..66ac360d3e 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py @@ -1,4 +1,3 @@ -import asyncio from copy import deepcopy from time import time import json @@ -19,7 +18,6 @@ from .......cache.in_memory import InMemoryCache from .......cache.base import BaseCache from .......storage.record import StorageRecord -from .......storage.error import StorageNotFoundError from .......messaging.credential_definitions.util import CRED_DEF_SENT_RECORD_TYPE from .......messaging.decorators.attach_decorator import AttachDecorator from .......indy.holder import IndyHolder @@ -41,7 +39,7 @@ CRED_20_ISSUE, ) -from ...handler import LOGGER, V20CredFormatError +from ...handler import V20CredFormatError from ..handler import IndyCredFormatHandler from ..handler import LOGGER as INDY_LOGGER diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py index 9c580fd01d..26f5d10498 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py @@ -14,8 +14,7 @@ class V20CredAckHandler(BaseHandler): """Message handler class for credential acks.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for credential acks. + """Message handler logic for credential acks. Args: context: request context diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py index ee148857f1..f3c5704252 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py @@ -19,8 +19,7 @@ class V20CredIssueHandler(BaseHandler): """Message handler class for credential offers.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for credential offers. + """Message handler logic for credential offers. Args: context: request context diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py index 9fc223c4c0..3184b79b55 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py @@ -21,8 +21,7 @@ class V20CredOfferHandler(BaseHandler): """Message handler class for credential offers.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for credential offers. + """Message handler logic for credential offers. Args: context: request context diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py index 32515d1365..d3b85ecacd 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py @@ -13,8 +13,7 @@ class CredProblemReportHandler(BaseHandler): """Message handler class for problem reports.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for problem reports. + """Message handler logic for problem reports. Args: context: request context diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py index e59e9a36d2..4ff09f70aa 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py @@ -19,8 +19,7 @@ class V20CredProposalHandler(BaseHandler): """Message handler class for credential proposals.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for credential proposals. + """Message handler logic for credential proposals. Args: context: proposal context diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py index 1bdf7671e9..ecf0d6fb15 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py @@ -20,8 +20,7 @@ class V20CredRequestHandler(BaseHandler): """Message handler class for credential requests.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for credential requests. + """Message handler logic for credential requests. Args: context: request context diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/manager.py b/aries_cloudagent/protocols/issue_credential/v2_0/manager.py index 142190c8b1..fe737c27f6 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/manager.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/manager.py @@ -32,8 +32,7 @@ class V20CredManager: """Class for managing credentials.""" def __init__(self, profile: Profile): - """ - Initialize a V20CredManager. + """Initialize a V20CredManager. Args: profile: The profile instance for this credential manager @@ -42,8 +41,7 @@ def __init__(self, profile: Profile): @property def profile(self) -> Profile: - """ - Accessor for the current profile instance. + """Accessor for the current profile instance. Returns: The profile instance for this credential manager @@ -59,8 +57,7 @@ async def prepare_send( auto_remove: bool = None, replacement_id: str = None, ) -> Tuple[V20CredExRecord, V20CredOffer]: - """ - Set up a new credential exchange record for an automated send. + """Set up a new credential exchange record for an automated send. Args: connection_id: connection for which to create offer @@ -102,8 +99,7 @@ async def create_proposal( fmt2filter: Mapping[V20CredFormat.Format, Mapping[str, str]], trace: bool = False, ) -> V20CredExRecord: - """ - Create a credential proposal. + """Create a credential proposal. Args: connection_id: connection for which to create proposal @@ -159,8 +155,7 @@ async def receive_proposal( cred_proposal_message: V20CredProposal, connection_id: str, ) -> V20CredExRecord: - """ - Receive a credential proposal. + """Receive a credential proposal. Returns: The resulting credential exchange record, created @@ -206,8 +201,7 @@ async def create_offer( replacement_id: str = None, comment: str = None, ) -> Tuple[V20CredExRecord, V20CredOffer]: - """ - Create credential offer, update credential exchange record. + """Create credential offer, update credential exchange record. Args: cred_ex_record: credential exchange record for which to create offer @@ -273,8 +267,7 @@ async def receive_offer( cred_offer_message: V20CredOffer, connection_id: Optional[str], ) -> V20CredExRecord: - """ - Receive a credential offer. + """Receive a credential offer. Args: cred_offer_message: credential offer message @@ -325,8 +318,7 @@ async def receive_offer( async def create_request( self, cred_ex_record: V20CredExRecord, holder_did: str, comment: str = None ) -> Tuple[V20CredExRecord, V20CredRequest]: - """ - Create a credential request. + """Create a credential request. Args: cred_ex_record: credential exchange record for which to create request @@ -405,8 +397,7 @@ async def receive_request( connection_record: Optional[ConnRecord], oob_record: Optional[OobRecord], ) -> V20CredExRecord: - """ - Receive a credential request. + """Receive a credential request. Args: cred_request_message: credential request to receive @@ -469,8 +460,7 @@ async def issue_credential( *, comment: str = None, ) -> Tuple[V20CredExRecord, V20CredIssue]: - """ - Issue a credential. + """Issue a credential. Args: cred_ex_record: credential exchange record for which to issue credential @@ -541,8 +531,7 @@ async def issue_credential( async def receive_credential( self, cred_issue_message: V20CredIssue, connection_id: Optional[str] ) -> V20CredExRecord: - """ - Receive a credential issue message from an issuer. + """Receive a credential issue message from an issuer. Hold cred in storage potentially to be processed by controller before storing. @@ -600,8 +589,7 @@ async def receive_credential( async def store_credential( self, cred_ex_record: V20CredExRecord, cred_id: str = None ) -> Tuple[V20CredExRecord, V20CredAck]: - """ - Store a credential in holder wallet; send ack to issuer. + """Store a credential in holder wallet; send ack to issuer. Args: cred_ex_record: credential exchange record with credential to store and ack @@ -635,8 +623,7 @@ async def send_cred_ack( self, cred_ex_record: V20CredExRecord, ): - """ - Create, send, and return ack message for input cred ex record. + """Create, send, and return ack message for input cred ex record. Delete cred ex record if set to auto-remove. @@ -683,8 +670,7 @@ async def send_cred_ack( async def receive_credential_ack( self, cred_ack_message: V20CredAck, connection_id: Optional[str] ) -> V20CredExRecord: - """ - Receive credential ack from holder. + """Receive credential ack from holder. Args: cred_ack_message: credential ack message to receive @@ -728,8 +714,7 @@ async def delete_cred_ex_record(self, cred_ex_id: str) -> None: async def receive_problem_report( self, message: V20CredProblemReport, connection_id: str ): - """ - Receive problem report. + """Receive problem report. Returns: credential exchange record, retrieved and updated diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_ex_record_webhook.py b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_ex_record_webhook.py index aa566db23d..ef71eded68 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_ex_record_webhook.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_ex_record_webhook.py @@ -35,8 +35,7 @@ def __init__( self, **kwargs, ): - """ - Initialize webhook object from V20CredExRecord. + """Initialize webhook object from V20CredExRecord. from a list of accepted attributes. """ diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_issue.py b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_issue.py index efe854c579..1154b4db07 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_issue.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_issue.py @@ -36,8 +36,7 @@ def __init__( credentials_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize credential issue object. + """Initialize credential issue object. Args: comment: optional comment @@ -53,8 +52,7 @@ def __init__( self.credentials_attach = list(credentials_attach) if credentials_attach else [] def attachment(self, fmt: V20CredFormat.Format = None) -> dict: - """ - Return attached credential. + """Return attached credential. Args: fmt: format of attachment in list to decode and return diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_offer.py b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_offer.py index 0ccb28bf54..f6dd4d0de8 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_offer.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_offer.py @@ -38,8 +38,7 @@ def __init__( offers_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize credential offer object. + """Initialize credential offer object. Args: replacement_id: unique to issuer, to coordinate credential replacement @@ -57,8 +56,7 @@ def __init__( self.offers_attach = list(offers_attach) if offers_attach else [] def attachment(self, fmt: V20CredFormat.Format = None) -> dict: - """ - Return attached offer. + """Return attached offer. Args: fmt: format of attachment in list to decode and return diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_problem_report.py b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_problem_report.py index 64af518625..716e99a74c 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_problem_report.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_problem_report.py @@ -49,8 +49,7 @@ class Meta: @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields. + """Validate schema fields. Args: data: The data to validate diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_proposal.py b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_proposal.py index 463e0dec71..d09d71c6d1 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_proposal.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_proposal.py @@ -38,8 +38,7 @@ def __init__( filters_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize credential proposal object. + """Initialize credential proposal object. Args: comment: optional human-readable comment @@ -55,8 +54,7 @@ def __init__( self.filters_attach = list(filters_attach) if filters_attach else [] def attachment(self, fmt: V20CredFormat.Format = None) -> dict: - """ - Return attached filter. + """Return attached filter. Args: fmt: format of attachment in list to decode and return diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_request.py b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_request.py index b805097462..193638f2eb 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_request.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/messages/cred_request.py @@ -36,8 +36,7 @@ def __init__( requests_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize credential request object. + """Initialize credential request object. Args: requests_attach: requests attachments @@ -52,8 +51,7 @@ def __init__( self.requests_attach = list(requests_attach) if requests_attach else [] def attachment(self, fmt: V20CredFormat.Format = None) -> dict: - """ - Return attached credential request. + """Return attached credential request. Args: fmt: format of attachment in list to decode and return diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/messages/inner/cred_preview.py b/aries_cloudagent/protocols/issue_credential/v2_0/messages/inner/cred_preview.py index 78c8986602..85256fc9f0 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/messages/inner/cred_preview.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/messages/inner/cred_preview.py @@ -19,8 +19,7 @@ class Meta: schema_class = "V20CredAttrSpecSchema" def __init__(self, *, name: str, value: str, mime_type: str = None, **kwargs): - """ - Initialize attribute preview object. + """Initialize attribute preview object. Args: name: attribute name @@ -37,8 +36,7 @@ def __init__(self, *, name: str, value: str, mime_type: str = None, **kwargs): @staticmethod def list_plain(plain: dict) -> Sequence["V20CredAttrSpec"]: - """ - Return a list of `V20CredAttrSpec` (copies), absent any MIME types. + """Return a list of `V20CredAttrSpec` (copies), absent any MIME types. Args: plain: dict mapping names to values @@ -113,8 +111,7 @@ def __init__( attributes: Sequence[V20CredAttrSpec] = None, **kwargs, ): - """ - Initialize credential preview object. + """Initialize credential preview object. Args: _type: formalism for Marshmallow model creation: ignored @@ -140,8 +137,7 @@ def _type(self): return DIDCommPrefix.qualify_current(V20CredPreview.Meta.message_type) def attr_dict(self, decode: bool = False): - """ - Return name:value pair per attribute. + """Return name:value pair per attribute. Args: decode: whether first to decode attributes with MIME type @@ -156,8 +152,7 @@ def attr_dict(self, decode: bool = False): } def mime_types(self): - """ - Return per-attribute mapping from name to MIME type. + """Return per-attribute mapping from name to MIME type. Return empty dict if no attribute has MIME type. diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_ack.py b/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_ack.py index 328ece9c81..ec4e33c4bf 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_ack.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_ack.py @@ -2,7 +2,7 @@ from .....didcomm_prefix import DIDCommPrefix -from ...message_types import CRED_20_ACK, PROTOCOL_PACKAGE +from ...message_types import CRED_20_ACK from .. import cred_ack as test_module from ..cred_ack import V20CredAck diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_offer.py b/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_offer.py index 1394281b45..3334aa5c59 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_offer.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_offer.py @@ -1,4 +1,4 @@ -from asynctest import mock as async_mock, TestCase as AsyncTestCase +from asynctest import TestCase as AsyncTestCase from ......messaging.decorators.attach_decorator import AttachDecorator from ......messaging.models.base import BaseModelError @@ -7,7 +7,6 @@ from ...message_types import ATTACHMENT_FORMAT, CRED_20_OFFER -from .. import cred_offer as test_module from ..cred_format import V20CredFormat from ..cred_offer import V20CredOffer from ..inner.cred_preview import V20CredAttrSpec, V20CredPreview diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_proposal.py b/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_proposal.py index f9edf2e2b0..e45778f008 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_proposal.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_proposal.py @@ -8,7 +8,7 @@ from ...message_types import ATTACHMENT_FORMAT, CRED_20_PREVIEW, CRED_20_PROPOSAL from ..cred_format import V20CredFormat -from ..cred_proposal import V20CredProposal, V20CredFormat +from ..cred_proposal import V20CredProposal from ..inner.cred_preview import V20CredAttrSpec, V20CredPreview diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py b/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py index 642dbd987d..1eece14bac 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py @@ -154,8 +154,7 @@ async def save_error_state( log_params: Mapping[str, Any] = None, log_override: bool = False, ): - """ - Save record error state if need be; log and swallow any storage error. + """Save record error state if need be; log and swallow any storage error. Args: session: The profile session to use @@ -183,8 +182,7 @@ async def save_error_state( # Override async def emit_event(self, session: ProfileSession, payload: Any = None): - """ - Emit an event. + """Emit an event. Args: session: The profile session to use diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/routes.py b/aries_cloudagent/protocols/issue_credential/v2_0/routes.py index e78606807b..721128b4ae 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/routes.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/routes.py @@ -184,8 +184,7 @@ class V20CredFilterSchema(OpenAPISchema): @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields. + """Validate schema fields. Data must have indy, ld_proof, or both. @@ -496,8 +495,7 @@ def _format_result_with_details( @querystring_schema(V20CredExRecordListQueryStringSchema) @response_schema(V20CredExRecordListResultSchema(), 200, description="") async def credential_exchange_list(request: web.BaseRequest): - """ - Request handler for searching credential exchange records. + """Request handler for searching credential exchange records. Args: request: aiohttp request object @@ -544,8 +542,7 @@ async def credential_exchange_list(request: web.BaseRequest): @match_info_schema(V20CredExIdMatchInfoSchema()) @response_schema(V20CredExRecordDetailSchema(), 200, description="") async def credential_exchange_retrieve(request: web.BaseRequest): - """ - Request handler for fetching single credential exchange record. + """Request handler for fetching single credential exchange record. Args: request: aiohttp request object @@ -592,8 +589,7 @@ async def credential_exchange_retrieve(request: web.BaseRequest): @request_schema(V20IssueCredSchemaCore()) @response_schema(V20CredExRecordSchema(), 200, description="") async def credential_exchange_create(request: web.BaseRequest): - """ - Request handler for creating a credential from attr values. + """Request handler for creating a credential from attr values. The internal credential record will be created without the credential being sent to any connection. This can be used in conjunction with @@ -667,8 +663,7 @@ async def credential_exchange_create(request: web.BaseRequest): @request_schema(V20CredExFreeSchema()) @response_schema(V20CredExRecordSchema(), 200, description="") async def credential_exchange_send(request: web.BaseRequest): - """ - Request handler for sending credential from issuer to holder from attr values. + """Request handler for sending credential from issuer to holder from attr values. If both issuer and holder are configured for automatic responses, the operation ultimately results in credential issue; otherwise, the result waits on the first @@ -782,8 +777,7 @@ async def credential_exchange_send(request: web.BaseRequest): @request_schema(V20CredExFreeSchema()) @response_schema(V20CredExRecordSchema(), 200, description="") async def credential_exchange_send_proposal(request: web.BaseRequest): - """ - Request handler for sending credential proposal. + """Request handler for sending credential proposal. Args: request: aiohttp request object @@ -912,8 +906,7 @@ async def _create_free_offer( @request_schema(V20CredOfferConnFreeRequestSchema()) @response_schema(V20CredExRecordSchema(), 200, description="") async def credential_exchange_create_free_offer(request: web.BaseRequest): - """ - Request handler for creating free credential offer. + """Request handler for creating free credential offer. Unlike with `send-offer`, this credential exchange is not tied to a specific connection. It must be dispatched out-of-band by the controller. @@ -983,8 +976,7 @@ async def credential_exchange_create_free_offer(request: web.BaseRequest): @request_schema(V20CredOfferRequestSchema()) @response_schema(V20CredExRecordSchema(), 200, description="") async def credential_exchange_send_free_offer(request: web.BaseRequest): - """ - Request handler for sending free credential offer. + """Request handler for sending free credential offer. An issuer initiates a such a credential offer, free from any holder-initiated corresponding credential proposal with preview. @@ -1078,8 +1070,7 @@ async def credential_exchange_send_free_offer(request: web.BaseRequest): @request_schema(V20CredBoundOfferRequestSchema()) @response_schema(V20CredExRecordSchema(), 200, description="") async def credential_exchange_send_bound_offer(request: web.BaseRequest): - """ - Request handler for sending bound credential offer. + """Request handler for sending bound credential offer. A holder initiates this sequence with a credential proposal; this message responds with an offer bound to the proposal. @@ -1189,8 +1180,7 @@ async def credential_exchange_send_bound_offer(request: web.BaseRequest): @request_schema(V20CredRequestFreeSchema()) @response_schema(V20CredExRecordSchema(), 200, description="") async def credential_exchange_send_free_request(request: web.BaseRequest): - """ - Request handler for sending free credential request. + """Request handler for sending free credential request. Args: request: aiohttp request object @@ -1290,8 +1280,7 @@ async def credential_exchange_send_free_request(request: web.BaseRequest): @request_schema(V20CredRequestRequestSchema()) @response_schema(V20CredExRecordSchema(), 200, description="") async def credential_exchange_send_bound_request(request: web.BaseRequest): - """ - Request handler for sending credential request. + """Request handler for sending credential request. Args: request: aiohttp request object @@ -1409,8 +1398,7 @@ async def credential_exchange_send_bound_request(request: web.BaseRequest): @request_schema(V20CredIssueRequestSchema()) @response_schema(V20CredExRecordDetailSchema(), 200, description="") async def credential_exchange_issue(request: web.BaseRequest): - """ - Request handler for sending credential. + """Request handler for sending credential. Args: request: aiohttp request object @@ -1503,8 +1491,7 @@ async def credential_exchange_issue(request: web.BaseRequest): @request_schema(V20CredStoreRequestSchema()) @response_schema(V20CredExRecordDetailSchema(), 200, description="") async def credential_exchange_store(request: web.BaseRequest): - """ - Request handler for storing credential. + """Request handler for storing credential. Args: request: aiohttp request object @@ -1606,8 +1593,7 @@ async def credential_exchange_store(request: web.BaseRequest): @match_info_schema(V20CredExIdMatchInfoSchema()) @response_schema(V20IssueCredentialModuleResponseSchema(), 200, description="") async def credential_exchange_remove(request: web.BaseRequest): - """ - Request handler for removing a credential exchange record. + """Request handler for removing a credential exchange record. Args: request: aiohttp request object @@ -1635,8 +1621,7 @@ async def credential_exchange_remove(request: web.BaseRequest): @request_schema(V20CredIssueProblemReportRequestSchema()) @response_schema(V20IssueCredentialModuleResponseSchema(), 200, description="") async def credential_exchange_problem_report(request: web.BaseRequest): - """ - Request handler for sending problem report. + """Request handler for sending problem report. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py b/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py index 04a35f4e66..b1ed8216ea 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py @@ -1,8 +1,5 @@ -import asyncio import json -from copy import deepcopy -from time import time from asynctest import mock as async_mock, TestCase as AsyncTestCase @@ -46,7 +43,6 @@ REV_REG_DEF, SCHEMA, SCHEMA_ID, - TEST_DID, ) CRED_REQ = V20CredRequest( diff --git a/aries_cloudagent/protocols/notification/v1_0/handlers/ack_handler.py b/aries_cloudagent/protocols/notification/v1_0/handlers/ack_handler.py index 8063056695..e5f1fedc77 100644 --- a/aries_cloudagent/protocols/notification/v1_0/handlers/ack_handler.py +++ b/aries_cloudagent/protocols/notification/v1_0/handlers/ack_handler.py @@ -12,8 +12,7 @@ class V10AckHandler(BaseHandler): """Message handler class for generic acks.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for presentation acks. + """Message handler logic for presentation acks. Args: context: request context diff --git a/aries_cloudagent/protocols/notification/v1_0/messages/ack.py b/aries_cloudagent/protocols/notification/v1_0/messages/ack.py index 62a1d21c61..3c3b3345fd 100644 --- a/aries_cloudagent/protocols/notification/v1_0/messages/ack.py +++ b/aries_cloudagent/protocols/notification/v1_0/messages/ack.py @@ -19,8 +19,7 @@ class Meta: schema_class = "V10AckSchema" def __init__(self, status: str = None, **kwargs): - """ - Initialize an explicit ack message instance. + """Initialize an explicit ack message instance. Args: status: Status (default OK) diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py index 9b52d16679..9602d5ce7d 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py @@ -9,15 +9,13 @@ class OOBProblemReportMessageHandler(BaseHandler): - """ - Handler class for OOB Problem Report Message. + """Handler class for OOB Problem Report Message. Updates the ConnRecord Metadata state. """ async def handle(self, context: RequestContext, responder: BaseResponder): - """ - OOB Problem Report Message Handler. + """OOB Problem Report Message Handler. Args: context: Request context diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py index 653e565651..ae19d16441 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py @@ -12,8 +12,7 @@ class HandshakeReuseAcceptMessageHandler(BaseHandler): """Handler class for Handshake Reuse Accepted Message Handler under RFC 0434.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle Handshake Reuse Accepted Message Handler under RFC 0434. + """Handle Handshake Reuse Accepted Message Handler under RFC 0434. Args: context: Request context diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py index 0a34e5c85c..a312a2af1f 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py @@ -12,8 +12,7 @@ class HandshakeReuseMessageHandler(BaseHandler): """Handler class for Handshake Reuse Message Handler under RFC 0434.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle Handshake Reuse Message Handler under RFC 0434. + """Handle Handshake Reuse Message Handler under RFC 0434. Args: context: Request context diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py index 1c5ebefaad..c8b69357cb 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py @@ -3,18 +3,14 @@ from asynctest import mock as async_mock -from ......connections.models import connection_target from ......connections.models.conn_record import ConnRecord -from ......connections.models.diddoc import DIDDoc, PublicKey, PublicKeyType, Service from ......core.profile import ProfileSession from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder -from ......storage.base import BaseStorage -from ......storage.error import StorageNotFoundError from ......transport.inbound.receipt import MessageReceipt from ...handlers import problem_report_handler as test_module -from ...manager import OutOfBandManagerError, OutOfBandManager +from ...manager import OutOfBandManagerError from ...messages.problem_report import OOBProblemReport, ProblemReportReason diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py index d2e9c7e7ed..f403a1ce17 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py @@ -3,19 +3,14 @@ from asynctest import mock as async_mock -from ......connections.models import connection_target from ......connections.models.conn_record import ConnRecord -from ......connections.models.diddoc import DIDDoc, PublicKey, PublicKeyType, Service from ......core.profile import ProfileSession from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder -from ......storage.base import BaseStorage -from ......storage.error import StorageNotFoundError from ......transport.inbound.receipt import MessageReceipt from ...handlers import reuse_accept_handler as test_module -from ...manager import OutOfBandManagerError, OutOfBandManager -from ...messages.reuse import HandshakeReuse +from ...manager import OutOfBandManagerError from ...messages.reuse_accept import HandshakeReuseAccept diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py index ea54f754b3..d4d94f546c 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py @@ -3,18 +3,14 @@ from asynctest import mock as async_mock -from ......connections.models import connection_target from ......connections.models.conn_record import ConnRecord -from ......connections.models.diddoc import DIDDoc, PublicKey, PublicKeyType, Service from ......core.profile import ProfileSession from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder -from ......storage.base import BaseStorage -from ......storage.error import StorageNotFoundError from ......transport.inbound.receipt import MessageReceipt from ...handlers import reuse_handler as test_module -from ...manager import OutOfBandManagerError, OutOfBandManager +from ...manager import OutOfBandManagerError from ...messages.reuse import HandshakeReuse from ...messages.reuse_accept import HandshakeReuseAccept diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/manager.py b/aries_cloudagent/protocols/out_of_band/v1_0/manager.py index c38f026e63..007b43a675 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/manager.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/manager.py @@ -57,8 +57,7 @@ class OutOfBandManager(BaseConnectionManager): """Class for managing out of band messages.""" def __init__(self, profile: Profile): - """ - Initialize a OutOfBandManager. + """Initialize a OutOfBandManager. Args: profile: The profile for this out of band manager @@ -68,8 +67,7 @@ def __init__(self, profile: Profile): @property def profile(self) -> Profile: - """ - Accessor for the current profile. + """Accessor for the current profile. Returns: The profile for this connection manager @@ -94,8 +92,7 @@ async def create_invitation( goal_code: Optional[Text] = None, goal: Optional[Text] = None, ) -> InvitationRecord: - """ - Generate new connection invitation. + """Generate new connection invitation. This interaction represents an out-of-band communication channel. In the future and in practice, these sort of invitations will be received over any number of @@ -411,8 +408,7 @@ async def receive_invitation( alias: Optional[str] = None, mediation_id: Optional[str] = None, ) -> OobRecord: - """ - Receive an out of band invitation message. + """Receive an out of band invitation message. Args: invitation: invitation message @@ -891,8 +887,7 @@ async def _create_handshake_reuse_message( conn_record: ConnRecord, version: str, ) -> OobRecord: - """ - Create and Send a Handshake Reuse message under RFC 0434. + """Create and Send a Handshake Reuse message under RFC 0434. Args: oob_record: OOB Record @@ -954,8 +949,7 @@ async def receive_reuse_message( receipt: MessageReceipt, conn_rec: ConnRecord, ) -> None: - """ - Receive and process a HandshakeReuse message under RFC 0434. + """Receive and process a HandshakeReuse message under RFC 0434. Process a `HandshakeReuse` message by looking up the connection records using the MessageReceipt sender DID. @@ -1032,8 +1026,7 @@ async def receive_reuse_accepted_message( receipt: MessageReceipt, conn_record: ConnRecord, ) -> None: - """ - Receive and process a HandshakeReuseAccept message under RFC 0434. + """Receive and process a HandshakeReuseAccept message under RFC 0434. Process a `HandshakeReuseAccept` message by updating the OobRecord state to `accepted`. @@ -1112,8 +1105,7 @@ async def receive_problem_report( receipt: MessageReceipt, conn_record: ConnRecord, ) -> None: - """ - Receive and process a ProblemReport message from the inviter to invitee. + """Receive and process a ProblemReport message from the inviter to invitee. Process a `ProblemReport` message by updating the OobRecord state to `not_accepted`. diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/messages/invitation.py b/aries_cloudagent/protocols/out_of_band/v1_0/messages/invitation.py index 53f1ef0e66..09a2dfe19e 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/messages/invitation.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/messages/invitation.py @@ -126,8 +126,7 @@ def __init__( goal: Optional[Text] = None, **kwargs, ): - """ - Initialize invitation message object. + """Initialize invitation message object. Args: requests_attach: request attachments @@ -152,8 +151,7 @@ def wrap_message(cls, message: dict) -> AttachDecorator: return AttachDecorator.data_json(mapping=message, ident="request-0") def to_url(self, base_url: str = None) -> str: - """ - Convert an invitation message to URL format for sharing. + """Convert an invitation message to URL format for sharing. Returns: An invite url @@ -175,8 +173,7 @@ def to_url(self, base_url: str = None) -> str: @classmethod def from_url(cls, url: str) -> "InvitationMessage": - """ - Parse a URL-encoded invitation into an `InvitationMessage` instance. + """Parse a URL-encoded invitation into an `InvitationMessage` instance. Args: url: Url to decode @@ -296,8 +293,7 @@ class Meta: @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields. + """Validate schema fields. Args: data: The data to validate diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/messages/service.py b/aries_cloudagent/protocols/out_of_band/v1_0/messages/service.py index d54049f233..aca81b20f7 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/messages/service.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/messages/service.py @@ -31,8 +31,7 @@ def __init__( routing_keys: Sequence[str] = None, service_endpoint: str = None, ): - """ - Initialize a Service instance. + """Initialize a Service instance. Args: id: An identifier for this service block diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_invitation.py b/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_invitation.py index 10c5acccf0..4f33cbbbe9 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_invitation.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_invitation.py @@ -11,11 +11,9 @@ from .....didexchange.v1_0.message_types import ARIES_PROTOCOL as DIDX_PROTO from .....didexchange.v1_0.messages.request import DIDXRequest -from ...message_types import INVITATION from .. import invitation as test_module from ..invitation import HSProto, InvitationMessage, InvitationMessageSchema -from ..invitation import InvitationMessage, InvitationMessageSchema from ..service import Service TEST_DID = "55GkHamhTU1ZbTbV2ab9DE" diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_problem_report.py b/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_problem_report.py index c594ad146b..831d109b9f 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_problem_report.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_problem_report.py @@ -2,7 +2,7 @@ import logging import pytest -from unittest import mock, TestCase +from unittest import TestCase from ......messaging.models.base import BaseModelError diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_reuse.py b/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_reuse.py index 837698e718..b81721b0a4 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_reuse.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_reuse.py @@ -1,12 +1,11 @@ """Test Reuse Message.""" import pytest -from asynctest import TestCase as AsyncTestCase -from unittest import mock, TestCase +from unittest import TestCase from ......messaging.models.base import BaseModelError -from ..reuse import HandshakeReuse, HandshakeReuseSchema +from ..reuse import HandshakeReuse class TestReuseMessage(TestCase): diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_reuse_accept.py b/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_reuse_accept.py index 556493c618..269a36cd3c 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_reuse_accept.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_reuse_accept.py @@ -1,14 +1,13 @@ """Test Reuse Accept Message.""" import pytest -from asynctest import TestCase as AsyncTestCase -from unittest import mock, TestCase +from unittest import TestCase from ......messaging.models.base import BaseModelError from .....didcomm_prefix import DIDCommPrefix -from ..reuse_accept import HandshakeReuseAccept, HandshakeReuseAcceptSchema +from ..reuse_accept import HandshakeReuseAccept class TestReuseAcceptMessage(TestCase): diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/models/tests/test_invitation.py b/aries_cloudagent/protocols/out_of_band/v1_0/models/tests/test_invitation.py index 12dae75f89..9581e6a923 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/models/tests/test_invitation.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/models/tests/test_invitation.py @@ -1,6 +1,4 @@ -import json - -from asynctest import TestCase as AsyncTestCase, mock as async_mock +from asynctest import TestCase as AsyncTestCase from .....didcomm_prefix import DIDCommPrefix @@ -8,7 +6,7 @@ from ...messages.invitation import InvitationMessage -from ..invitation import InvitationRecord, InvitationRecordSchema +from ..invitation import InvitationRecord TEST_DID = "did:sov:55GkHamhTU1ZbTbV2ab9DE" diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/routes.py b/aries_cloudagent/protocols/out_of_band/v1_0/routes.py index 963e62e5fc..4f11ca51ca 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/routes.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/routes.py @@ -183,8 +183,7 @@ class InvitationReceiveQueryStringSchema(OpenAPISchema): @request_schema(InvitationCreateRequestSchema()) @response_schema(InvitationRecordSchema(), description="") async def invitation_create(request: web.BaseRequest): - """ - Request handler for creating a new connection invitation. + """Request handler for creating a new connection invitation. Args: request: aiohttp request object @@ -245,8 +244,7 @@ async def invitation_create(request: web.BaseRequest): @request_schema(InvitationMessageSchema()) @response_schema(OobRecordSchema(), 200, description="") async def invitation_receive(request: web.BaseRequest): - """ - Request handler for receiving a new connection invitation. + """Request handler for receiving a new connection invitation. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/out_of_band/v1_0/tests/test_manager.py index 6bac30daad..7bee844ce4 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/tests/test_manager.py @@ -80,7 +80,6 @@ OutOfBandManager, OutOfBandManagerError, ) -from ..message_types import INVITATION, MESSAGE_REUSE from ..messages.invitation import HSProto, InvitationMessage from ..messages.invitation import Service as OobService from ..messages.problem_report import ProblemReport, ProblemReportReason diff --git a/aries_cloudagent/protocols/present_proof/dif/pres_exch.py b/aries_cloudagent/protocols/present_proof/dif/pres_exch.py index a5af62db46..c7f974ddb1 100644 --- a/aries_cloudagent/protocols/present_proof/dif/pres_exch.py +++ b/aries_cloudagent/protocols/present_proof/dif/pres_exch.py @@ -382,7 +382,7 @@ def extract_info(self, data, **kwargs): new_data[key] = value data = new_data if "enum" in data: - if type(data.get("enum")) is not list: + if not isinstance(data.get("enum"), list): raise ValidationError("enum is not specified as a list") return data diff --git a/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py b/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py index bb46a35ccb..46492d8e87 100644 --- a/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py +++ b/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py @@ -1,5 +1,4 @@ -""" -Utilities for dif presentation exchange attachment. +"""Utilities for dif presentation exchange attachment. General Flow: create_vp -> @@ -224,8 +223,7 @@ async def get_sign_key_credential_subject_id( async def to_requirement( self, sr: SubmissionRequirements, descriptors: Sequence[InputDescriptors] ) -> Requirement: - """ - Return Requirement. + """Return Requirement. Args: sr: submission_requirement @@ -279,8 +277,7 @@ async def make_requirement( srs: Sequence[SubmissionRequirements] = None, descriptors: Sequence[InputDescriptors] = None, ) -> Requirement: - """ - Return Requirement. + """Return Requirement. Creates and return Requirement with nesting if required using to_requirement() @@ -318,8 +315,7 @@ async def make_requirement( return requirement def is_len_applicable(self, req: Requirement, val: int) -> bool: - """ - Check and validate requirement minimum, maximum and count. + """Check and validate requirement minimum, maximum and count. Args: req: Requirement @@ -340,8 +336,7 @@ def is_len_applicable(self, req: Requirement, val: int) -> bool: return True def contains(self, data: Sequence[str], e: str) -> bool: - """ - Check for e in data. + """Check for e in data. Returns True if e exists in data else return False @@ -363,8 +358,7 @@ async def filter_constraints( constraints: Constraints, credentials: Sequence[VCRecord], ) -> Sequence[VCRecord]: - """ - Return list of applicable VCRecords after applying filtering. + """Return list of applicable VCRecords after applying filtering. Args: constraints: Constraints @@ -457,11 +451,11 @@ def create_vcrecord(self, cred_dict: dict) -> VCRecord: """Return VCRecord from a credential dict.""" proofs = cred_dict.get("proof") or [] proof_types = None - if type(proofs) is dict: + if isinstance(proofs, dict): proofs = [proofs] if proofs: proof_types = [proof.get("type") for proof in proofs] - contexts = [ctx for ctx in cred_dict.get("@context") if type(ctx) is str] + contexts = [ctx for ctx in cred_dict.get("@context") if isinstance(ctx, str)] if "@graph" in cred_dict: for enclosed_data in cred_dict.get("@graph"): if ( @@ -476,14 +470,14 @@ def create_vcrecord(self, cred_dict: dict) -> VCRecord: given_id = str(uuid4()) # issuer issuer = cred_dict.get("issuer") - if type(issuer) is dict: + if isinstance(issuer, dict): issuer = issuer.get("id") # subjects subject_ids = None subjects = cred_dict.get("credentialSubject") if subjects: - if type(subjects) is dict: + if isinstance(subjects, dict): subjects = [subjects] subject_ids = [ subject.get("id") for subject in subjects if ("id" in subject) @@ -493,7 +487,7 @@ def create_vcrecord(self, cred_dict: dict) -> VCRecord: # Schemas schemas = cred_dict.get("credentialSchema", []) - if type(schemas) is dict: + if isinstance(schemas, dict): schemas = [schemas] schema_ids = [schema.get("id") for schema in schemas] document_loader = self.profile.inject(DocumentLoader) @@ -560,8 +554,7 @@ def reveal_doc(self, credential_dict: dict, constraints: Constraints): def new_credential_builder( self, new_credential: dict, unflatten_dict: dict ) -> dict: - """ - Update and return the new_credential. + """Update and return the new_credential. Args: new_credential: credential dict to be updated and returned @@ -574,8 +567,7 @@ def new_credential_builder( return new_credential async def filter_by_field(self, field: DIFField, credential: VCRecord) -> bool: - """ - Apply filter on VCRecord. + """Apply filter on VCRecord. Checks if a credential is applicable @@ -638,8 +630,7 @@ def string_to_timezone_aware_datetime(self, datetime_str: str) -> datetime: return dateutil_parser(datetime_str).replace(tzinfo=utc) def validate_patch(self, to_check: any, _filter: Filter) -> bool: - """ - Apply filter on match_value. + """Apply filter on match_value. Utility function used in applying filtering to a cred by triggering checks according to filter specification @@ -686,8 +677,7 @@ def validate_patch(self, to_check: any, _filter: Filter) -> bool: return return_val def check_filter_only_type_enforced(self, _filter: Filter) -> bool: - """ - Check if only type is specified in filter. + """Check if only type is specified in filter. Args: _filter: Filter @@ -711,8 +701,7 @@ def check_filter_only_type_enforced(self, _filter: Filter) -> bool: return False def process_numeric_val(self, val: any, _filter: Filter) -> bool: - """ - Trigger Filter checks. + """Trigger Filter checks. Trigger appropriate check for a number type filter, according to _filter spec. @@ -740,8 +729,7 @@ def process_numeric_val(self, val: any, _filter: Filter) -> bool: return False def process_string_val(self, val: any, _filter: Filter) -> bool: - """ - Trigger Filter checks. + """Trigger Filter checks. Trigger appropriate check for a string type filter, according to _filter spec. @@ -773,8 +761,7 @@ def process_string_val(self, val: any, _filter: Filter) -> bool: return False def exclusive_minimum_check(self, val: any, _filter: Filter) -> bool: - """ - Exclusiveminimum check. + """Exclusiveminimum check. Returns True if value greater than filter specified check @@ -804,8 +791,7 @@ def exclusive_minimum_check(self, val: any, _filter: Filter) -> bool: return False def exclusive_maximum_check(self, val: any, _filter: Filter) -> bool: - """ - Exclusivemaximum check. + """Exclusivemaximum check. Returns True if value less than filter specified check @@ -835,8 +821,7 @@ def exclusive_maximum_check(self, val: any, _filter: Filter) -> bool: return False def maximum_check(self, val: any, _filter: Filter) -> bool: - """ - Maximum check. + """Maximum check. Returns True if value less than equal to filter specified check @@ -866,8 +851,7 @@ def maximum_check(self, val: any, _filter: Filter) -> bool: return False def minimum_check(self, val: any, _filter: Filter) -> bool: - """ - Minimum check. + """Minimum check. Returns True if value greater than equal to filter specified check @@ -897,8 +881,7 @@ def minimum_check(self, val: any, _filter: Filter) -> bool: return False def length_check(self, val: any, _filter: Filter) -> bool: - """ - Length check. + """Length check. Returns True if length value string meets the minLength and maxLength specs @@ -922,8 +905,7 @@ def length_check(self, val: any, _filter: Filter) -> bool: return False def pattern_check(self, val: any, _filter: Filter) -> bool: - """ - Pattern check. + """Pattern check. Returns True if value string matches the specified pattern @@ -939,8 +921,7 @@ def pattern_check(self, val: any, _filter: Filter) -> bool: return False def const_check(self, val: any, _filter: Filter) -> bool: - """ - Const check. + """Const check. Returns True if value is equal to filter specified check @@ -956,8 +937,7 @@ def const_check(self, val: any, _filter: Filter) -> bool: return False def enum_check(self, val: any, _filter: Filter) -> bool: - """ - Enum check. + """Enum check. Returns True if value is contained to filter specified list @@ -973,8 +953,7 @@ def enum_check(self, val: any, _filter: Filter) -> bool: return False def subject_is_issuer(self, credential: VCRecord) -> bool: - """ - subject_is_issuer check. + """subject_is_issuer check. Returns True if cred issuer_id is in subject_ids @@ -1019,8 +998,7 @@ async def filter_schema( credentials: Sequence[VCRecord], schemas: SchemasInputDescriptorFilter, ) -> Sequence[VCRecord]: - """ - Filter by schema. + """Filter by schema. Returns list of credentials where credentialSchema.id or types matched with input_descriptors.schema.uri @@ -1043,8 +1021,7 @@ async def filter_schema( return result def credential_match_schema(self, credential: VCRecord, schema_id: str) -> bool: - """ - Credential matching by schema. + """Credential matching by schema. Used by filter_schema to check if credential.schema_ids or credential.types matched with schema_id @@ -1077,8 +1054,7 @@ async def apply_requirements( credentials: Sequence[VCRecord], records_filter: dict = None, ) -> dict: - """ - Apply Requirement. + """Apply Requirement. Args: req: Requirement @@ -1165,8 +1141,7 @@ async def apply_requirements( ) def is_numeric(self, val: any): - """ - Check if val is an int or float. + """Check if val is an int or float. Args: val: to check @@ -1193,8 +1168,7 @@ def is_numeric(self, val: any): async def merge_nested_results( self, nested_result: Sequence[dict], exclude: dict ) -> dict: - """ - Merge nested results with merged credentials. + """Merge nested results with merged credentials. Args: nested_result: Sequence of dict containing input_descriptor.id as keys @@ -1234,8 +1208,7 @@ async def create_vp( domain: str = None, records_filter: dict = None, ) -> Union[Sequence[dict], dict]: - """ - Create VerifiablePresentation. + """Create VerifiablePresentation. Args: credentials: Sequence of VCRecords @@ -1351,8 +1324,7 @@ async def merge( self, dict_descriptor_creds: dict, ) -> Tuple[Sequence[VCRecord], Sequence[InputDescriptorMapping]]: - """ - Return applicable credentials and descriptor_map for attachment. + """Return applicable credentials and descriptor_map for attachment. Used for generating the presentation_submission property with the descriptor_map, mantaining the order in which applicable credential @@ -1368,7 +1340,7 @@ async def merge( dict_of_descriptors = {} result = [] descriptors = [] - sorted_desc_keys = sorted(list(dict_descriptor_creds.keys())) + sorted_desc_keys = sorted(dict_descriptor_creds.keys()) for desc_id in sorted_desc_keys: credentials = dict_descriptor_creds.get(desc_id) for cred in credentials: @@ -1393,8 +1365,7 @@ async def verify_received_pres( pd: PresentationDefinition, pres: Union[Sequence[dict], dict], ): - """ - Verify credentials received in presentation. + """Verify credentials received in presentation. Args: pres: received VerifiablePresentation @@ -1493,7 +1464,7 @@ async def apply_constraint_received_cred( ) # Selective Disclosure check if is_limit_disclosure: - field_paths = set([path.replace("$.", "") for path in field_paths]) + field_paths = {path.replace("$.", "") for path in field_paths} mandatory_paths = { "@context", "type", diff --git a/aries_cloudagent/protocols/present_proof/dif/tests/test_data.py b/aries_cloudagent/protocols/present_proof/dif/tests/test_data.py index 125ca93419..96a538fccb 100644 --- a/aries_cloudagent/protocols/present_proof/dif/tests/test_data.py +++ b/aries_cloudagent/protocols/present_proof/dif/tests/test_data.py @@ -1,7 +1,5 @@ """Data for DIFPresExchHandler.""" import json -from pyld import jsonld -from pyld.jsonld import JsonLdProcessor from .....storage.vc_holder.vc_record import VCRecord @@ -10,29 +8,29 @@ def create_vcrecord(cred_dict: dict, expanded_types: list): given_id = cred_dict.get("id") - contexts = [ctx for ctx in cred_dict.get("@context") if type(ctx) is str] + contexts = [ctx for ctx in cred_dict.get("@context") if isinstance(ctx, str)] # issuer issuer = cred_dict.get("issuer") - if type(issuer) is dict: + if isinstance(issuer, dict): issuer = issuer.get("id") # subjects subjects = cred_dict.get("credentialSubject") - if type(subjects) is dict: + if isinstance(subjects, dict): subjects = [subjects] subject_ids = [subject.get("id") for subject in subjects if subject.get("id")] # Schemas schemas = cred_dict.get("credentialSchema", []) - if type(schemas) is dict: + if isinstance(schemas, dict): schemas = [schemas] schema_ids = [schema.get("id") for schema in schemas] # Proofs (this can be done easier if we use the expanded version) proofs = cred_dict.get("proof") or [] proof_types = None - if type(proofs) is dict: + if isinstance(proofs, dict): proofs = [proofs] if proofs: proof_types = [proof.get("type") for proof in proofs] diff --git a/aries_cloudagent/protocols/present_proof/dif/tests/test_pres_exch_handler.py b/aries_cloudagent/protocols/present_proof/dif/tests/test_pres_exch_handler.py index e487d218cf..055604e6a3 100644 --- a/aries_cloudagent/protocols/present_proof/dif/tests/test_pres_exch_handler.py +++ b/aries_cloudagent/protocols/present_proof/dif/tests/test_pres_exch_handler.py @@ -10,11 +10,9 @@ from aries_cloudagent.wallet.key_type import BLS12381G2, ED25519 from .....core.in_memory import InMemoryProfile -from .....did.did_key import DIDKey from .....resolver.did_resolver import DIDResolver from .....storage.vc_holder.vc_record import VCRecord from .....wallet.base import BaseWallet, DIDInfo -from .....wallet.crypto import KeyType from .....wallet.default_verification_key_strategy import ( DefaultVerificationKeyStrategy, BaseVerificationKeyStrategy, diff --git a/aries_cloudagent/protocols/present_proof/v1_0/__init__.py b/aries_cloudagent/protocols/present_proof/v1_0/__init__.py index f2921058ac..8bcc3e0dc9 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/__init__.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/__init__.py @@ -14,8 +14,7 @@ def problem_report_for_record( record: Union[ConnRecord, V10PresentationExchange], desc_en: str, ) -> PresentationProblemReport: - """ - Create problem report for record. + """Create problem report for record. Args: record: connection or exchange record @@ -43,8 +42,7 @@ async def report_problem( record: Union[ConnRecord, V10PresentationExchange], outbound_handler: Coroutine, ): - """ - Send problem report response and raise corresponding HTTP error. + """Send problem report response and raise corresponding HTTP error. Args: err: error for internal diagnostics diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py index d66c500fc0..6a3dfa9eef 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py @@ -14,8 +14,7 @@ class PresentationAckHandler(BaseHandler): """Message handler class for presentation acks.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for presentation acks. + """Message handler logic for presentation acks. Args: context: request context diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py index e30eb65306..7aa96f7f27 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py @@ -19,8 +19,7 @@ class PresentationHandler(BaseHandler): """Message handler class for presentations.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for presentations. + """Message handler logic for presentations. Args: context: request context diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py index fb5874145a..56ca1a6848 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py @@ -13,8 +13,7 @@ class PresentationProblemReportHandler(BaseHandler): """Message handler class for problem reports.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for problem reports. + """Message handler logic for problem reports. Args: context: request context diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py index 7977626453..d513123258 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py @@ -18,8 +18,7 @@ class PresentationProposalHandler(BaseHandler): """Message handler class for presentation proposals.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for presentation proposals. + """Message handler logic for presentation proposals. Args: context: proposal context diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py index f3477a9351..a34cdde4cd 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py @@ -23,8 +23,7 @@ class PresentationRequestHandler(BaseHandler): """Message handler class for Aries#0037 v1.0 presentation requests.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for Aries#0037 v1.0 presentation requests. + """Message handler logic for Aries#0037 v1.0 presentation requests. Args: context: request context diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py index 775bdb068a..28b4747502 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py @@ -1,5 +1,3 @@ -import pytest - from asynctest import mock as async_mock, TestCase as AsyncTestCase from ......core.oob_processor import OobMessageProcessor diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py index a60154533c..95c963f704 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py @@ -1,5 +1,3 @@ -import pytest - from asynctest import mock as async_mock, TestCase as AsyncTestCase from ......messaging.request_context import RequestContext diff --git a/aries_cloudagent/protocols/present_proof/v1_0/manager.py b/aries_cloudagent/protocols/present_proof/v1_0/manager.py index a7e154bd2e..b5a85278f9 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/manager.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/manager.py @@ -36,8 +36,7 @@ class PresentationManager: """Class for managing presentations.""" def __init__(self, profile: Profile): - """ - Initialize a PresentationManager. + """Initialize a PresentationManager. Args: profile: The profile instance for this presentation manager @@ -52,8 +51,7 @@ async def create_exchange_for_proposal( auto_present: bool = None, auto_remove: bool = None, ): - """ - Create a presentation exchange record for input presentation proposal. + """Create a presentation exchange record for input presentation proposal. Args: connection_id: connection identifier @@ -90,8 +88,7 @@ async def create_exchange_for_proposal( async def receive_proposal( self, message: PresentationProposal, connection_record: ConnRecord ): - """ - Receive a presentation proposal from message in context on manager creation. + """Receive a presentation proposal from message in context on manager creation. Returns: Presentation exchange record, created @@ -122,8 +119,7 @@ async def create_bound_request( nonce: str = None, comment: str = None, ): - """ - Create a presentation request bound to a proposal. + """Create a presentation request bound to a proposal. Args: presentation_exchange_record: Presentation exchange record for which @@ -178,8 +174,7 @@ async def create_exchange_for_request( auto_verify: bool = None, auto_remove: bool = None, ): - """ - Create a presentation exchange record for input presentation request. + """Create a presentation exchange record for input presentation request. Args: connection_id: connection identifier @@ -215,8 +210,7 @@ async def create_exchange_for_request( async def receive_request( self, presentation_exchange_record: V10PresentationExchange ): - """ - Receive a presentation request. + """Receive a presentation request. Args: presentation_exchange_record: presentation exchange record with @@ -242,8 +236,7 @@ async def create_presentation( requested_credentials: dict, comment: str = None, ): - """ - Create a presentation. + """Create a presentation. Args: presentation_exchange_record: Record to update @@ -318,8 +311,7 @@ async def receive_presentation( connection_record: Optional[ConnRecord], oob_record: Optional[OobRecord], ): - """ - Receive a presentation, from message in context on manager creation. + """Receive a presentation, from message in context on manager creation. Returns: presentation exchange record, retrieved and updated @@ -408,8 +400,7 @@ async def verify_presentation( presentation_exchange_record: V10PresentationExchange, responder: Optional[BaseResponder] = None, ): - """ - Verify a presentation. + """Verify a presentation. Args: presentation_exchange_record: presentation exchange record @@ -457,8 +448,7 @@ async def send_presentation_ack( presentation_exchange_record: V10PresentationExchange, responder: Optional[BaseResponder] = None, ): - """ - Send acknowledgement of presentation receipt. + """Send acknowledgement of presentation receipt. Args: presentation_exchange_record: presentation exchange record with thread id @@ -516,8 +506,7 @@ async def send_presentation_ack( async def receive_presentation_ack( self, message: PresentationAck, connection_record: Optional[ConnRecord] ): - """ - Receive a presentation ack, from message in context on manager creation. + """Receive a presentation ack, from message in context on manager creation. Returns: presentation exchange record, retrieved and updated @@ -556,8 +545,7 @@ async def receive_presentation_ack( async def receive_problem_report( self, message: PresentationProblemReport, connection_id: str ): - """ - Receive problem report. + """Receive problem report. Returns: presentation exchange record, retrieved and updated diff --git a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation.py b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation.py index 9b37e4255d..46abf095bf 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation.py @@ -32,8 +32,7 @@ def __init__( presentations_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize presentation object. + """Initialize presentation object. Args: presentations_attach: attachments @@ -47,8 +46,7 @@ def __init__( ) def indy_proof(self, index: int = 0): - """ - Retrieve and decode indy proof from attachment. + """Retrieve and decode indy proof from attachment. Args: index: ordinal in attachment list to decode and return diff --git a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_ack.py b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_ack.py index 67103a3871..f2abc1bc5d 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_ack.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_ack.py @@ -21,8 +21,7 @@ class Meta: schema_class = "PresentationAckSchema" def __init__(self, status: str = None, verification_result: str = None, **kwargs): - """ - Initialize an explicit ack message instance. + """Initialize an explicit ack message instance. Args: status: Status (default OK) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_problem_report.py b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_problem_report.py index 42a7139a2e..cc0653653a 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_problem_report.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_problem_report.py @@ -46,8 +46,7 @@ class Meta: @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields. + """Validate schema fields. Args: data: The data to validate diff --git a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_proposal.py b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_proposal.py index a000d5a84c..f5b6d53487 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_proposal.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_proposal.py @@ -30,8 +30,7 @@ def __init__( presentation_proposal: IndyPresPreview = None, **kwargs, ): - """ - Initialize presentation proposal object. + """Initialize presentation proposal object. Args: comment: optional human-readable comment diff --git a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_request.py b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_request.py index 1cac870cf4..978fe46b23 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_request.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_request.py @@ -35,8 +35,7 @@ def __init__( request_presentations_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize presentation request object. + """Initialize presentation request object. Args: request_presentations_attach: proof request attachments @@ -50,8 +49,7 @@ def __init__( ) def indy_proof_request(self, index: int = 0): - """ - Retrieve and decode indy proof request from attachment. + """Retrieve and decode indy proof request from attachment. Args: index: ordinal in attachment list to decode and return diff --git a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_webhook.py b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_webhook.py index 0a58f25e71..d0de978ad2 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_webhook.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/messages/presentation_webhook.py @@ -25,8 +25,7 @@ def __init__( self, **kwargs, ): - """ - Initialize webhook object from V10PresentationExchange. + """Initialize webhook object from V10PresentationExchange. from a list of accepted attributes. """ diff --git a/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation.py b/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation.py index ae4a817153..da1435ff8c 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation.py @@ -1,16 +1,13 @@ import json -from datetime import datetime, timezone from unittest import TestCase -from ......indy.models.pres_preview import PRESENTATION_PREVIEW from ......messaging.decorators.attach_decorator import AttachDecorator -from ......messaging.util import str_to_datetime, str_to_epoch from .....didcomm_prefix import DIDCommPrefix from ...message_types import ATTACH_DECO_IDS, PRESENTATION -from ..presentation import Presentation, PresentationSchema +from ..presentation import Presentation INDY_PROOF = json.loads( """{ diff --git a/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_ack.py b/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_ack.py index 783e40f82f..57675a5b5b 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_ack.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_ack.py @@ -1,6 +1,5 @@ import json -from datetime import datetime, timezone from unittest import TestCase from .....didcomm_prefix import DIDCommPrefix diff --git a/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_proposal.py b/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_proposal.py index 2c43f97269..bd2a1b7bae 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_proposal.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_proposal.py @@ -4,7 +4,6 @@ IndyPresAttrSpec, IndyPresPredSpec, IndyPresPreview, - PRESENTATION_PREVIEW, ) from .....didcomm_prefix import DIDCommPrefix diff --git a/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_request.py b/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_request.py index c1e3ebcdaf..3a71200006 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_request.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/messages/tests/test_presentation_request.py @@ -2,15 +2,14 @@ from datetime import datetime, timezone from unittest import TestCase -from ......indy.models.pres_preview import PRESENTATION_PREVIEW from ......messaging.decorators.attach_decorator import AttachDecorator -from ......messaging.util import str_to_datetime, str_to_epoch +from ......messaging.util import str_to_epoch from .....didcomm_prefix import DIDCommPrefix from ...message_types import ATTACH_DECO_IDS, PRESENTATION_REQUEST -from ..presentation_request import PresentationRequest, PresentationRequestSchema +from ..presentation_request import PresentationRequest NOW_8601 = datetime.utcnow().replace(tzinfo=timezone.utc).isoformat(" ", "seconds") diff --git a/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py b/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py index 4b60be980d..a32c1355eb 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py @@ -168,8 +168,7 @@ async def save_error_state( log_params: Mapping[str, Any] = None, log_override: bool = False, ): - """ - Save record error state if need be; log and swallow any storage error. + """Save record error state if need be; log and swallow any storage error. Args: session: The profile session to use @@ -197,8 +196,7 @@ async def save_error_state( # Override async def emit_event(self, session: ProfileSession, payload: Any = None): - """ - Emit an event. + """Emit an event. Args: session: The profile session to use diff --git a/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py b/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py index 3e5a579401..0498a89a8e 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py @@ -6,10 +6,8 @@ IndyPresPredSpec, IndyPresPreview, ) -from ......messaging.decorators.attach_decorator import AttachDecorator from ......messaging.models.base_record import BaseExchangeRecord, BaseExchangeSchema -from ...message_types import PRESENTATION_PROPOSAL from ...messages.presentation_proposal import PresentationProposal from .. import presentation_exchange as test_module diff --git a/aries_cloudagent/protocols/present_proof/v1_0/routes.py b/aries_cloudagent/protocols/present_proof/v1_0/routes.py index 2470ff1e87..32ac5b431b 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/routes.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/routes.py @@ -286,8 +286,7 @@ class V10PresExIdMatchInfoSchema(OpenAPISchema): @querystring_schema(V10PresentationExchangeListQueryStringSchema) @response_schema(V10PresentationExchangeListSchema(), 200, description="") async def presentation_exchange_list(request: web.BaseRequest): - """ - Request handler for searching presentation exchange records. + """Request handler for searching presentation exchange records. Args: request: aiohttp request object @@ -327,8 +326,7 @@ async def presentation_exchange_list(request: web.BaseRequest): @match_info_schema(V10PresExIdMatchInfoSchema()) @response_schema(V10PresentationExchangeSchema(), 200, description="") async def presentation_exchange_retrieve(request: web.BaseRequest): - """ - Request handler for fetching a single presentation exchange record. + """Request handler for fetching a single presentation exchange record. Args: request: aiohttp request object @@ -376,8 +374,7 @@ async def presentation_exchange_retrieve(request: web.BaseRequest): @querystring_schema(CredentialsFetchQueryStringSchema()) @response_schema(IndyCredPrecisSchema(many=True), 200, description="") async def presentation_exchange_credentials_list(request: web.BaseRequest): - """ - Request handler for searching applicable credential records. + """Request handler for searching applicable credential records. Args: request: aiohttp request object @@ -453,8 +450,7 @@ async def presentation_exchange_credentials_list(request: web.BaseRequest): @request_schema(V10PresentationProposalRequestSchema()) @response_schema(V10PresentationExchangeSchema(), 200, description="") async def presentation_exchange_send_proposal(request: web.BaseRequest): - """ - Request handler for sending a presentation proposal. + """Request handler for sending a presentation proposal. Args: request: aiohttp request object @@ -537,8 +533,7 @@ async def presentation_exchange_send_proposal(request: web.BaseRequest): @request_schema(V10PresentationCreateRequestRequestSchema()) @response_schema(V10PresentationExchangeSchema(), 200, description="") async def presentation_exchange_create_request(request: web.BaseRequest): - """ - Request handler for creating a free presentation request. + """Request handler for creating a free presentation request. The presentation request will not be bound to any proposal or existing connection. @@ -615,8 +610,7 @@ async def presentation_exchange_create_request(request: web.BaseRequest): @request_schema(V10PresentationSendRequestRequestSchema()) @response_schema(V10PresentationExchangeSchema(), 200, description="") async def presentation_exchange_send_free_request(request: web.BaseRequest): - """ - Request handler for sending a presentation request free from any proposal. + """Request handler for sending a presentation request free from any proposal. Args: request: aiohttp request object @@ -704,8 +698,7 @@ async def presentation_exchange_send_free_request(request: web.BaseRequest): @request_schema(V10PresentationSendRequestToProposalSchema()) @response_schema(V10PresentationExchangeSchema(), 200, description="") async def presentation_exchange_send_bound_request(request: web.BaseRequest): - """ - Request handler for sending a presentation request bound to a proposal. + """Request handler for sending a presentation request bound to a proposal. Args: request: aiohttp request object @@ -797,8 +790,7 @@ async def presentation_exchange_send_bound_request(request: web.BaseRequest): @request_schema(V10PresentationSendRequestSchema()) @response_schema(V10PresentationExchangeSchema(), description="") async def presentation_exchange_send_presentation(request: web.BaseRequest): - """ - Request handler for sending a presentation. + """Request handler for sending a presentation. Args: request: aiohttp request object @@ -911,8 +903,7 @@ async def presentation_exchange_send_presentation(request: web.BaseRequest): @match_info_schema(V10PresExIdMatchInfoSchema()) @response_schema(V10PresentationExchangeSchema(), description="") async def presentation_exchange_verify_presentation(request: web.BaseRequest): - """ - Request handler for verifying a presentation request. + """Request handler for verifying a presentation request. Args: request: aiohttp request object @@ -986,8 +977,7 @@ async def presentation_exchange_verify_presentation(request: web.BaseRequest): @request_schema(V10PresentationProblemReportRequestSchema()) @response_schema(V10PresentProofModuleResponseSchema(), 200, description="") async def presentation_exchange_problem_report(request: web.BaseRequest): - """ - Request handler for sending problem report. + """Request handler for sending problem report. Args: request: aiohttp request object @@ -1027,8 +1017,7 @@ async def presentation_exchange_problem_report(request: web.BaseRequest): @match_info_schema(V10PresExIdMatchInfoSchema()) @response_schema(V10PresentProofModuleResponseSchema(), description="") async def presentation_exchange_remove(request: web.BaseRequest): - """ - Request handler for removing a presentation exchange record. + """Request handler for removing a presentation exchange record. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py index 97675469e4..97f77aac9e 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py @@ -10,24 +10,19 @@ from .....core.in_memory import InMemoryProfile from .....indy.holder import IndyHolder, IndyHolderError -from .....indy.issuer import IndyIssuer -from .....indy.sdk.holder import IndySdkHolder from .....indy.models.xform import indy_proof_req_preview2indy_requested_creds from .....indy.models.pres_preview import ( IndyPresAttrSpec, IndyPresPreview, IndyPresPredSpec, ) -from .....indy.sdk.verifier import IndySdkVerifier from .....indy.verifier import IndyVerifier from .....ledger.base import BaseLedger from .....ledger.multiple_ledger.ledger_requests_executor import ( IndyLedgerRequestsExecutor, ) from .....messaging.decorators.attach_decorator import AttachDecorator -from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder, MockResponder -from .....storage.error import StorageNotFoundError from ....didcomm_prefix import DIDCommPrefix @@ -37,7 +32,6 @@ from ..manager import PresentationManager, PresentationManagerError from ..message_types import ATTACH_DECO_IDS, PRESENTATION, PRESENTATION_REQUEST from ..messages.presentation import Presentation -from ..messages.presentation_ack import PresentationAck from ..messages.presentation_problem_report import PresentationProblemReport from ..messages.presentation_proposal import PresentationProposal from ..messages.presentation_request import PresentationRequest @@ -376,7 +370,7 @@ async def test_create_exchange_for_proposal(self): assert exchange.initiator == V10PresentationExchange.INITIATOR_SELF assert exchange.role == V10PresentationExchange.ROLE_PROVER assert exchange.state == V10PresentationExchange.STATE_PROPOSAL_SENT - assert exchange.auto_remove == True + assert exchange.auto_remove is True async def test_receive_proposal(self): connection_record = async_mock.MagicMock(connection_id=CONN_ID) @@ -439,7 +433,7 @@ async def test_create_exchange_for_request(self): assert exchange.initiator == V10PresentationExchange.INITIATOR_SELF assert exchange.role == V10PresentationExchange.ROLE_VERIFIER assert exchange.state == V10PresentationExchange.STATE_REQUEST_SENT - assert exchange.auto_remove == True + assert exchange.auto_remove is True async def test_receive_request(self): exchange_in = V10PresentationExchange() diff --git a/aries_cloudagent/protocols/present_proof/v2_0/__init__.py b/aries_cloudagent/protocols/present_proof/v2_0/__init__.py index 2b8a888355..04d58ea726 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/__init__.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/__init__.py @@ -14,8 +14,7 @@ def problem_report_for_record( record: Union[ConnRecord, V20PresExRecord], desc_en: str, ) -> V20PresProblemReport: - """ - Create problem report for record. + """Create problem report for record. Args: record: connection or exchange record @@ -43,8 +42,7 @@ async def report_problem( record: Union[ConnRecord, V20PresExRecord], outbound_handler: Coroutine, ): - """ - Send problem report response and raise corresponding HTTP error. + """Send problem report response and raise corresponding HTTP error. Args: err: error for internal diagnostics diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py index 8291a0e3fa..868d7148bf 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py @@ -137,8 +137,7 @@ async def create_bound_request( pres_ex_record: V20PresExRecord, request_data: dict = None, ) -> Tuple[V20PresFormat, AttachDecorator]: - """ - Create a presentation request bound to a proposal. + """Create a presentation request bound to a proposal. Args: pres_ex_record: Presentation exchange record for which @@ -462,8 +461,7 @@ async def receive_pres(self, message: V20Pres, pres_ex_record: V20PresExRecord): return False async def verify_pres(self, pres_ex_record: V20PresExRecord) -> V20PresExRecord: - """ - Verify a presentation. + """Verify a presentation. Args: pres_ex_record: presentation exchange record diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py index 699b1ab858..8143083c0a 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py @@ -19,11 +19,6 @@ BbsBlsSignatureProof2020, ) from .......vc.tests.document_loader import custom_document_loader -from .......vc.vc_ld.prove import ( - sign_presentation, - create_presentation, - derive_credential, -) from .......vc.vc_ld.validation_result import PresentationVerificationResult from .......wallet.base import BaseWallet @@ -49,7 +44,6 @@ from ...handler import V20PresFormatHandlerError from .. import handler as test_module -from .....dif.pres_exch_handler import DIFPresExchHandler as test_pe_handler_module from ..handler import DIFPresFormatHandler TEST_DID_SOV = "did:sov:LjgpST2rjsoxYegQDRm7EL" diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py index 96c01b83c2..1d8a2e5d07 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py @@ -33,8 +33,7 @@ def __init__(self, profile: Profile): @property def profile(self) -> Profile: - """ - Accessor for the current profile instance. + """Accessor for the current profile instance. Returns: The profile instance for this presentation exchange format diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py index 8f0a3e5057..16ebb7fec6 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py @@ -99,8 +99,7 @@ async def create_bound_request( pres_ex_record: V20PresExRecord, request_data: dict = None, ) -> Tuple[V20PresFormat, AttachDecorator]: - """ - Create a presentation request bound to a proposal. + """Create a presentation request bound to a proposal. Args: pres_ex_record: Presentation exchange record for which @@ -258,7 +257,7 @@ def _check_proof_vs_proposal(): req_value = proof_req_pred_spec["p_value"] req_restrictions = proof_req_pred_spec.get("restrictions", {}) for req_restriction in req_restrictions: - for k in [k for k in req_restriction]: # cannot modify en passant + for k in list(req_restriction): # cannot modify en passant if k.startswith("attr::"): req_restriction.pop(k) # let indy-sdk reject mismatch here sub_proof_index = pred_spec["sub_proof_index"] @@ -306,8 +305,7 @@ def _check_proof_vs_proposal(): _check_proof_vs_proposal() async def verify_pres(self, pres_ex_record: V20PresExRecord) -> V20PresExRecord: - """ - Verify a presentation. + """Verify a presentation. Args: pres_ex_record: presentation exchange record diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py index d7d20508f1..2534a65c4f 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py @@ -14,8 +14,7 @@ class V20PresAckHandler(BaseHandler): """Message handler class for presentation acks.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for presentation acks. + """Message handler logic for presentation acks. Args: context: request context diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py index 493cfad5c1..9a93d68cc0 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py @@ -19,8 +19,7 @@ class V20PresHandler(BaseHandler): """Message handler class for presentations.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for presentations. + """Message handler logic for presentations. Args: context: request context diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py index 3b76e30af6..32c5e23e0a 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py @@ -13,8 +13,7 @@ class V20PresProblemReportHandler(BaseHandler): """Message handler class for problem reports.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for problem reports. + """Message handler logic for problem reports. Args: context: request context diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py index e20c1d620c..23b16c0ebf 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py @@ -18,8 +18,7 @@ class V20PresProposalHandler(BaseHandler): """Message handler class for presentation proposals.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for presentation proposals. + """Message handler logic for presentation proposals. Args: context: proposal context diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py index 4b0fc18f69..abac0f7398 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py @@ -23,8 +23,7 @@ class V20PresRequestHandler(BaseHandler): """Message handler class for v2.0 presentation requests.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Message handler logic for v2.0 presentation requests. + """Message handler logic for v2.0 presentation requests. Args: context: request context diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py index 0603e77626..b28027c263 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py @@ -1,5 +1,3 @@ -import pytest - from asynctest import mock as async_mock, TestCase as AsyncTestCase from ......core.oob_processor import OobMessageProcessor diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py index c0e28fa043..786d78bee5 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py @@ -1,5 +1,4 @@ from asynctest import mock as async_mock, TestCase as AsyncTestCase -from copy import deepcopy from ......core.oob_processor import OobMessageProcessor from ......indy.holder import IndyHolder diff --git a/aries_cloudagent/protocols/present_proof/v2_0/manager.py b/aries_cloudagent/protocols/present_proof/v2_0/manager.py index bd727bf744..083dcac5ac 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/manager.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/manager.py @@ -30,8 +30,7 @@ class V20PresManager: """Class for managing presentations.""" def __init__(self, profile: Profile): - """ - Initialize a V20PresManager. + """Initialize a V20PresManager. Args: profile: The profile instance for this presentation manager @@ -46,8 +45,7 @@ async def create_exchange_for_proposal( auto_present: bool = None, auto_remove: bool = None, ): - """ - Create a presentation exchange record for input presentation proposal. + """Create a presentation exchange record for input presentation proposal. Args: connection_id: connection identifier @@ -85,8 +83,7 @@ async def create_exchange_for_proposal( async def receive_pres_proposal( self, message: V20PresProposal, conn_record: ConnRecord ): - """ - Receive a presentation proposal from message in context on manager creation. + """Receive a presentation proposal from message in context on manager creation. Returns: Presentation exchange record, created @@ -116,8 +113,7 @@ async def create_bound_request( request_data: dict = None, comment: str = None, ): - """ - Create a presentation request bound to a proposal. + """Create a presentation request bound to a proposal. Args: pres_ex_record: Presentation exchange record for which @@ -173,8 +169,7 @@ async def create_exchange_for_request( auto_verify: bool = None, auto_remove: bool = None, ): - """ - Create a presentation exchange record for input presentation request. + """Create a presentation exchange record for input presentation request. Args: connection_id: connection identifier @@ -208,8 +203,7 @@ async def create_exchange_for_request( return pres_ex_record async def receive_pres_request(self, pres_ex_record: V20PresExRecord): - """ - Receive a presentation request. + """Receive a presentation request. Args: pres_ex_record: presentation exchange record with request to receive @@ -233,8 +227,7 @@ async def create_pres( *, comment: str = None, ) -> Tuple[V20PresExRecord, V20Pres]: - """ - Create a presentation. + """Create a presentation. Args: pres_ex_record: record to update @@ -323,8 +316,7 @@ async def receive_pres( connection_record: Optional[ConnRecord], oob_record: Optional[OobRecord], ): - """ - Receive a presentation, from message in context on manager creation. + """Receive a presentation, from message in context on manager creation. Returns: presentation exchange record, retrieved and updated @@ -385,8 +377,7 @@ async def receive_pres( async def verify_pres( self, pres_ex_record: V20PresExRecord, responder: Optional[BaseResponder] = None ): - """ - Verify a presentation. + """Verify a presentation. Args: pres_ex_record: presentation exchange record @@ -423,8 +414,7 @@ async def verify_pres( async def send_pres_ack( self, pres_ex_record: V20PresExRecord, responder: Optional[BaseResponder] = None ): - """ - Send acknowledgement of presentation receipt. + """Send acknowledgement of presentation receipt. Args: pres_ex_record: presentation exchange record with thread id @@ -456,8 +446,7 @@ async def send_pres_ack( ) async def receive_pres_ack(self, message: V20PresAck, conn_record: ConnRecord): - """ - Receive a presentation ack, from message in context on manager creation. + """Receive a presentation ack, from message in context on manager creation. Returns: presentation exchange record, retrieved and updated @@ -489,8 +478,7 @@ async def receive_pres_ack(self, message: V20PresAck, conn_record: ConnRecord): async def receive_problem_report( self, message: V20PresProblemReport, connection_id: str ): - """ - Receive problem report. + """Receive problem report. Returns: presentation exchange record, retrieved and updated diff --git a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres.py b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres.py index bad86c88c0..6db821b4e3 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres.py @@ -34,8 +34,7 @@ def __init__( presentations_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize presentation object. + """Initialize presentation object. Args: presentations_attach: attachments @@ -50,8 +49,7 @@ def __init__( ) def attachment(self, fmt: V20PresFormat.Format = None) -> dict: - """ - Return attached presentation item. + """Return attached presentation item. Args: fmt: format of attachment in list to decode and return diff --git a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_ack.py b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_ack.py index f8f235df7d..9abc71172a 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_ack.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_ack.py @@ -19,8 +19,7 @@ class Meta: schema_class = "V20PresAckSchema" def __init__(self, status: str = None, verification_result: str = None, **kwargs): - """ - Initialize an explicit ack message instance. + """Initialize an explicit ack message instance. Args: status: Status (default OK) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_problem_report.py b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_problem_report.py index fd4b8f3416..96e76e5bb4 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_problem_report.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_problem_report.py @@ -46,8 +46,7 @@ class Meta: @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields. + """Validate schema fields. Args: data: The data to validate diff --git a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_proposal.py b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_proposal.py index cf3179d530..12511f4a41 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_proposal.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_proposal.py @@ -36,8 +36,7 @@ def __init__( proposals_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize pres proposal object. + """Initialize pres proposal object. Args: comment: optional human-readable comment @@ -50,8 +49,7 @@ def __init__( self.proposals_attach = list(proposals_attach) if proposals_attach else [] def attachment(self, fmt: V20PresFormat.Format = None) -> dict: - """ - Return attached proposal item. + """Return attached proposal item. Args: fmt: format of attachment in list to decode and return diff --git a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_request.py b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_request.py index b62b3c8d23..e8efc553cb 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_request.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_request.py @@ -37,8 +37,7 @@ def __init__( request_presentations_attach: Sequence[AttachDecorator] = None, **kwargs, ): - """ - Initialize presentation request object. + """Initialize presentation request object. Args: request_presentations_attach: proof request attachments @@ -54,8 +53,7 @@ def __init__( ) def attachment(self, fmt: V20PresFormat.Format = None) -> dict: - """ - Return attached presentation request item. + """Return attached presentation request item. Args: fmt: format of attachment in list to decode and return diff --git a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_webhook.py b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_webhook.py index cec96cd089..e5d3cc3228 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_webhook.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/messages/pres_webhook.py @@ -25,8 +25,7 @@ def __init__( self, **kwargs, ): - """ - Initialize webhook object from V20PresExRecord. + """Initialize webhook object from V20PresExRecord. from a list of accepted attributes. """ diff --git a/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres.py b/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres.py index ccd14b0896..892abd0542 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres.py @@ -1,19 +1,16 @@ import json -import pytest -from datetime import datetime, timezone from unittest import TestCase from ......messaging.decorators.attach_decorator import AttachDecorator from ......messaging.models.base import BaseModelError -from ......messaging.util import str_to_datetime, str_to_epoch from .....didcomm_prefix import DIDCommPrefix from ...message_types import ATTACHMENT_FORMAT, PRES_20 from ..pres_format import V20PresFormat -from ..pres import V20Pres, V20PresSchema +from ..pres import V20Pres INDY_PROOF = json.loads( # indy returns proof json-encoded: json-decode before base64 """{ diff --git a/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_ack.py b/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_ack.py index d1cb6627ed..7acf919ec7 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_ack.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_ack.py @@ -1,6 +1,5 @@ import json -from datetime import datetime, timezone from unittest import TestCase from .....didcomm_prefix import DIDCommPrefix diff --git a/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_format.py b/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_format.py index 90a62f5465..dcdaae3c36 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_format.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_format.py @@ -1,12 +1,6 @@ from unittest import TestCase -from marshmallow import ValidationError -from ......indy.models.pres_preview import ( - IndyPresAttrSpec, - IndyPresPreview, - IndyPresPredSpec, -) from ......messaging.decorators.attach_decorator import AttachDecorator from ..pres_format import V20PresFormat diff --git a/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_proposal.py b/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_proposal.py index a2815c2ce4..a4c27ce8ac 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_proposal.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_proposal.py @@ -2,12 +2,6 @@ from unittest import TestCase -from ......indy.models.pres_preview import ( - IndyPresAttrSpec, - IndyPresPredSpec, - IndyPresPreview, - PRESENTATION_PREVIEW, -) from ......messaging.decorators.attach_decorator import AttachDecorator from ......messaging.models.base import BaseModelError @@ -18,7 +12,7 @@ from ..pres_format import V20PresFormat from ..pres_proposal import V20PresProposal -CD_ID = f"NcYxiDXkpYi6ov5FcYDi1e:3:CL:12:tag1" +CD_ID = "NcYxiDXkpYi6ov5FcYDi1e:3:CL:12:tag1" INDY_PROOF_REQ = [ { "name": "proof-req", diff --git a/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_request.py b/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_request.py index 91b87bfa6e..65e9dfab74 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_request.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/messages/tests/test_pres_request.py @@ -1,22 +1,16 @@ -import json -import pytest - -from datetime import datetime, timezone from unittest import TestCase -from ......indy.models.pres_preview import PRESENTATION_PREVIEW from ......messaging.decorators.attach_decorator import AttachDecorator from ......messaging.models.base import BaseModelError -from ......messaging.util import str_to_datetime, str_to_epoch from .....didcomm_prefix import DIDCommPrefix from ...message_types import ATTACHMENT_FORMAT, PRES_20_REQUEST from ..pres_format import V20PresFormat -from ..pres_request import V20PresRequest, V20PresRequestSchema +from ..pres_request import V20PresRequest -CD_ID = f"NcYxiDXkpYi6ov5FcYDi1e:3:CL:12:tag1" +CD_ID = "NcYxiDXkpYi6ov5FcYDi1e:3:CL:12:tag1" INDY_PROOF_REQ = [ { "name": "proof-req", diff --git a/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py b/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py index e50e3af207..06f43036ea 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py @@ -154,8 +154,7 @@ async def save_error_state( log_params: Mapping[str, Any] = None, log_override: bool = False, ): - """ - Save record error state if need be; log and swallow any storage error. + """Save record error state if need be; log and swallow any storage error. Args: session: The profile session to use @@ -183,8 +182,7 @@ async def save_error_state( # Override async def emit_event(self, session: ProfileSession, payload: Any = None): - """ - Emit an event. + """Emit an event. Args: session: The profile session to use diff --git a/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py b/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py index b307a4fa9b..ba27e20f45 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py @@ -1,11 +1,6 @@ from asynctest import mock as async_mock, TestCase as AsyncTestCase from ......core.in_memory import InMemoryProfile -from ......indy.models.pres_preview import ( - IndyPresAttrSpec, - IndyPresPredSpec, - IndyPresPreview, -) from ......messaging.decorators.attach_decorator import AttachDecorator from ......messaging.models.base_record import BaseExchangeRecord, BaseExchangeSchema diff --git a/aries_cloudagent/protocols/present_proof/v2_0/routes.py b/aries_cloudagent/protocols/present_proof/v2_0/routes.py index 14f2160c14..eba9138663 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/routes.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/routes.py @@ -129,8 +129,7 @@ class V20PresProposalByFormatSchema(OpenAPISchema): @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields: data must have at least one format. + """Validate schema fields: data must have at least one format. Args: data: The data to validate @@ -205,8 +204,7 @@ class V20PresRequestByFormatSchema(OpenAPISchema): @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields: data must have at least one format. + """Validate schema fields: data must have at least one format. Args: data: The data to validate @@ -321,8 +319,7 @@ class V20PresSpecByFormatRequestSchema(AdminAPIMessageTracingSchema): @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields: specify exactly one format. + """Validate schema fields: specify exactly one format. Args: data: The data to validate @@ -428,8 +425,7 @@ def _formats_attach(by_format: Mapping, msg_type: str, spec: str) -> Mapping: @querystring_schema(V20PresExRecordListQueryStringSchema) @response_schema(V20PresExRecordListSchema(), 200, description="") async def present_proof_list(request: web.BaseRequest): - """ - Request handler for searching presentation exchange records. + """Request handler for searching presentation exchange records. Args: request: aiohttp request object @@ -471,8 +467,7 @@ async def present_proof_list(request: web.BaseRequest): @match_info_schema(V20PresExIdMatchInfoSchema()) @response_schema(V20PresExRecordSchema(), 200, description="") async def present_proof_retrieve(request: web.BaseRequest): - """ - Request handler for fetching a single presentation exchange record. + """Request handler for fetching a single presentation exchange record. Args: request: aiohttp request object @@ -518,8 +513,7 @@ async def present_proof_retrieve(request: web.BaseRequest): @querystring_schema(V20CredentialsFetchQueryStringSchema()) @response_schema(IndyCredPrecisSchema(many=True), 200, description="") async def present_proof_credentials_list(request: web.BaseRequest): - """ - Request handler for searching applicable credential records. + """Request handler for searching applicable credential records. Args: request: aiohttp request object @@ -804,8 +798,7 @@ async def retrieve_uri_list_from_schema_filter( @request_schema(V20PresProposalRequestSchema()) @response_schema(V20PresExRecordSchema(), 200, description="") async def present_proof_send_proposal(request: web.BaseRequest): - """ - Request handler for sending a presentation proposal. + """Request handler for sending a presentation proposal. Args: request: aiohttp request object @@ -887,8 +880,7 @@ async def present_proof_send_proposal(request: web.BaseRequest): @request_schema(V20PresCreateRequestRequestSchema()) @response_schema(V20PresExRecordSchema(), 200, description="") async def present_proof_create_request(request: web.BaseRequest): - """ - Request handler for creating a free presentation request. + """Request handler for creating a free presentation request. The presentation request will not be bound to any proposal or existing connection. @@ -964,8 +956,7 @@ async def present_proof_create_request(request: web.BaseRequest): @request_schema(V20PresSendRequestRequestSchema()) @response_schema(V20PresExRecordSchema(), 200, description="") async def present_proof_send_free_request(request: web.BaseRequest): - """ - Request handler for sending a presentation request free from any proposal. + """Request handler for sending a presentation request free from any proposal. Args: request: aiohttp request object @@ -1048,8 +1039,7 @@ async def present_proof_send_free_request(request: web.BaseRequest): @request_schema(V20PresentationSendRequestToProposalSchema()) @response_schema(V20PresExRecordSchema(), 200, description="") async def present_proof_send_bound_request(request: web.BaseRequest): - """ - Request handler for sending a presentation request bound to a proposal. + """Request handler for sending a presentation request bound to a proposal. Args: request: aiohttp request object @@ -1139,8 +1129,7 @@ async def present_proof_send_bound_request(request: web.BaseRequest): @request_schema(V20PresSpecByFormatRequestSchema()) @response_schema(V20PresExRecordSchema(), description="") async def present_proof_send_presentation(request: web.BaseRequest): - """ - Request handler for sending a presentation. + """Request handler for sending a presentation. Args: request: aiohttp request object @@ -1252,8 +1241,7 @@ async def present_proof_send_presentation(request: web.BaseRequest): @match_info_schema(V20PresExIdMatchInfoSchema()) @response_schema(V20PresExRecordSchema(), description="") async def present_proof_verify_presentation(request: web.BaseRequest): - """ - Request handler for verifying a presentation request. + """Request handler for verifying a presentation request. Args: request: aiohttp request object @@ -1321,8 +1309,7 @@ async def present_proof_verify_presentation(request: web.BaseRequest): @request_schema(V20PresProblemReportRequestSchema()) @response_schema(V20PresentProofModuleResponseSchema(), 200, description="") async def present_proof_problem_report(request: web.BaseRequest): - """ - Request handler for sending problem report. + """Request handler for sending problem report. Args: request: aiohttp request object @@ -1360,8 +1347,7 @@ async def present_proof_problem_report(request: web.BaseRequest): @match_info_schema(V20PresExIdMatchInfoSchema()) @response_schema(V20PresentProofModuleResponseSchema(), description="") async def present_proof_remove(request: web.BaseRequest): - """ - Request handler for removing a presentation exchange record. + """Request handler for removing a presentation exchange record. Args: request: aiohttp request object diff --git a/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py b/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py index 007af80786..51da3c6450 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py @@ -31,7 +31,6 @@ from ..formats.dif.handler import DIFPresFormatHandler from ..formats.dif.tests.test_handler import ( DIF_PRES_REQUEST_B as DIF_PRES_REQ, - DIF_PRES_REQUEST_A as DIF_PRES_REQ_ALT, DIF_PRES, ) from ..formats.indy import handler as test_indy_handler @@ -544,7 +543,7 @@ async def test_create_exchange_for_proposal(self): assert px_rec.initiator == V20PresExRecord.INITIATOR_SELF assert px_rec.role == V20PresExRecord.ROLE_PROVER assert px_rec.state == V20PresExRecord.STATE_PROPOSAL_SENT - assert px_rec.auto_remove == True + assert px_rec.auto_remove is True async def test_receive_proposal(self): connection_record = async_mock.MagicMock(connection_id=CONN_ID) @@ -762,7 +761,7 @@ async def test_create_exchange_for_request(self): assert px_rec.initiator == V20PresExRecord.INITIATOR_SELF assert px_rec.role == V20PresExRecord.ROLE_VERIFIER assert px_rec.state == V20PresExRecord.STATE_REQUEST_SENT - assert px_rec.auto_remove == True + assert px_rec.auto_remove is True async def test_receive_pres_request(self): px_rec_in = V20PresExRecord() diff --git a/aries_cloudagent/protocols/problem_report/v1_0/handler.py b/aries_cloudagent/protocols/problem_report/v1_0/handler.py index 66a470f7f6..99e1c1d179 100644 --- a/aries_cloudagent/protocols/problem_report/v1_0/handler.py +++ b/aries_cloudagent/protocols/problem_report/v1_0/handler.py @@ -13,8 +13,7 @@ class ProblemReportHandler(BaseHandler): """Problem report handler class.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle problem report message. + """Handle problem report message. Args: context: Request context diff --git a/aries_cloudagent/protocols/problem_report/v1_0/message.py b/aries_cloudagent/protocols/problem_report/v1_0/message.py index 594ca4d243..2c21f4c0aa 100644 --- a/aries_cloudagent/protocols/problem_report/v1_0/message.py +++ b/aries_cloudagent/protocols/problem_report/v1_0/message.py @@ -35,8 +35,7 @@ def __init__( escalation_uri: str = None, **kwargs, ): - """ - Initialize a ProblemReport message instance. + """Initialize a ProblemReport message instance. Args: description: Human-readable, localized string(s) explaining the problem @@ -158,8 +157,7 @@ class Meta: @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields. + """Validate schema fields. Args: data: The data to validate diff --git a/aries_cloudagent/protocols/problem_report/v1_0/tests/test_handler.py b/aries_cloudagent/protocols/problem_report/v1_0/tests/test_handler.py index a022ee4b85..85d35137d4 100644 --- a/aries_cloudagent/protocols/problem_report/v1_0/tests/test_handler.py +++ b/aries_cloudagent/protocols/problem_report/v1_0/tests/test_handler.py @@ -1,7 +1,6 @@ import pytest -from .....core.event_bus import EventBus, MockEventBus, Event -from .....messaging.base_handler import HandlerException +from .....core.event_bus import EventBus, MockEventBus from .....messaging.request_context import RequestContext from .....messaging.responder import MockResponder from .....transport.inbound.receipt import MessageReceipt diff --git a/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/tests/test_revoke_handler.py b/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/tests/test_revoke_handler.py index bdc72d2e26..29c90c0692 100644 --- a/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/tests/test_revoke_handler.py +++ b/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/tests/test_revoke_handler.py @@ -2,7 +2,6 @@ import pytest -from ......config.settings import Settings from ......core.event_bus import EventBus, MockEventBus from ......core.in_memory import InMemoryProfile from ......core.profile import Profile diff --git a/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/tests/test_revoke_handler.py b/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/tests/test_revoke_handler.py index a93a314e23..110b47dee0 100644 --- a/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/tests/test_revoke_handler.py +++ b/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/tests/test_revoke_handler.py @@ -2,7 +2,6 @@ import pytest -from ......config.settings import Settings from ......core.event_bus import EventBus, MockEventBus from ......core.in_memory import InMemoryProfile from ......core.profile import Profile diff --git a/aries_cloudagent/protocols/routing/v1_0/manager.py b/aries_cloudagent/protocols/routing/v1_0/manager.py index d200a30b59..9176b411dd 100644 --- a/aries_cloudagent/protocols/routing/v1_0/manager.py +++ b/aries_cloudagent/protocols/routing/v1_0/manager.py @@ -38,8 +38,7 @@ class RoutingManager: RECORD_TYPE = "forward_route" def __init__(self, profile: Profile): - """ - Initialize a RoutingManager. + """Initialize a RoutingManager. Args: profile: The profile instance for this manager @@ -49,8 +48,7 @@ def __init__(self, profile: Profile): raise RoutingManagerError("Missing profile") async def get_recipient(self, recip_verkey: str) -> RouteRecord: - """ - Resolve the recipient for a verkey. + """Resolve the recipient for a verkey. Args: recip_verkey: The verkey ("to") of the incoming Forward message @@ -90,8 +88,7 @@ async def get_recipient(self, recip_verkey: str) -> RouteRecord: async def get_routes( self, client_connection_id: str = None, tag_filter: dict = None ) -> Sequence[RouteRecord]: - """ - Fetch all routes associated with the current connection. + """Fetch all routes associated with the current connection. Args: client_connection_id: The ID of the connection record @@ -135,8 +132,7 @@ async def create_route_record( recipient_key: str = None, internal_wallet_id: str = None, ) -> RouteRecord: - """ - Create and store a new RouteRecord. + """Create and store a new RouteRecord. Args: client_connection_id: The ID of the connection record @@ -167,8 +163,7 @@ async def create_route_record( async def update_routes( self, client_connection_id: str, updates: Sequence[RouteUpdate] ) -> Sequence[RouteUpdated]: - """ - Update routes associated with the current connection. + """Update routes associated with the current connection. Args: client_connection_id: The ID of the connection record diff --git a/aries_cloudagent/protocols/routing/v1_0/messages/forward.py b/aries_cloudagent/protocols/routing/v1_0/messages/forward.py index bd2c827044..9e822414d3 100644 --- a/aries_cloudagent/protocols/routing/v1_0/messages/forward.py +++ b/aries_cloudagent/protocols/routing/v1_0/messages/forward.py @@ -24,8 +24,7 @@ class Meta: schema_class = "ForwardSchema" def __init__(self, *, to: str = None, msg: Union[dict, str] = None, **kwargs): - """ - Initialize forward message object. + """Initialize forward message object. Args: to (str): Recipient DID diff --git a/aries_cloudagent/protocols/routing/v1_0/messages/route_query_request.py b/aries_cloudagent/protocols/routing/v1_0/messages/route_query_request.py index 5a5c1cbea4..7384d47648 100644 --- a/aries_cloudagent/protocols/routing/v1_0/messages/route_query_request.py +++ b/aries_cloudagent/protocols/routing/v1_0/messages/route_query_request.py @@ -22,8 +22,7 @@ class Meta: schema_class = "RouteQueryRequestSchema" def __init__(self, *, filter: dict = None, paginate: Paginate = None, **kwargs): - """ - Initialize a RouteQueryRequest message instance. + """Initialize a RouteQueryRequest message instance. Args: filter: Filter results according to specific field values diff --git a/aries_cloudagent/protocols/routing/v1_0/messages/route_query_response.py b/aries_cloudagent/protocols/routing/v1_0/messages/route_query_response.py index 9dd7002f23..4145874e25 100644 --- a/aries_cloudagent/protocols/routing/v1_0/messages/route_query_response.py +++ b/aries_cloudagent/protocols/routing/v1_0/messages/route_query_response.py @@ -33,8 +33,7 @@ def __init__( paginated: Paginated = None, **kwargs, ): - """ - Initialize a RouteQueryResponse message instance. + """Initialize a RouteQueryResponse message instance. Args: filter: Filter results according to specific field values diff --git a/aries_cloudagent/protocols/routing/v1_0/messages/route_update_request.py b/aries_cloudagent/protocols/routing/v1_0/messages/route_update_request.py index d1a8c98357..09a5cf633e 100644 --- a/aries_cloudagent/protocols/routing/v1_0/messages/route_update_request.py +++ b/aries_cloudagent/protocols/routing/v1_0/messages/route_update_request.py @@ -26,8 +26,7 @@ class Meta: schema_class = "RouteUpdateRequestSchema" def __init__(self, *, updates: Sequence[RouteUpdate] = None, **kwargs): - """ - Initialize a RouteUpdateRequest message instance. + """Initialize a RouteUpdateRequest message instance. Args: updates: A list of route updates diff --git a/aries_cloudagent/protocols/routing/v1_0/messages/route_update_response.py b/aries_cloudagent/protocols/routing/v1_0/messages/route_update_response.py index be0ba028a6..b7967ab939 100644 --- a/aries_cloudagent/protocols/routing/v1_0/messages/route_update_response.py +++ b/aries_cloudagent/protocols/routing/v1_0/messages/route_update_response.py @@ -26,8 +26,7 @@ class Meta: schema_class = "RouteUpdateResponseSchema" def __init__(self, *, updated: Sequence[RouteUpdated] = None, **kwargs): - """ - Initialize a RouteUpdateResponse message instance. + """Initialize a RouteUpdateResponse message instance. Args: updated: A list of route updates diff --git a/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_query_request.py b/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_query_request.py index a617611455..862750df29 100644 --- a/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_query_request.py +++ b/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_query_request.py @@ -3,7 +3,7 @@ from .....didcomm_prefix import DIDCommPrefix from ...message_types import PROTOCOL_PACKAGE, ROUTE_QUERY_REQUEST -from ...models.paginate import Paginate, PaginateSchema +from ...models.paginate import Paginate from ..route_query_request import RouteQueryRequest diff --git a/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_query_response.py b/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_query_response.py index a164934e10..3907ff60cf 100644 --- a/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_query_response.py +++ b/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_query_response.py @@ -3,7 +3,7 @@ from .....didcomm_prefix import DIDCommPrefix from ...message_types import PROTOCOL_PACKAGE, ROUTE_QUERY_RESPONSE -from ...models.paginated import Paginated, PaginatedSchema +from ...models.paginated import Paginated from ...models.route_record import RouteRecord from ..route_query_response import RouteQueryResponse diff --git a/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_update_request.py b/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_update_request.py index 8ce6a520e1..83ea4e6052 100644 --- a/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_update_request.py +++ b/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_update_request.py @@ -3,7 +3,7 @@ from .....didcomm_prefix import DIDCommPrefix from ...message_types import PROTOCOL_PACKAGE, ROUTE_UPDATE_REQUEST -from ...models.route_update import RouteUpdate, RouteUpdateSchema +from ...models.route_update import RouteUpdate from ..route_update_request import RouteUpdateRequest diff --git a/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_update_response.py b/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_update_response.py index 3d42d216bf..fdfb62e520 100644 --- a/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_update_response.py +++ b/aries_cloudagent/protocols/routing/v1_0/messages/tests/test_route_update_response.py @@ -3,7 +3,7 @@ from .....didcomm_prefix import DIDCommPrefix from ...message_types import PROTOCOL_PACKAGE, ROUTE_UPDATE_RESPONSE -from ...models.route_updated import RouteUpdated, RouteUpdatedSchema +from ...models.route_updated import RouteUpdated from ..route_update_response import RouteUpdateResponse diff --git a/aries_cloudagent/protocols/routing/v1_0/models/paginate.py b/aries_cloudagent/protocols/routing/v1_0/models/paginate.py index a7f1db8758..4a6b6f6d8a 100644 --- a/aries_cloudagent/protocols/routing/v1_0/models/paginate.py +++ b/aries_cloudagent/protocols/routing/v1_0/models/paginate.py @@ -14,8 +14,7 @@ class Meta: schema_class = "PaginateSchema" def __init__(self, *, limit: int = None, offset: int = None, **kwargs): - """ - Initialize a Paginate instance. + """Initialize a Paginate instance. Args: limit: Limit the number of requested records diff --git a/aries_cloudagent/protocols/routing/v1_0/models/paginated.py b/aries_cloudagent/protocols/routing/v1_0/models/paginated.py index 11d586f20e..8a91dc587c 100644 --- a/aries_cloudagent/protocols/routing/v1_0/models/paginated.py +++ b/aries_cloudagent/protocols/routing/v1_0/models/paginated.py @@ -22,8 +22,7 @@ def __init__( total: int = None, **kwargs ): - """ - Initialize a Paginated instance. + """Initialize a Paginated instance. Args: start: The first record offset diff --git a/aries_cloudagent/protocols/routing/v1_0/models/route_query_result.py b/aries_cloudagent/protocols/routing/v1_0/models/route_query_result.py index cc7ad92c78..b42428fc01 100644 --- a/aries_cloudagent/protocols/routing/v1_0/models/route_query_result.py +++ b/aries_cloudagent/protocols/routing/v1_0/models/route_query_result.py @@ -14,8 +14,7 @@ class Meta: schema_class = "RouteQueryResultSchema" def __init__(self, *, recipient_key: str = None, **kwargs): - """ - Initialize a RouteQueryResult instance. + """Initialize a RouteQueryResult instance. Args: recipient_key: The recipient verkey of the route diff --git a/aries_cloudagent/protocols/routing/v1_0/models/route_record.py b/aries_cloudagent/protocols/routing/v1_0/models/route_record.py index e750cd15eb..94545e8d70 100644 --- a/aries_cloudagent/protocols/routing/v1_0/models/route_record.py +++ b/aries_cloudagent/protocols/routing/v1_0/models/route_record.py @@ -125,8 +125,7 @@ class Meta: @validates_schema def validate_fields(self, data, **kwargs): - """ - Validate schema fields. + """Validate schema fields. Args: data: The data to validate diff --git a/aries_cloudagent/protocols/routing/v1_0/models/route_update.py b/aries_cloudagent/protocols/routing/v1_0/models/route_update.py index ecd2d14c25..4afa7773a4 100644 --- a/aries_cloudagent/protocols/routing/v1_0/models/route_update.py +++ b/aries_cloudagent/protocols/routing/v1_0/models/route_update.py @@ -17,8 +17,7 @@ class Meta: ACTION_DELETE = "delete" def __init__(self, *, recipient_key: str = None, action: str = None, **kwargs): - """ - Initialize a RouteUpdate instance. + """Initialize a RouteUpdate instance. Args: recipient_key: The recipient verkey of the route diff --git a/aries_cloudagent/protocols/routing/v1_0/models/route_updated.py b/aries_cloudagent/protocols/routing/v1_0/models/route_updated.py index c86168bf68..b38ab8cc0e 100644 --- a/aries_cloudagent/protocols/routing/v1_0/models/route_updated.py +++ b/aries_cloudagent/protocols/routing/v1_0/models/route_updated.py @@ -26,8 +26,7 @@ def __init__( result: str = None, **kwargs ): - """ - Initialize a RouteUpdated instance. + """Initialize a RouteUpdated instance. Args: recipient_key: The recipient verkey of the route diff --git a/aries_cloudagent/protocols/routing/v1_0/tests/test_routing_manager.py b/aries_cloudagent/protocols/routing/v1_0/tests/test_routing_manager.py index 52c6bb693f..b8e9e577e4 100644 --- a/aries_cloudagent/protocols/routing/v1_0/tests/test_routing_manager.py +++ b/aries_cloudagent/protocols/routing/v1_0/tests/test_routing_manager.py @@ -9,7 +9,6 @@ StorageError, StorageNotFoundError, ) -from .....storage.in_memory import InMemoryStorage from .....transport.inbound.receipt import MessageReceipt from ..manager import RoutingManager, RoutingManagerError, RouteNotFoundError diff --git a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py index 11817d59e4..7963109e43 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py +++ b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py @@ -14,8 +14,7 @@ class PingHandler(BaseHandler): """Ping handler class.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle ping message. + """Handle ping message. Args: context: Request context diff --git a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py index 18de38ad56..c66c68158a 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py +++ b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py @@ -13,8 +13,7 @@ class PingResponseHandler(BaseHandler): """Ping response handler class.""" async def handle(self, context: RequestContext, responder: BaseResponder): - """ - Handle ping response message. + """Handle ping response message. Args: context: Request context diff --git a/aries_cloudagent/protocols/trustping/v1_0/handlers/tests/test_ping_handler.py b/aries_cloudagent/protocols/trustping/v1_0/handlers/tests/test_ping_handler.py index 9366908fb0..ccf75fdfa7 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/handlers/tests/test_ping_handler.py +++ b/aries_cloudagent/protocols/trustping/v1_0/handlers/tests/test_ping_handler.py @@ -1,6 +1,5 @@ import pytest -from ......messaging.base_handler import HandlerException from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder from ......transport.inbound.receipt import MessageReceipt diff --git a/aries_cloudagent/protocols/trustping/v1_0/handlers/tests/test_ping_response_handler.py b/aries_cloudagent/protocols/trustping/v1_0/handlers/tests/test_ping_response_handler.py index f5b7cd13e4..5cb29c6f7b 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/handlers/tests/test_ping_response_handler.py +++ b/aries_cloudagent/protocols/trustping/v1_0/handlers/tests/test_ping_response_handler.py @@ -1,6 +1,5 @@ import pytest -from ......messaging.base_handler import HandlerException from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder from ......transport.inbound.receipt import MessageReceipt diff --git a/aries_cloudagent/protocols/trustping/v1_0/messages/ping.py b/aries_cloudagent/protocols/trustping/v1_0/messages/ping.py index 0353baf6e9..7685b7b1b6 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/messages/ping.py +++ b/aries_cloudagent/protocols/trustping/v1_0/messages/ping.py @@ -21,8 +21,7 @@ class Meta: def __init__( self, *, response_requested: bool = True, comment: str = None, **kwargs ): - """ - Initialize a Ping message instance. + """Initialize a Ping message instance. Args: response_requested: A flag indicating that a response is requested diff --git a/aries_cloudagent/protocols/trustping/v1_0/messages/ping_response.py b/aries_cloudagent/protocols/trustping/v1_0/messages/ping_response.py index 9297bd5a0a..9135ba4b84 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/messages/ping_response.py +++ b/aries_cloudagent/protocols/trustping/v1_0/messages/ping_response.py @@ -19,8 +19,7 @@ class Meta: schema_class = "PingResponseSchema" def __init__(self, *, comment: str = None, **kwargs): - """ - Initialize a PingResponse message instance. + """Initialize a PingResponse message instance. Args: comment: An optional comment string to include in the message diff --git a/aries_cloudagent/protocols/trustping/v1_0/routes.py b/aries_cloudagent/protocols/trustping/v1_0/routes.py index e1e4cbd488..f8a41fd412 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/routes.py +++ b/aries_cloudagent/protocols/trustping/v1_0/routes.py @@ -46,8 +46,7 @@ class PingConnIdMatchInfoSchema(OpenAPISchema): @request_schema(PingRequestSchema()) @response_schema(PingRequestResponseSchema(), 200, description="") async def connections_send_ping(request: web.BaseRequest): - """ - Request handler for sending a trust ping to a connection. + """Request handler for sending a trust ping to a connection. Args: request: aiohttp request object diff --git a/aries_cloudagent/resolver/default/web.py b/aries_cloudagent/resolver/default/web.py index df2d99e6cc..15aad96e6a 100644 --- a/aries_cloudagent/resolver/default/web.py +++ b/aries_cloudagent/resolver/default/web.py @@ -36,8 +36,7 @@ def supported_did_regex(self) -> Pattern: return DIDWeb.PATTERN def __transform_to_url(self, did): - """ - Transform did to url. + """Transform did to url. according to https://w3c-ccg.github.io/did-method-web/#read-resolve diff --git a/aries_cloudagent/resolver/did_resolver.py b/aries_cloudagent/resolver/did_resolver.py index a9bc4d4c0a..1ed7e55868 100644 --- a/aries_cloudagent/resolver/did_resolver.py +++ b/aries_cloudagent/resolver/did_resolver.py @@ -1,5 +1,4 @@ -""" -the did resolver. +"""the did resolver. responsible for keeping track of all resolvers. more importantly retrieving did's from different sources provided by the method type. diff --git a/aries_cloudagent/resolver/routes.py b/aries_cloudagent/resolver/routes.py index fac9ae56d6..fd34699ff4 100644 --- a/aries_cloudagent/resolver/routes.py +++ b/aries_cloudagent/resolver/routes.py @@ -1,41 +1,40 @@ -""" -Resolve did document admin routes. +"""Resolve did document admin routes. - "/resolver/resolve/{did}": { - "get": { - "responses": { - "200": { - "schema": { - "$ref": "#/definitions/DIDDoc" +"/resolver/resolve/{did}": { +"get": { +"responses": { +"200": { +"schema": { +"$ref": "#/definitions/DIDDoc" - }, - "description": null +}, +"description": null - } +} - }, - "parameters": [ +}, +"parameters": [ - { - "in": "path", - "name": "did", - "required": true, - "type": "string", - "pattern": "did:([a-z]+):((?:[a-zA-Z0-9._-]*:)*[a-zA-Z0-9._-]+)", - "description": "decentralize identifier(DID)", - "example": "did:ted:WgWxqztrNooG92RXvxSTWv" +{ +"in": "path", +"name": "did", +"required": true, +"type": "string", +"pattern": "did:([a-z]+):((?:[a-zA-Z0-9._-]*:)*[a-zA-Z0-9._-]+)", +"description": "decentralize identifier(DID)", +"example": "did:ted:WgWxqztrNooG92RXvxSTWv" - } +} - ], +], - "tags": [ "resolver" ], - "summary": "Retrieve doc for requested did", - "produces": [ "application/json" ] +"tags": [ "resolver" ], +"summary": "Retrieve doc for requested did", +"produces": [ "application/json" ] - } +} - } +} """ diff --git a/aries_cloudagent/resolver/tests/test_did_resolver.py b/aries_cloudagent/resolver/tests/test_did_resolver.py index 328dfbdb71..26d984a12b 100644 --- a/aries_cloudagent/resolver/tests/test_did_resolver.py +++ b/aries_cloudagent/resolver/tests/test_did_resolver.py @@ -6,7 +6,6 @@ import pytest -from asynctest import mock as async_mock from pydid import DID, DIDDocument, VerificationMethod, BasicDIDDocument from ...core.in_memory import InMemoryProfile diff --git a/aries_cloudagent/revocation/indy.py b/aries_cloudagent/revocation/indy.py index 89333aa75e..622ef3f583 100644 --- a/aries_cloudagent/revocation/indy.py +++ b/aries_cloudagent/revocation/indy.py @@ -204,8 +204,7 @@ async def list_issuer_registries(self) -> Sequence[IssuerRevRegRecord]: async def get_issuer_rev_reg_delta( self, rev_reg_id: str, fro: int = None, to: int = None ) -> dict: - """ - Check ledger for revocation status for a given revocation registry. + """Check ledger for revocation status for a given revocation registry. Args: rev_reg_id: ID of the revocation registry diff --git a/aries_cloudagent/revocation/manager.py b/aries_cloudagent/revocation/manager.py index 0a34f98493..3fc8b81741 100644 --- a/aries_cloudagent/revocation/manager.py +++ b/aries_cloudagent/revocation/manager.py @@ -31,8 +31,7 @@ class RevocationManager: """Class for managing revocation operations.""" def __init__(self, profile: Profile): - """ - Initialize a RevocationManager. + """Initialize a RevocationManager. Args: context: The context for this revocation manager @@ -50,8 +49,7 @@ async def revoke_credential_by_cred_ex_id( connection_id: str = None, comment: str = None, ): - """ - Revoke a credential by its credential exchange identifier at issue. + """Revoke a credential by its credential exchange identifier at issue. Optionally, publish the corresponding revocation registry delta to the ledger. @@ -95,8 +93,7 @@ async def revoke_credential( connection_id: str = None, comment: str = None, ): - """ - Revoke a credential. + """Revoke a credential. Optionally, publish the corresponding revocation registry delta to the ledger. @@ -166,8 +163,7 @@ async def update_rev_reg_revoked_state( rev_reg_record: IssuerRevRegRecord, genesis_transactions: dict, ) -> Tuple[dict, dict, dict]: - """ - Request handler to fix ledger entry of credentials revoked against registry. + """Request handler to fix ledger entry of credentials revoked against registry. Args: rev_reg_id: revocation registry id @@ -187,8 +183,7 @@ async def publish_pending_revocations( self, rrid2crid: Mapping[Text, Sequence[Text]] = None, ) -> Mapping[Text, Sequence[Text]]: - """ - Publish pending revocations to the ledger. + """Publish pending revocations to the ledger. Args: rrid2crid: Mapping from revocation registry identifiers to all credential @@ -256,8 +251,7 @@ async def publish_pending_revocations( async def clear_pending_revocations( self, purge: Mapping[Text, Sequence[Text]] = None ) -> Mapping[Text, Sequence[Text]]: - """ - Clear pending revocation publications. + """Clear pending revocation publications. Args: purge: Mapping from revocation registry identifiers to all credential @@ -304,8 +298,7 @@ async def clear_pending_revocations( async def set_cred_revoked_state( self, rev_reg_id: str, cred_rev_ids: Sequence[str] ) -> None: - """ - Update credentials state to credential_revoked. + """Update credentials state to credential_revoked. Args: rev_reg_id: revocation registry ID diff --git a/aries_cloudagent/revocation/models/issuer_rev_reg_record.py b/aries_cloudagent/revocation/models/issuer_rev_reg_record.py index 20f295a969..ccb47e63ed 100644 --- a/aries_cloudagent/revocation/models/issuer_rev_reg_record.py +++ b/aries_cloudagent/revocation/models/issuer_rev_reg_record.py @@ -123,7 +123,7 @@ def __init__( self.tails_local_path = tails_local_path self.tails_public_uri = tails_public_uri self.pending_pub = ( - sorted(list(set(pending_pub))) if pending_pub else [] + sorted(set(pending_pub)) if pending_pub else [] ) # order for eq comparison between instances @property diff --git a/aries_cloudagent/revocation/models/tests/test_indy.py b/aries_cloudagent/revocation/models/tests/test_indy.py index 8c02057708..79ddc929c9 100644 --- a/aries_cloudagent/revocation/models/tests/test_indy.py +++ b/aries_cloudagent/revocation/models/tests/test_indy.py @@ -1,9 +1,5 @@ from unittest import TestCase -from asynctest import TestCase as AsyncTestCase -from asynctest import mock as async_mock - -import pytest from ..indy import NonRevocationInterval diff --git a/aries_cloudagent/revocation/models/tests/test_issuer_rev_reg_record.py b/aries_cloudagent/revocation/models/tests/test_issuer_rev_reg_record.py index 8154884aeb..80d15592ea 100644 --- a/aries_cloudagent/revocation/models/tests/test_issuer_rev_reg_record.py +++ b/aries_cloudagent/revocation/models/tests/test_issuer_rev_reg_record.py @@ -6,7 +6,6 @@ from ....core.in_memory import InMemoryProfile from ....indy.issuer import IndyIssuer, IndyIssuerError -from ....indy.models.revocation import IndyRevRegDef from ....indy.util import indy_client_dir from ....ledger.base import BaseLedger from ....tails.base import BaseTailsServer diff --git a/aries_cloudagent/revocation/models/tests/test_revocation_registry.py b/aries_cloudagent/revocation/models/tests/test_revocation_registry.py index 5cc277ec60..ddba588969 100644 --- a/aries_cloudagent/revocation/models/tests/test_revocation_registry.py +++ b/aries_cloudagent/revocation/models/tests/test_revocation_registry.py @@ -1,7 +1,3 @@ -import json - -import pytest - from asynctest import TestCase as AsyncTestCase, mock as async_mock from copy import deepcopy from pathlib import Path diff --git a/aries_cloudagent/revocation/routes.py b/aries_cloudagent/revocation/routes.py index 96cf06060b..f00e928798 100644 --- a/aries_cloudagent/revocation/routes.py +++ b/aries_cloudagent/revocation/routes.py @@ -506,8 +506,7 @@ class RevRegConnIdMatchInfoSchema(OpenAPISchema): @request_schema(RevokeRequestSchema()) @response_schema(RevocationModuleResponseSchema(), description="") async def revoke(request: web.BaseRequest): - """ - Request handler for storing a credential revocation. + """Request handler for storing a credential revocation. Args: request: aiohttp request object @@ -557,8 +556,7 @@ async def revoke(request: web.BaseRequest): @request_schema(PublishRevocationsSchema()) @response_schema(TxnOrPublishRevocationsResultSchema(), 200, description="") async def publish_revocations(request: web.BaseRequest): - """ - Request handler for publishing pending revocations to the ledger. + """Request handler for publishing pending revocations to the ledger. Args: request: aiohttp request object @@ -587,8 +585,7 @@ async def publish_revocations(request: web.BaseRequest): @request_schema(ClearPendingRevocationsRequestSchema()) @response_schema(PublishRevocationsSchema(), 200, description="") async def clear_pending_revocations(request: web.BaseRequest): - """ - Request handler for clearing pending revocations. + """Request handler for clearing pending revocations. Args: request: aiohttp request object @@ -614,8 +611,7 @@ async def clear_pending_revocations(request: web.BaseRequest): @match_info_schema(RevocationCredDefIdMatchInfoSchema()) @response_schema(RevRegsCreatedSchema(), 200, description="") async def rotate_rev_reg(request: web.BaseRequest): - """ - Request handler to rotate the active revocation registries for cred. def. + """Request handler to rotate the active revocation registries for cred. def. Args: request: aiohttp request object @@ -644,8 +640,7 @@ async def rotate_rev_reg(request: web.BaseRequest): @request_schema(RevRegCreateRequestSchema()) @response_schema(RevRegResultSchema(), 200, description="") async def create_rev_reg(request: web.BaseRequest): - """ - Request handler to create a new revocation registry. + """Request handler to create a new revocation registry. Args: request: aiohttp request object @@ -695,8 +690,7 @@ async def create_rev_reg(request: web.BaseRequest): @querystring_schema(RevRegsCreatedQueryStringSchema()) @response_schema(RevRegsCreatedSchema(), 200, description="") async def rev_regs_created(request: web.BaseRequest): - """ - Request handler to get revocation registries that current agent created. + """Request handler to get revocation registries that current agent created. Args: request: aiohttp request object @@ -707,9 +701,7 @@ async def rev_regs_created(request: web.BaseRequest): """ context: AdminRequestContext = request["context"] - search_tags = [ - tag for tag in vars(RevRegsCreatedQueryStringSchema)["_declared_fields"] - ] + search_tags = list(vars(RevRegsCreatedQueryStringSchema)["_declared_fields"]) tag_filter = { tag: request.query[tag] for tag in search_tags if tag in request.query } @@ -736,8 +728,7 @@ async def rev_regs_created(request: web.BaseRequest): @match_info_schema(RevRegIdMatchInfoSchema()) @response_schema(RevRegResultSchema(), 200, description="") async def get_rev_reg(request: web.BaseRequest): - """ - Request handler to get a revocation registry by rev reg id. + """Request handler to get a revocation registry by rev reg id. Args: request: aiohttp request object @@ -766,8 +757,7 @@ async def get_rev_reg(request: web.BaseRequest): @match_info_schema(RevRegIdMatchInfoSchema()) @response_schema(RevRegIssuedResultSchema(), 200, description="") async def get_rev_reg_issued_count(request: web.BaseRequest): - """ - Request handler to get number of credentials issued against revocation registry. + """Request handler to get number of credentials issued against revocation registry. Args: request: aiohttp request object @@ -799,8 +789,7 @@ async def get_rev_reg_issued_count(request: web.BaseRequest): @match_info_schema(RevRegIdMatchInfoSchema()) @response_schema(CredRevRecordDetailsResultSchema(), 200, description="") async def get_rev_reg_issued(request: web.BaseRequest): - """ - Request handler to get credentials issued against revocation registry. + """Request handler to get credentials issued against revocation registry. Args: request: aiohttp request object @@ -834,8 +823,7 @@ async def get_rev_reg_issued(request: web.BaseRequest): @match_info_schema(RevRegIdMatchInfoSchema()) @response_schema(CredRevIndyRecordsResultSchema(), 200, description="") async def get_rev_reg_indy_recs(request: web.BaseRequest): - """ - Request handler to get details of revoked credentials from ledger. + """Request handler to get details of revoked credentials from ledger. Args: request: aiohttp request object @@ -866,8 +854,7 @@ async def get_rev_reg_indy_recs(request: web.BaseRequest): @querystring_schema(RevRegUpdateRequestMatchInfoSchema()) @response_schema(RevRegWalletUpdatedResultSchema(), 200, description="") async def update_rev_reg_revoked_state(request: web.BaseRequest): - """ - Request handler to fix ledger entry of credentials revoked against registry. + """Request handler to fix ledger entry of credentials revoked against registry. Args: request: aiohttp request object @@ -955,8 +942,7 @@ async def update_rev_reg_revoked_state(request: web.BaseRequest): @querystring_schema(CredRevRecordQueryStringSchema()) @response_schema(CredRevRecordResultSchema(), 200, description="") async def get_cred_rev_record(request: web.BaseRequest): - """ - Request handler to get credential revocation record. + """Request handler to get credential revocation record. Args: request: aiohttp request object @@ -994,8 +980,7 @@ async def get_cred_rev_record(request: web.BaseRequest): @match_info_schema(RevocationCredDefIdMatchInfoSchema()) @response_schema(RevRegResultSchema(), 200, description="") async def get_active_rev_reg(request: web.BaseRequest): - """ - Request handler to get current active revocation registry by cred def id. + """Request handler to get current active revocation registry by cred def id. Args: request: aiohttp request object @@ -1025,8 +1010,7 @@ async def get_active_rev_reg(request: web.BaseRequest): @match_info_schema(RevRegIdMatchInfoSchema()) @response_schema(RevocationModuleResponseSchema, description="tails file") async def get_tails_file(request: web.BaseRequest) -> web.FileResponse: - """ - Request handler to download tails file for revocation registry. + """Request handler to download tails file for revocation registry. Args: request: aiohttp request object @@ -1055,8 +1039,7 @@ async def get_tails_file(request: web.BaseRequest) -> web.FileResponse: @match_info_schema(RevRegIdMatchInfoSchema()) @response_schema(RevocationModuleResponseSchema(), description="") async def upload_tails_file(request: web.BaseRequest): - """ - Request handler to upload local tails file for revocation registry. + """Request handler to upload local tails file for revocation registry. Args: request: aiohttp request object @@ -1091,8 +1074,7 @@ async def upload_tails_file(request: web.BaseRequest): @querystring_schema(RevRegConnIdMatchInfoSchema()) @response_schema(TxnOrRevRegResultSchema(), 200, description="") async def send_rev_reg_def(request: web.BaseRequest): - """ - Request handler to send revocation registry definition by rev reg id to ledger. + """Request handler to send revocation registry definition by rev reg id to ledger. Args: request: aiohttp request object @@ -1210,8 +1192,7 @@ async def send_rev_reg_def(request: web.BaseRequest): @querystring_schema(RevRegConnIdMatchInfoSchema()) @response_schema(RevRegResultSchema(), 200, description="") async def send_rev_reg_entry(request: web.BaseRequest): - """ - Request handler to send rev reg entry by registry id to ledger. + """Request handler to send rev reg entry by registry id to ledger. Args: request: aiohttp request object @@ -1328,8 +1309,7 @@ async def send_rev_reg_entry(request: web.BaseRequest): @request_schema(RevRegUpdateTailsFileUriSchema()) @response_schema(RevRegResultSchema(), 200, description="") async def update_rev_reg(request: web.BaseRequest): - """ - Request handler to update a rev reg's public tails URI by registry id. + """Request handler to update a rev reg's public tails URI by registry id. Args: request: aiohttp request object @@ -1363,8 +1343,7 @@ async def update_rev_reg(request: web.BaseRequest): @querystring_schema(SetRevRegStateQueryStringSchema()) @response_schema(RevRegResultSchema(), 200, description="") async def set_rev_reg_state(request: web.BaseRequest): - """ - Request handler to set a revocation registry state manually. + """Request handler to set a revocation registry state manually. Args: request: aiohttp request object diff --git a/aries_cloudagent/revocation/tests/test_indy.py b/aries_cloudagent/revocation/tests/test_indy.py index 493f7cf651..32c2215dc6 100644 --- a/aries_cloudagent/revocation/tests/test_indy.py +++ b/aries_cloudagent/revocation/tests/test_indy.py @@ -1,5 +1,3 @@ -import pytest - from asynctest import mock as async_mock, TestCase as AsyncTestCase from ...core.in_memory import InMemoryProfile diff --git a/aries_cloudagent/settings/routes.py b/aries_cloudagent/settings/routes.py index ab4cf73034..b5be37258d 100644 --- a/aries_cloudagent/settings/routes.py +++ b/aries_cloudagent/settings/routes.py @@ -88,8 +88,7 @@ def _get_settings_dict( @request_schema(UpdateProfileSettingsSchema()) @response_schema(ProfileSettingsSchema(), 200, description="") async def update_profile_settings(request: web.BaseRequest): - """ - Request handler for updating setting associated with profile. + """Request handler for updating setting associated with profile. Args: request: aiohttp request object @@ -130,8 +129,7 @@ async def update_profile_settings(request: web.BaseRequest): ) @response_schema(ProfileSettingsSchema(), 200, description="") async def get_profile_settings(request: web.BaseRequest): - """ - Request handler for getting setting associated with profile. + """Request handler for getting setting associated with profile. Args: request: aiohttp request object diff --git a/aries_cloudagent/storage/askar.py b/aries_cloudagent/storage/askar.py index 2a48cfb2a7..bab4cc4ff7 100644 --- a/aries_cloudagent/storage/askar.py +++ b/aries_cloudagent/storage/askar.py @@ -26,8 +26,7 @@ class AskarStorage(BaseStorage): """Aries-Askar Non-Secrets interface.""" def __init__(self, session: AskarProfileSession): - """ - Initialize an `AskarStorage` instance. + """Initialize an `AskarStorage` instance. Args: session: The Askar profile session to use @@ -40,8 +39,7 @@ def session(self) -> Session: return self._session async def add_record(self, record: StorageRecord): - """ - Add a new record to the store. + """Add a new record to the store. Args: record: `StorageRecord` to be stored @@ -62,8 +60,7 @@ async def add_record(self, record: StorageRecord): async def get_record( self, record_type: str, record_id: str, options: Mapping = None ) -> StorageRecord: - """ - Fetch a record from the store by type and ID. + """Fetch a record from the store by type and ID. Args: record_type: The record type @@ -101,8 +98,7 @@ async def get_record( ) async def update_record(self, record: StorageRecord, value: str, tags: Mapping): - """ - Update an existing stored record's value. + """Update an existing stored record's value. Args: record: `StorageRecord` to update @@ -123,8 +119,7 @@ async def update_record(self, record: StorageRecord, value: str, tags: Mapping): raise StorageError("Error when updating storage record value") from err async def delete_record(self, record: StorageRecord): - """ - Delete a record. + """Delete a record. Args: record: `StorageRecord` to delete @@ -148,8 +143,7 @@ async def delete_record(self, record: StorageRecord): async def find_record( self, type_filter: str, tag_query: Mapping, options: Mapping = None ) -> StorageRecord: - """ - Find a record using a unique tag filter. + """Find a record using a unique tag filter. Args: type_filter: Filter string @@ -210,8 +204,7 @@ class AskarStorageSearch(BaseStorageSearch): """Active instance of an Askar storage search query.""" def __init__(self, profile: AskarProfile): - """ - Initialize an `AskarStorageSearch` instance. + """Initialize an `AskarStorageSearch` instance. Args: profile: The Askar profile instance to use @@ -225,8 +218,7 @@ def search_records( page_size: int = None, options: Mapping = None, ) -> "AskarStorageSearchSession": - """ - Search stored records. + """Search stored records. Args: type_filter: Filter string @@ -254,8 +246,7 @@ def __init__( page_size: int = None, options: Mapping = None, ): - """ - Initialize a `AskarStorageSearchSession` instance. + """Initialize a `AskarStorageSearchSession` instance. Args: profile: Askar profile instance to search @@ -273,8 +264,7 @@ def __init__( @property def opened(self) -> bool: - """ - Accessor for open state. + """Accessor for open state. Returns: True if opened, else False @@ -284,8 +274,7 @@ def opened(self) -> bool: @property def handle(self): - """ - Accessor for search handle. + """Accessor for search handle. Returns: The handle @@ -319,8 +308,7 @@ async def __anext__(self): ) async def fetch(self, max_count: int = None) -> Sequence[StorageRecord]: - """ - Fetch the next list of results from the store. + """Fetch the next list of results from the store. Args: max_count: Max number of records to return diff --git a/aries_cloudagent/storage/base.py b/aries_cloudagent/storage/base.py index 3e2006a98c..8eb798ffbf 100644 --- a/aries_cloudagent/storage/base.py +++ b/aries_cloudagent/storage/base.py @@ -27,8 +27,7 @@ class BaseStorage(ABC): @abstractmethod async def add_record(self, record: StorageRecord): - """ - Add a new record to the store. + """Add a new record to the store. Args: record: `StorageRecord` to be stored @@ -39,8 +38,7 @@ async def add_record(self, record: StorageRecord): async def get_record( self, record_type: str, record_id: str, options: Mapping = None ) -> StorageRecord: - """ - Fetch a record from the store by type and ID. + """Fetch a record from the store by type and ID. Args: record_type: The record type @@ -54,8 +52,7 @@ async def get_record( @abstractmethod async def update_record(self, record: StorageRecord, value: str, tags: Mapping): - """ - Update an existing stored record's value and tags. + """Update an existing stored record's value and tags. Args: record: `StorageRecord` to update @@ -66,8 +63,7 @@ async def update_record(self, record: StorageRecord, value: str, tags: Mapping): @abstractmethod async def delete_record(self, record: StorageRecord): - """ - Delete an existing record. + """Delete an existing record. Args: record: `StorageRecord` to delete @@ -77,8 +73,7 @@ async def delete_record(self, record: StorageRecord): async def find_record( self, type_filter: str, tag_query: Mapping = None, options: Mapping = None ) -> StorageRecord: - """ - Find a record using a unique tag filter. + """Find a record using a unique tag filter. Args: type_filter: Filter string @@ -123,8 +118,7 @@ def search_records( page_size: int = None, options: Mapping = None, ) -> "BaseStorageSearchSession": - """ - Create a new record query. + """Create a new record query. Args: type_filter: Filter string @@ -147,8 +141,7 @@ class BaseStorageSearchSession(ABC): @abstractmethod async def fetch(self, max_count: int = None) -> Sequence[StorageRecord]: - """ - Fetch the next list of results from the store. + """Fetch the next list of results from the store. Args: max_count: Max number of records to return. If not provided, diff --git a/aries_cloudagent/storage/in_memory.py b/aries_cloudagent/storage/in_memory.py index 296858f1d2..84a9ed241f 100644 --- a/aries_cloudagent/storage/in_memory.py +++ b/aries_cloudagent/storage/in_memory.py @@ -23,8 +23,7 @@ class InMemoryStorage(BaseStorage, BaseStorageSearch): """Basic in-memory storage class.""" def __init__(self, profile: InMemoryProfile): - """ - Initialize a `InMemoryStorage` instance. + """Initialize a `InMemoryStorage` instance. Args: profile: The in-memory profile instance @@ -33,8 +32,7 @@ def __init__(self, profile: InMemoryProfile): self.profile = profile async def add_record(self, record: StorageRecord): - """ - Add a new record to the store. + """Add a new record to the store. Args: record: `StorageRecord` to be stored @@ -52,8 +50,7 @@ async def add_record(self, record: StorageRecord): async def get_record( self, record_type: str, record_id: str, options: Mapping = None ) -> StorageRecord: - """ - Fetch a record from the store by type and ID. + """Fetch a record from the store by type and ID. Args: record_type: The record type @@ -73,8 +70,7 @@ async def get_record( raise StorageNotFoundError("Record not found: {}".format(record_id)) async def update_record(self, record: StorageRecord, value: str, tags: Mapping): - """ - Update an existing stored record's value. + """Update an existing stored record's value. Args: record: `StorageRecord` to update @@ -92,8 +88,7 @@ async def update_record(self, record: StorageRecord, value: str, tags: Mapping): self.profile.records[record.id] = oldrec._replace(value=value, tags=tags) async def delete_record(self, record: StorageRecord): - """ - Delete a record. + """Delete a record. Args: record: `StorageRecord` to delete @@ -140,8 +135,7 @@ def search_records( page_size: int = None, options: Mapping = None, ) -> "InMemoryStorageSearch": - """ - Search stored records. + """Search stored records. Args: type_filter: Filter string @@ -246,8 +240,7 @@ def __init__( page_size: int = None, options: Mapping = None, ): - """ - Initialize a `InMemoryStorageSearch` instance. + """Initialize a `InMemoryStorageSearch` instance. Args: profile: The in-memory profile to search @@ -264,8 +257,7 @@ def __init__( self.type_filter = type_filter async def fetch(self, max_count: int = None) -> Sequence[StorageRecord]: - """ - Fetch the next list of results from the store. + """Fetch the next list of results from the store. Args: max_count: Max number of records to return. If not provided, diff --git a/aries_cloudagent/storage/indy.py b/aries_cloudagent/storage/indy.py index 9a5e37aec8..16bfab6624 100644 --- a/aries_cloudagent/storage/indy.py +++ b/aries_cloudagent/storage/indy.py @@ -31,8 +31,7 @@ class IndySdkStorage(BaseStorage, BaseStorageSearch): """Indy Non-Secrets interface.""" def __init__(self, wallet: IndyOpenWallet): - """ - Initialize an `IndySdkStorage` instance. + """Initialize an `IndySdkStorage` instance. Args: wallet: The indy wallet instance to use @@ -46,8 +45,7 @@ def wallet(self) -> IndyOpenWallet: return self._wallet async def add_record(self, record: StorageRecord): - """ - Add a new record to the store. + """Add a new record to the store. Args: record: `StorageRecord` to be stored @@ -69,8 +67,7 @@ async def add_record(self, record: StorageRecord): async def get_record( self, record_type: str, record_id: str, options: Mapping = None ) -> StorageRecord: - """ - Fetch a record from the store by type and ID. + """Fetch a record from the store by type and ID. Args: record_type: The record type @@ -119,8 +116,7 @@ async def get_record( ) async def update_record(self, record: StorageRecord, value: str, tags: Mapping): - """ - Update an existing stored record's value and tags. + """Update an existing stored record's value and tags. Args: record: `StorageRecord` to update @@ -147,8 +143,7 @@ async def update_record(self, record: StorageRecord, value: str, tags: Mapping): raise StorageError(str(x_indy)) async def delete_record(self, record: StorageRecord): - """ - Delete a record. + """Delete a record. Args: record: `StorageRecord` to delete @@ -203,8 +198,7 @@ def search_records( page_size: int = None, options: Mapping = None, ) -> "IndySdkStorageSearch": - """ - Search stored records. + """Search stored records. Args: type_filter: Filter string @@ -230,8 +224,7 @@ def __init__( page_size: int = None, options: Mapping = None, ): - """ - Initialize a `IndySdkStorageSearch` instance. + """Initialize a `IndySdkStorageSearch` instance. Args: store: `BaseStorage` to search @@ -249,8 +242,7 @@ def __init__( self.type_filter = type_filter async def fetch(self, max_count: int = None) -> Sequence[StorageRecord]: - """ - Fetch the next list of results from the store. + """Fetch the next list of results from the store. Args: max_count: Max number of records to return. If not provided, diff --git a/aries_cloudagent/storage/tests/test_askar_storage.py b/aries_cloudagent/storage/tests/test_askar_storage.py index 4cc013dfae..b1a146a45d 100644 --- a/aries_cloudagent/storage/tests/test_askar_storage.py +++ b/aries_cloudagent/storage/tests/test_askar_storage.py @@ -38,6 +38,10 @@ async def store(): # await profile.close() +# TODO: Ignore "Undefined name `indy`" errors; these tests should be revisited +# ruff: noqa: F821 + + @pytest.mark.askar class TestAskarStorage(test_in_memory_storage.TestInMemoryStorage): """Tests for Askar storage.""" diff --git a/aries_cloudagent/storage/tests/test_storage_record.py b/aries_cloudagent/storage/tests/test_storage_record.py index 52e8a621b2..ca9b54d1f2 100644 --- a/aries_cloudagent/storage/tests/test_storage_record.py +++ b/aries_cloudagent/storage/tests/test_storage_record.py @@ -9,5 +9,5 @@ def test_create(self): assert record.type == record_type assert record.value == record_value - assert record.id and type(record.id) is str + assert record.id and isinstance(record.id, str) assert record.tags == {} diff --git a/aries_cloudagent/storage/vc_holder/askar.py b/aries_cloudagent/storage/vc_holder/askar.py index 15b71a7d0b..2cc8df2ff9 100644 --- a/aries_cloudagent/storage/vc_holder/askar.py +++ b/aries_cloudagent/storage/vc_holder/askar.py @@ -37,8 +37,7 @@ def build_type_or_schema_query(self, uri_list: Sequence[str]) -> dict: return type_or_schema_query async def store_credential(self, cred: VCRecord): - """ - Add a new VC record to the store. + """Add a new VC record to the store. Args: cred: The VCRecord instance to store @@ -51,8 +50,7 @@ async def store_credential(self, cred: VCRecord): await AskarStorage(session).add_record(record) async def retrieve_credential_by_id(self, record_id: str) -> VCRecord: - """ - Fetch a VC record by its record ID. + """Fetch a VC record by its record ID. Raises: StorageNotFoundError: If the record is not found @@ -65,8 +63,7 @@ async def retrieve_credential_by_id(self, record_id: str) -> VCRecord: return storage_to_vc_record(record) async def retrieve_credential_by_given_id(self, given_id: str) -> VCRecord: - """ - Fetch a VC record by its given ID ('id' property). + """Fetch a VC record by its given ID ('id' property). Raises: StorageNotFoundError: If the record is not found @@ -79,8 +76,7 @@ async def retrieve_credential_by_given_id(self, given_id: str) -> VCRecord: return storage_to_vc_record(record) async def delete_credential(self, cred: VCRecord): - """ - Remove a previously-stored VC record. + """Remove a previously-stored VC record. Raises: StorageNotFoundError: If the record is not found @@ -101,8 +97,7 @@ def search_credentials( tag_query: Mapping = None, pd_uri_list: Sequence[str] = None, ) -> "VCRecordSearch": - """ - Start a new VC record search. + """Start a new VC record search. Args: contexts: An inclusive list of JSON-LD contexts to match @@ -168,8 +163,7 @@ async def close(self): await self._search.close() async def fetch(self, max_count: int = None) -> Sequence[VCRecord]: - """ - Fetch the next list of VC records from the store. + """Fetch the next list of VC records from the store. Args: max_count: Max number of records to return. If not provided, diff --git a/aries_cloudagent/storage/vc_holder/base.py b/aries_cloudagent/storage/vc_holder/base.py index c381e5750a..df3a7138c9 100644 --- a/aries_cloudagent/storage/vc_holder/base.py +++ b/aries_cloudagent/storage/vc_holder/base.py @@ -11,8 +11,7 @@ class VCHolder(ABC): @abstractmethod async def store_credential(self, cred: VCRecord): - """ - Add a new VC record to the store. + """Add a new VC record to the store. Args: cred: The VCRecord instance to store @@ -23,8 +22,7 @@ async def store_credential(self, cred: VCRecord): @abstractmethod async def retrieve_credential_by_id(self, record_id: str) -> VCRecord: - """ - Fetch a VC record by its record ID. + """Fetch a VC record by its record ID. Raises: StorageNotFoundError: If the record is not found @@ -33,8 +31,7 @@ async def retrieve_credential_by_id(self, record_id: str) -> VCRecord: @abstractmethod async def retrieve_credential_by_given_id(self, given_id: str) -> VCRecord: - """ - Fetch a VC record by its given ID ('id' property). + """Fetch a VC record by its given ID ('id' property). Raises: StorageNotFoundError: If the record is not found @@ -43,8 +40,7 @@ async def retrieve_credential_by_given_id(self, given_id: str) -> VCRecord: @abstractmethod async def delete_credential(self, cred: VCRecord): - """ - Remove a previously-stored VC record. + """Remove a previously-stored VC record. Raises: StorageNotFoundError: If the record is not found @@ -53,8 +49,7 @@ async def delete_credential(self, cred: VCRecord): @abstractmethod def build_type_or_schema_query(self, uri_list: Sequence[str]) -> dict: - """ - Build and return backend-specific type_or_schema_query. + """Build and return backend-specific type_or_schema_query. Args: uri_list: List of schema uri from input_descriptor @@ -72,8 +67,7 @@ def search_credentials( given_id: str = None, tag_query: Mapping = None, ) -> "VCRecordSearch": - """ - Start a new VC record search. + """Start a new VC record search. Args: contexts: An inclusive list of JSON-LD contexts to match @@ -88,8 +82,7 @@ def search_credentials( """ def __repr__(self) -> str: - """ - Return a human readable representation of this class. + """Return a human readable representation of this class. Returns: A human readable string for this class @@ -103,8 +96,7 @@ class VCRecordSearch(ABC): @abstractmethod async def fetch(self, max_count: int = None) -> Sequence[VCRecord]: - """ - Fetch the next list of VC records from the store. + """Fetch the next list of VC records from the store. Args: max_count: Max number of records to return. If not provided, diff --git a/aries_cloudagent/storage/vc_holder/in_memory.py b/aries_cloudagent/storage/vc_holder/in_memory.py index cd9b21a18a..4c94f63adf 100644 --- a/aries_cloudagent/storage/vc_holder/in_memory.py +++ b/aries_cloudagent/storage/vc_holder/in_memory.py @@ -32,8 +32,7 @@ def build_type_or_schema_query(self, uri_list: Sequence[str]) -> dict: return type_or_schema_query async def store_credential(self, cred: VCRecord): - """ - Add a new VC record to the store. + """Add a new VC record to the store. Args: cred: The VCRecord instance to store @@ -45,8 +44,7 @@ async def store_credential(self, cred: VCRecord): await self._store.add_record(record) async def retrieve_credential_by_id(self, record_id: str) -> VCRecord: - """ - Fetch a VC record by its record ID. + """Fetch a VC record by its record ID. Raises: StorageNotFoundError: If the record is not found @@ -56,8 +54,7 @@ async def retrieve_credential_by_id(self, record_id: str) -> VCRecord: return storage_to_vc_record(record) async def retrieve_credential_by_given_id(self, given_id: str) -> VCRecord: - """ - Fetch a VC record by its given ID ('id' property). + """Fetch a VC record by its given ID ('id' property). Raises: StorageNotFoundError: If the record is not found @@ -69,8 +66,7 @@ async def retrieve_credential_by_given_id(self, given_id: str) -> VCRecord: return storage_to_vc_record(record) async def delete_credential(self, cred: VCRecord): - """ - Remove a previously-stored VC record. + """Remove a previously-stored VC record. Raises: StorageNotFoundError: If the record is not found @@ -90,8 +86,7 @@ def search_credentials( tag_query: Mapping = None, pd_uri_list: Sequence[str] = None, ) -> "VCRecordSearch": - """ - Start a new VC record search. + """Start a new VC record search. Args: contexts: An inclusive list of JSON-LD contexts to match @@ -140,8 +135,7 @@ def __init__(self, search: InMemoryStorageSearch): self._search = search async def fetch(self, max_count: int = None) -> Sequence[VCRecord]: - """ - Fetch the next list of VC records from the store. + """Fetch the next list of VC records from the store. Args: max_count: Max number of records to return. If not provided, diff --git a/aries_cloudagent/storage/vc_holder/indy.py b/aries_cloudagent/storage/vc_holder/indy.py index 219317ee00..60a96aa1bb 100644 --- a/aries_cloudagent/storage/vc_holder/indy.py +++ b/aries_cloudagent/storage/vc_holder/indy.py @@ -32,8 +32,7 @@ def build_type_or_schema_query(self, uri_list: Sequence[str]) -> dict: return type_or_schema_query async def store_credential(self, cred: VCRecord): - """ - Add a new VC record to the store. + """Add a new VC record to the store. Args: cred: The VCRecord instance to store @@ -45,8 +44,7 @@ async def store_credential(self, cred: VCRecord): await self._store.add_record(record) async def retrieve_credential_by_id(self, record_id: str) -> VCRecord: - """ - Fetch a VC record by its record ID. + """Fetch a VC record by its record ID. Raises: StorageNotFoundError: If the record is not found @@ -56,8 +54,7 @@ async def retrieve_credential_by_id(self, record_id: str) -> VCRecord: return storage_to_vc_record(record) async def retrieve_credential_by_given_id(self, given_id: str) -> VCRecord: - """ - Fetch a VC record by its given ID ('id' property). + """Fetch a VC record by its given ID ('id' property). Raises: StorageNotFoundError: If the record is not found @@ -69,8 +66,7 @@ async def retrieve_credential_by_given_id(self, given_id: str) -> VCRecord: return storage_to_vc_record(record) async def delete_credential(self, cred: VCRecord): - """ - Remove a previously-stored VC record. + """Remove a previously-stored VC record. Raises: StorageNotFoundError: If the record is not found @@ -90,8 +86,7 @@ def search_credentials( tag_query: Mapping = None, pd_uri_list: Sequence[str] = None, ) -> "VCRecordSearch": - """ - Start a new VC record search. + """Start a new VC record search. Args: contexts: An inclusive list of JSON-LD contexts to match @@ -144,8 +139,7 @@ async def close(self): await self._search.close() async def fetch(self, max_count: int = None) -> Sequence[VCRecord]: - """ - Fetch the next list of VC records from the store. + """Fetch the next list of VC records from the store. Args: max_count: Max number of records to return. If not provided, diff --git a/aries_cloudagent/storage/vc_holder/tests/test_vc_record.py b/aries_cloudagent/storage/vc_holder/tests/test_vc_record.py index 3682689255..f3d8456f83 100644 --- a/aries_cloudagent/storage/vc_holder/tests/test_vc_record.py +++ b/aries_cloudagent/storage/vc_holder/tests/test_vc_record.py @@ -145,7 +145,7 @@ def test_create(self): assert record.proof_types == set(PROOF_TYPES) assert record.issuer_id == ISSUER_ID assert record.given_id == GIVEN_ID - assert record.record_id and type(record.record_id) is str + assert record.record_id and isinstance(record.record_id, str) assert record.cred_tags == CRED_TAGS assert record.cred_value == CRED_VALUE diff --git a/aries_cloudagent/storage/vc_holder/vc_record.py b/aries_cloudagent/storage/vc_holder/vc_record.py index f15bd5ede3..697c676c47 100644 --- a/aries_cloudagent/storage/vc_holder/vc_record.py +++ b/aries_cloudagent/storage/vc_holder/vc_record.py @@ -48,8 +48,7 @@ def __init__( self.record_id = record_id or uuid4().hex def serialize(self, as_string=False) -> dict: - """ - Create a JSON-compatible dict representation of the model instance. + """Create a JSON-compatible dict representation of the model instance. Args: as_string: Return a string of JSON instead of a dict @@ -59,7 +58,7 @@ def serialize(self, as_string=False) -> dict: """ - list_coercion = VCRecord(**{k: v for k, v in vars(self).items()}) + list_coercion = VCRecord(**dict(vars(self).items())) for k, v in vars(self).items(): if isinstance(v, set): setattr(list_coercion, k, list(v)) diff --git a/aries_cloudagent/transport/inbound/base.py b/aries_cloudagent/transport/inbound/base.py index 66f23179cf..c89c71879d 100644 --- a/aries_cloudagent/transport/inbound/base.py +++ b/aries_cloudagent/transport/inbound/base.py @@ -23,8 +23,7 @@ def __init__( wire_format: BaseWireFormat = None, root_profile: Profile = None, ): - """ - Initialize the inbound transport instance. + """Initialize the inbound transport instance. Args: scheme: The transport scheme identifier @@ -61,8 +60,7 @@ def create_session( client_info: dict = None, wire_format: BaseWireFormat = None, ) -> Awaitable[InboundSession]: - """ - Create a new inbound session. + """Create a new inbound session. Args: accept_undelivered: Flag for accepting undelivered messages diff --git a/aries_cloudagent/transport/inbound/delivery_queue.py b/aries_cloudagent/transport/inbound/delivery_queue.py index fff932ff6c..c22a2b91cf 100644 --- a/aries_cloudagent/transport/inbound/delivery_queue.py +++ b/aries_cloudagent/transport/inbound/delivery_queue.py @@ -1,5 +1,4 @@ -""" -The Delivery Queue. +"""The Delivery Queue. The delivery queue holds and manages messages that have not yet been delivered to their intended destination. @@ -11,15 +10,13 @@ class QueuedMessage: - """ - Wrapper Class for queued messages. + """Wrapper Class for queued messages. Allows tracking Metadata. """ def __init__(self, msg: OutboundMessage): - """ - Create Wrapper for queued message. + """Create Wrapper for queued message. Automatically sets timestamp on create. """ @@ -27,8 +24,7 @@ def __init__(self, msg: OutboundMessage): self.timestamp = time.time() def older_than(self, compare_timestamp: float) -> bool: - """ - Age Comparison. + """Age Comparison. Allows you to test age as compared to the provided timestamp. @@ -39,15 +35,13 @@ def older_than(self, compare_timestamp: float) -> bool: class DeliveryQueue: - """ - DeliveryQueue class. + """DeliveryQueue class. Manages undelivered messages. """ def __init__(self) -> None: - """ - Initialize an instance of DeliveryQueue. + """Initialize an instance of DeliveryQueue. This uses an in memory structure to queue messages. """ @@ -56,8 +50,7 @@ def __init__(self) -> None: self.ttl_seconds = 604800 # one week def expire_messages(self, ttl=None): - """ - Expire messages that are past the time limit. + """Expire messages that are past the time limit. Args: ttl: Optional. Allows override of configured ttl @@ -71,8 +64,7 @@ def expire_messages(self, ttl=None): ] def add_message(self, msg: OutboundMessage): - """ - Add an OutboundMessage to delivery queue. + """Add an OutboundMessage to delivery queue. The message is added once per recipient key @@ -91,8 +83,7 @@ def add_message(self, msg: OutboundMessage): self.queue_by_key[recipient_key].append(wrapped_msg) def has_message_for_key(self, key: str): - """ - Check for queued messages by key. + """Check for queued messages by key. Args: key: The key to use for lookup @@ -102,8 +93,7 @@ def has_message_for_key(self, key: str): return False def message_count_for_key(self, key: str): - """ - Count of queued messages by key. + """Count of queued messages by key. Args: key: The key to use for lookup @@ -114,8 +104,7 @@ def message_count_for_key(self, key: str): return 0 def get_one_message_for_key(self, key: str): - """ - Remove and return a matching message. + """Remove and return a matching message. Args: key: The key to use for lookup @@ -124,8 +113,7 @@ def get_one_message_for_key(self, key: str): return self.queue_by_key[key].pop(0).msg def inspect_all_messages_for_key(self, key: str): - """ - Return all messages for key. + """Return all messages for key. Args: key: The key to use for lookup @@ -135,8 +123,7 @@ def inspect_all_messages_for_key(self, key: str): yield wrapped_msg.msg def remove_message_for_key(self, key: str, msg: OutboundMessage): - """ - Remove specified message from queue for key. + """Remove specified message from queue for key. Args: key: The key to use for lookup diff --git a/aries_cloudagent/transport/inbound/http.py b/aries_cloudagent/transport/inbound/http.py index 696cab4bd3..a3bdaecd78 100644 --- a/aries_cloudagent/transport/inbound/http.py +++ b/aries_cloudagent/transport/inbound/http.py @@ -16,8 +16,7 @@ class HttpTransport(BaseInboundTransport): """Http Transport class.""" def __init__(self, host: str, port: int, create_session, **kwargs) -> None: - """ - Initialize an inbound HTTP transport instance. + """Initialize an inbound HTTP transport instance. Args: host: Host to listen on @@ -41,8 +40,7 @@ async def make_application(self) -> web.Application: return app async def start(self) -> None: - """ - Start this transport. + """Start this transport. Raises: InboundTransportSetupError: If there was an error starting the webserver @@ -67,8 +65,7 @@ async def stop(self) -> None: self.site = None async def inbound_message_handler(self, request: web.BaseRequest): - """ - Message handler for inbound messages. + """Message handler for inbound messages. Args: request: aiohttp request object @@ -129,8 +126,7 @@ async def inbound_message_handler(self, request: web.BaseRequest): return web.Response(status=200) async def invite_message_handler(self, request: web.BaseRequest): - """ - Message handler for invites. + """Message handler for invites. Args: request: aiohttp request object diff --git a/aries_cloudagent/transport/inbound/manager.py b/aries_cloudagent/transport/inbound/manager.py index 909703e7c5..0969d1c477 100644 --- a/aries_cloudagent/transport/inbound/manager.py +++ b/aries_cloudagent/transport/inbound/manager.py @@ -67,8 +67,7 @@ async def setup(self): self.undelivered_queue = DeliveryQueue() def register(self, config: InboundTransportConfiguration) -> str: - """ - Register transport module. + """Register transport module. Args: config: The inbound transport configuration @@ -103,8 +102,7 @@ def register(self, config: InboundTransportConfiguration) -> str: def register_transport( self, transport: BaseInboundTransport, transport_id: str ) -> str: - """ - Register a new inbound transport class. + """Register a new inbound transport class. Args: transport: Transport instance to register @@ -114,8 +112,7 @@ def register_transport( self.registered_transports[transport_id] = transport async def start_transport(self, transport_id: str): - """ - Start a registered inbound transport. + """Start a registered inbound transport. Args: transport_id: ID for the inbound transport to start @@ -149,8 +146,7 @@ async def create_session( client_info: dict = None, wire_format: BaseWireFormat = None, ): - """ - Create a new inbound session. + """Create a new inbound session. Args: transport_type: The inbound transport identifier @@ -184,8 +180,7 @@ def dispatch_complete(self, message: InboundMessage, completed: CompletedTask): message.dispatch_processing_complete() def closed_session(self, session: InboundSession): - """ - Clean up a closed session. + """Clean up a closed session. Returns an undelivered message to the caller if possible. """ @@ -218,8 +213,7 @@ def return_to_session(self, outbound: OutboundMessage) -> bool: return accepted def return_undelivered(self, outbound: OutboundMessage) -> bool: - """ - Add an undelivered message to the undelivered queue. + """Add an undelivered message to the undelivered queue. At this point the message could not be associated with an inbound session and could not be delivered via an outbound transport. @@ -230,8 +224,7 @@ def return_undelivered(self, outbound: OutboundMessage) -> bool: return False def process_undelivered(self, session: InboundSession): - """ - Interact with undelivered queue to find applicable messages. + """Interact with undelivered queue to find applicable messages. Args: session: The inbound session diff --git a/aries_cloudagent/transport/inbound/receipt.py b/aries_cloudagent/transport/inbound/receipt.py index f36412458e..c084fb0a30 100644 --- a/aries_cloudagent/transport/inbound/receipt.py +++ b/aries_cloudagent/transport/inbound/receipt.py @@ -43,8 +43,7 @@ def __init__( @property def connection_id(self) -> str: - """ - Accessor for the pairwise connection identifier. + """Accessor for the pairwise connection identifier. Returns: This context's connection identifier @@ -54,8 +53,7 @@ def connection_id(self) -> str: @connection_id.setter def connection_id(self, connection_id: bool): - """ - Setter for the pairwise connection identifier. + """Setter for the pairwise connection identifier. Args: connection_id: This context's new connection identifier @@ -65,8 +63,7 @@ def connection_id(self, connection_id: bool): @property def direct_response_mode(self) -> str: - """ - Accessor for the requested direct response mode. + """Accessor for the requested direct response mode. Returns: This context's requested direct response mode @@ -81,8 +78,7 @@ def direct_response_mode(self, mode: str) -> str: @property def direct_response_requested(self) -> str: - """ - Accessor for the the state of the direct response mode. + """Accessor for the the state of the direct response mode. Returns: This context's requested direct response mode @@ -92,8 +88,7 @@ def direct_response_requested(self) -> str: @property def in_time(self) -> str: - """ - Accessor for the datetime the message was received. + """Accessor for the datetime the message was received. Returns: This context's received time @@ -103,8 +98,7 @@ def in_time(self) -> str: @in_time.setter def in_time(self, in_time: datetime): - """ - Setter for the datetime the message was received. + """Setter for the datetime the message was received. Args: in_time: This context's new received time @@ -114,8 +108,7 @@ def in_time(self, in_time: datetime): @property def raw_message(self) -> str: - """ - Accessor for the raw message text. + """Accessor for the raw message text. Returns: The raw message text @@ -125,8 +118,7 @@ def raw_message(self) -> str: @raw_message.setter def raw_message(self, message: str): - """ - Setter for the raw message text. + """Setter for the raw message text. Args: message: The new message text @@ -136,8 +128,7 @@ def raw_message(self, message: str): @property def recipient_did(self) -> str: - """ - Accessor for the recipient DID which corresponds with the verkey. + """Accessor for the recipient DID which corresponds with the verkey. Returns: The recipient DID @@ -147,8 +138,7 @@ def recipient_did(self) -> str: @recipient_did.setter def recipient_did(self, did: str): - """ - Setter for the recipient DID which corresponds with the verkey. + """Setter for the recipient DID which corresponds with the verkey. Args: did: The new recipient DID @@ -158,8 +148,7 @@ def recipient_did(self, did: str): @property def recipient_did_public(self) -> bool: - """ - Check if the recipient did is public. + """Check if the recipient did is public. Indicates whether the message is associated with a public (ledger) recipient DID. @@ -172,8 +161,7 @@ def recipient_did_public(self) -> bool: @recipient_did_public.setter def recipient_did_public(self, public: bool): - """ - Setter for the flag indicating the recipient DID is public. + """Setter for the flag indicating the recipient DID is public. Args: public: A boolean value to indicate if the recipient DID is public @@ -183,8 +171,7 @@ def recipient_did_public(self, public: bool): @property def recipient_verkey(self) -> str: - """ - Accessor for the recipient verkey key used to pack the incoming request. + """Accessor for the recipient verkey key used to pack the incoming request. Returns: The recipient verkey @@ -194,8 +181,7 @@ def recipient_verkey(self) -> str: @recipient_verkey.setter def recipient_verkey(self, verkey: str): - """ - Setter for the recipient public key used to pack the incoming request. + """Setter for the recipient public key used to pack the incoming request. Args: verkey: This context's recipient's verkey @@ -205,8 +191,7 @@ def recipient_verkey(self, verkey: str): @property def sender_did(self) -> str: - """ - Accessor for the sender DID which corresponds with the verkey. + """Accessor for the sender DID which corresponds with the verkey. Returns: The sender did @@ -216,8 +201,7 @@ def sender_did(self) -> str: @sender_did.setter def sender_did(self, did: str): - """ - Setter for the sender DID which corresponds with the verkey. + """Setter for the sender DID which corresponds with the verkey. Args: The new sender did @@ -227,8 +211,7 @@ def sender_did(self, did: str): @property def sender_verkey(self) -> str: - """ - Accessor for the sender public key used to pack the incoming request. + """Accessor for the sender public key used to pack the incoming request. Returns: This context's sender's verkey @@ -238,8 +221,7 @@ def sender_verkey(self) -> str: @sender_verkey.setter def sender_verkey(self, verkey: str): - """ - Setter for the sender public key used to pack the incoming request. + """Setter for the sender public key used to pack the incoming request. Args: verkey: This context's sender's verkey @@ -249,8 +231,7 @@ def sender_verkey(self, verkey: str): @property def thread_id(self) -> str: - """ - Accessor for the identifier of the message thread. + """Accessor for the identifier of the message thread. Returns: The delivery thread ID @@ -260,8 +241,7 @@ def thread_id(self) -> str: @thread_id.setter def thread_id(self, thread: str): - """ - Setter for the message thread identifier. + """Setter for the message thread identifier. Args: thread: The new thread identifier @@ -271,8 +251,7 @@ def thread_id(self, thread: str): @property def parent_thread_id(self) -> Optional[str]: - """ - Accessor for the identifier of the message parent thread. + """Accessor for the identifier of the message parent thread. Returns: The delivery parent thread ID @@ -282,8 +261,7 @@ def parent_thread_id(self) -> Optional[str]: @parent_thread_id.setter def parent_thread_id(self, thread: Optional[str]): - """ - Setter for the message parent thread identifier. + """Setter for the message parent thread identifier. Args: thread: The new parent thread identifier @@ -292,8 +270,7 @@ def parent_thread_id(self, thread: Optional[str]): self._parent_thread_id = thread def __repr__(self) -> str: - """ - Provide a human readable representation of this object. + """Provide a human readable representation of this object. Returns: A human readable representation of this object diff --git a/aries_cloudagent/transport/inbound/session.py b/aries_cloudagent/transport/inbound/session.py index d6214acda7..5bfadb5aec 100644 --- a/aries_cloudagent/transport/inbound/session.py +++ b/aries_cloudagent/transport/inbound/session.py @@ -187,8 +187,7 @@ async def handle_relay_context(self, payload_enc: Union[str, bytes]): pass # No wallet found. Use the base session profile def process_inbound(self, message: InboundMessage): - """ - Process an incoming message and update the session metadata as necessary. + """Process an incoming message and update the session metadata as necessary. Args: message: The inbound message instance @@ -270,8 +269,7 @@ async def encode_outbound(self, outbound: OutboundMessage) -> OutboundMessage: ) def accept_response(self, message: OutboundMessage) -> AcceptResult: - """ - Try to queue an outbound message if it applies to this session. + """Try to queue an outbound message if it applies to this session. Returns: a tuple of (message buffered, retry later) """ diff --git a/aries_cloudagent/transport/inbound/tests/test_delivery_queue.py b/aries_cloudagent/transport/inbound/tests/test_delivery_queue.py index 6f05bfd865..c5f8f19a1e 100644 --- a/aries_cloudagent/transport/inbound/tests/test_delivery_queue.py +++ b/aries_cloudagent/transport/inbound/tests/test_delivery_queue.py @@ -1,8 +1,4 @@ -import asyncio -from unittest import mock, TestCase - from asynctest import TestCase as AsyncTestCase -from asynctest import mock as async_mock from ....connections.models.connection_target import ConnectionTarget from ....transport.outbound.message import OutboundMessage @@ -44,7 +40,7 @@ async def test_message_add_get_by_list(self): msg = OutboundMessage(payload="x", target=t) queue.add_message(msg) assert queue.has_message_for_key("aaa") - msg_list = [m for m in queue.inspect_all_messages_for_key("aaa")] + msg_list = list(queue.inspect_all_messages_for_key("aaa")) assert queue.message_count_for_key("aaa") == 1 assert len(msg_list) == 1 assert msg_list[0] == msg diff --git a/aries_cloudagent/transport/inbound/tests/test_http_transport.py b/aries_cloudagent/transport/inbound/tests/test_http_transport.py index fd74775572..aea3f2e740 100644 --- a/aries_cloudagent/transport/inbound/tests/test_http_transport.py +++ b/aries_cloudagent/transport/inbound/tests/test_http_transport.py @@ -2,13 +2,12 @@ import pytest import json -from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop, unused_port +from aiohttp.test_utils import AioHTTPTestCase, unused_port from asynctest import mock as async_mock from ....core.in_memory import InMemoryProfile from ....core.profile import Profile -from ...error import WireFormatParseError from ...outbound.message import OutboundMessage from ...wire_format import JsonWireFormat diff --git a/aries_cloudagent/transport/inbound/tests/test_manager.py b/aries_cloudagent/transport/inbound/tests/test_manager.py index ae13051416..7b0e2f4424 100644 --- a/aries_cloudagent/transport/inbound/tests/test_manager.py +++ b/aries_cloudagent/transport/inbound/tests/test_manager.py @@ -1,5 +1,3 @@ -import asyncio - from asynctest import TestCase as AsyncTestCase, mock as async_mock from ....core.in_memory import InMemoryProfile diff --git a/aries_cloudagent/transport/inbound/tests/test_ws_transport.py b/aries_cloudagent/transport/inbound/tests/test_ws_transport.py index 0e47bbecde..03250fe7f9 100644 --- a/aries_cloudagent/transport/inbound/tests/test_ws_transport.py +++ b/aries_cloudagent/transport/inbound/tests/test_ws_transport.py @@ -2,7 +2,7 @@ import json import pytest -from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop, unused_port +from aiohttp.test_utils import AioHTTPTestCase, unused_port from asynctest import mock as async_mock from ....core.in_memory import InMemoryProfile diff --git a/aries_cloudagent/transport/inbound/ws.py b/aries_cloudagent/transport/inbound/ws.py index 0348146b9e..98f889cc4a 100644 --- a/aries_cloudagent/transport/inbound/ws.py +++ b/aries_cloudagent/transport/inbound/ws.py @@ -18,8 +18,7 @@ class WsTransport(BaseInboundTransport): """Websockets Transport class.""" def __init__(self, host: str, port: int, create_session, **kwargs) -> None: - """ - Initialize an inbound WebSocket transport instance. + """Initialize an inbound WebSocket transport instance. Args: host: Host to listen on @@ -52,8 +51,7 @@ async def make_application(self) -> web.Application: return app async def start(self) -> None: - """ - Start this transport. + """Start this transport. Raises: InboundTransportSetupError: If there was an error starting the webserver @@ -78,8 +76,7 @@ async def stop(self) -> None: self.site = None async def inbound_message_handler(self, request): - """ - Message handler for inbound messages. + """Message handler for inbound messages. Args: request: aiohttp request object diff --git a/aries_cloudagent/transport/outbound/base.py b/aries_cloudagent/transport/outbound/base.py index eb324013b8..0c6f7c1cf5 100644 --- a/aries_cloudagent/transport/outbound/base.py +++ b/aries_cloudagent/transport/outbound/base.py @@ -104,8 +104,7 @@ async def handle_message( endpoint: str, metadata: dict = None, ): - """ - Handle message. + """Handle message. Args: profile: the profile that produced the message diff --git a/aries_cloudagent/transport/outbound/http.py b/aries_cloudagent/transport/outbound/http.py index 63c1c52980..7a8532518d 100644 --- a/aries_cloudagent/transport/outbound/http.py +++ b/aries_cloudagent/transport/outbound/http.py @@ -54,8 +54,7 @@ async def handle_message( metadata: dict = None, api_key: str = None, ): - """ - Handle message from queue. + """Handle message from queue. Args: profile: the profile that produced the message diff --git a/aries_cloudagent/transport/outbound/manager.py b/aries_cloudagent/transport/outbound/manager.py index dadc8e7f44..ab028f450f 100644 --- a/aries_cloudagent/transport/outbound/manager.py +++ b/aries_cloudagent/transport/outbound/manager.py @@ -36,8 +36,7 @@ class OutboundTransportManager: MAX_RETRY_COUNT = 4 def __init__(self, profile: Profile, handle_not_delivered: Callable = None): - """ - Initialize a `OutboundTransportManager` instance. + """Initialize a `OutboundTransportManager` instance. Args: root_profile: The application root profile @@ -69,8 +68,7 @@ async def setup(self): self.register(outbound_transport) def register(self, module_name: str) -> str: - """ - Register a new outbound transport by module path. + """Register a new outbound transport by module path. Args: module_name: Module name to register @@ -104,8 +102,7 @@ def register(self, module_name: str) -> str: def register_class( self, transport_class: Type[BaseOutboundTransport], transport_id: str = None ) -> str: - """ - Register a new outbound transport class. + """Register a new outbound transport class. Args: transport_class: Transport class to register @@ -221,8 +218,7 @@ def get_transport_instance(self, transport_id: str) -> BaseOutboundTransport: return self.running_transports[transport_id] async def enqueue_message(self, profile: Profile, outbound: OutboundMessage): - """ - Add an outbound message to the queue. + """Add an outbound message to the queue. Args: profile: The active profile for the request @@ -259,8 +255,7 @@ async def enqueue_message(self, profile: Profile, outbound: OutboundMessage): async def encode_outbound_message( self, profile: Profile, outbound: OutboundMessage, target: ConnectionTarget ): - """ - Encode outbound message for the target. + """Encode outbound message for the target. Args: profile: The active profile for the request @@ -285,8 +280,7 @@ def enqueue_webhook( max_attempts: int = None, metadata: dict = None, ): - """ - Add a webhook to the queue. + """Add a webhook to the queue. Args: topic: The webhook topic @@ -315,8 +309,7 @@ def enqueue_webhook( self.process_queued() def process_queued(self) -> asyncio.Task: - """ - Start the process to deliver queued messages if necessary. + """Start the process to deliver queued messages if necessary. Returns: the current queue processing task or None diff --git a/aries_cloudagent/transport/outbound/message.py b/aries_cloudagent/transport/outbound/message.py index eb722ea372..1f9ed54655 100644 --- a/aries_cloudagent/transport/outbound/message.py +++ b/aries_cloudagent/transport/outbound/message.py @@ -37,8 +37,7 @@ def __init__( self.to_session_only = to_session_only def __repr__(self) -> str: - """ - Return a human readable representation of this class. + """Return a human readable representation of this class. Returns: A human readable string for this class diff --git a/aries_cloudagent/transport/outbound/tests/test_http_transport.py b/aries_cloudagent/transport/outbound/tests/test_http_transport.py index 0954f2b9d7..3dc96d35bc 100644 --- a/aries_cloudagent/transport/outbound/tests/test_http_transport.py +++ b/aries_cloudagent/transport/outbound/tests/test_http_transport.py @@ -1,7 +1,7 @@ import asyncio import pytest -from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop +from aiohttp.test_utils import AioHTTPTestCase from aiohttp import web from asynctest import mock as async_mock diff --git a/aries_cloudagent/transport/outbound/tests/test_manager.py b/aries_cloudagent/transport/outbound/tests/test_manager.py index a2e958f2cf..7521173734 100644 --- a/aries_cloudagent/transport/outbound/tests/test_manager.py +++ b/aries_cloudagent/transport/outbound/tests/test_manager.py @@ -4,7 +4,6 @@ from ....core.in_memory import InMemoryProfile from ....connections.models.connection_target import ConnectionTarget -from ....core.in_memory import InMemoryProfile from ...wire_format import BaseWireFormat from .. import manager as test_module diff --git a/aries_cloudagent/transport/outbound/tests/test_ws_transport.py b/aries_cloudagent/transport/outbound/tests/test_ws_transport.py index 12b2a98a75..48697cf399 100644 --- a/aries_cloudagent/transport/outbound/tests/test_ws_transport.py +++ b/aries_cloudagent/transport/outbound/tests/test_ws_transport.py @@ -1,7 +1,7 @@ import asyncio import json -from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop +from aiohttp.test_utils import AioHTTPTestCase from aiohttp import web, WSMsgType from ....core.in_memory import InMemoryProfile diff --git a/aries_cloudagent/transport/outbound/ws.py b/aries_cloudagent/transport/outbound/ws.py index 6ec531c494..6510905631 100644 --- a/aries_cloudagent/transport/outbound/ws.py +++ b/aries_cloudagent/transport/outbound/ws.py @@ -39,8 +39,7 @@ async def handle_message( metadata: dict = None, api_key: str = None, ): - """ - Handle message from queue. + """Handle message from queue. Args: profile: the profile that produced the message diff --git a/aries_cloudagent/transport/pack_format.py b/aries_cloudagent/transport/pack_format.py index 76ac70b87f..9961c3ef5a 100644 --- a/aries_cloudagent/transport/pack_format.py +++ b/aries_cloudagent/transport/pack_format.py @@ -34,8 +34,7 @@ async def parse_message( session: ProfileSession, message_body: Union[str, bytes], ) -> Tuple[dict, MessageReceipt]: - """ - Deserialize an incoming message and further populate the request context. + """Deserialize an incoming message and further populate the request context. Args: session: The profile session for providing wallet access @@ -131,8 +130,7 @@ async def encode_message( routing_keys: Sequence[str], sender_key: str, ) -> Union[str, bytes]: - """ - Encode an outgoing message for transport. + """Encode an outgoing message for transport. Args: session: The profile session for providing wallet access @@ -195,8 +193,7 @@ async def pack( return message def get_recipient_keys(self, message_body: Union[str, bytes]) -> List[str]: - """ - Get all recipient keys from a wire message. + """Get all recipient keys from a wire message. Args: message_body: The body of the message diff --git a/aries_cloudagent/transport/queue/base.py b/aries_cloudagent/transport/queue/base.py index bd5959ce53..e390c02d8b 100644 --- a/aries_cloudagent/transport/queue/base.py +++ b/aries_cloudagent/transport/queue/base.py @@ -9,8 +9,7 @@ class BaseMessageQueue(ABC): @abstractmethod async def enqueue(self, message): - """ - Enqueue a message. + """Enqueue a message. Args: message: The message to add to the end of the queue @@ -22,8 +21,7 @@ async def enqueue(self, message): @abstractmethod async def dequeue(self, *, timeout: int = None): - """ - Dequeue a message. + """Dequeue a message. Returns: The dequeued message, or None if a timeout occurs diff --git a/aries_cloudagent/transport/queue/basic.py b/aries_cloudagent/transport/queue/basic.py index 6edfe93c67..a00a60d7c3 100644 --- a/aries_cloudagent/transport/queue/basic.py +++ b/aries_cloudagent/transport/queue/basic.py @@ -21,8 +21,7 @@ def make_queue(self): return asyncio.Queue() async def enqueue(self, message): - """ - Enqueue a message. + """Enqueue a message. Args: message: The message to add to the end of the queue @@ -38,8 +37,7 @@ async def enqueue(self, message): await self.queue.put(message) async def dequeue(self, *, timeout: int = None): - """ - Dequeue a message. + """Dequeue a message. Returns: The dequeued message, or None if a timeout occurs diff --git a/aries_cloudagent/transport/tests/test_stats.py b/aries_cloudagent/transport/tests/test_stats.py index 6676092d5a..f2cc267d0c 100644 --- a/aries_cloudagent/transport/tests/test_stats.py +++ b/aries_cloudagent/transport/tests/test_stats.py @@ -1,6 +1,5 @@ from asynctest import TestCase as AsyncTestCase, mock as async_mock -from ...config.injection_context import InjectionContext from .. import stats as test_module diff --git a/aries_cloudagent/transport/tests/test_wire_format.py b/aries_cloudagent/transport/tests/test_wire_format.py index b1a5dbda71..48471402a1 100644 --- a/aries_cloudagent/transport/tests/test_wire_format.py +++ b/aries_cloudagent/transport/tests/test_wire_format.py @@ -1,5 +1,3 @@ -import json - from asynctest import TestCase as AsyncTestCase from ..wire_format import JsonWireFormat diff --git a/aries_cloudagent/transport/wire_format.py b/aries_cloudagent/transport/wire_format.py index f70521dd4a..045ba66737 100644 --- a/aries_cloudagent/transport/wire_format.py +++ b/aries_cloudagent/transport/wire_format.py @@ -30,8 +30,7 @@ async def parse_message( session: ProfileSession, message_body: Union[str, bytes], ) -> Tuple[dict, MessageReceipt]: - """ - Deserialize an incoming message and further populate the request context. + """Deserialize an incoming message and further populate the request context. Args: session: The profile session for providing wallet access @@ -54,8 +53,7 @@ async def encode_message( routing_keys: Sequence[str], sender_key: str, ) -> Union[str, bytes]: - """ - Encode an outgoing message for transport. + """Encode an outgoing message for transport. Args: session: The profile session for providing wallet access @@ -74,8 +72,7 @@ async def encode_message( @abstractmethod def get_recipient_keys(self, message_body: Union[str, bytes]) -> List[str]: - """ - Get all recipient keys from a wire message. + """Get all recipient keys from a wire message. Args: message_body: The body of the message @@ -98,8 +95,7 @@ async def parse_message( session: ProfileSession, message_body: Union[str, bytes], ) -> Tuple[dict, MessageReceipt]: - """ - Deserialize an incoming message and further populate the request context. + """Deserialize an incoming message and further populate the request context. Args: session: The profile session for providing wallet access @@ -154,8 +150,7 @@ async def encode_message( routing_keys: Sequence[str], sender_key: str, ) -> Union[str, bytes]: - """ - Encode an outgoing message for transport. + """Encode an outgoing message for transport. Args: session: The profile session for providing wallet access @@ -174,8 +169,7 @@ async def encode_message( return message_json def get_recipient_keys(self, message_body: Union[str, bytes]) -> List[str]: - """ - Get all recipient keys from a wire message. + """Get all recipient keys from a wire message. Args: message_body: The body of the message diff --git a/aries_cloudagent/utils/classloader.py b/aries_cloudagent/utils/classloader.py index 2b4de2a207..b2a24e62a3 100644 --- a/aries_cloudagent/utils/classloader.py +++ b/aries_cloudagent/utils/classloader.py @@ -25,8 +25,7 @@ class ClassLoader: @classmethod def load_module(cls, mod_path: str, package: str = None) -> ModuleType: - """ - Load a module by its absolute path. + """Load a module by its absolute path. Args: mod_path: the absolute or relative module path @@ -80,8 +79,7 @@ def load_class( default_module: Optional[str] = None, package: Optional[str] = None, ): - """ - Resolve a complete class path (ie. typing.Dict) to the class itself. + """Resolve a complete class path (ie. typing.Dict) to the class itself. Args: class_name: the class name @@ -124,8 +122,7 @@ def load_class( @classmethod def load_subclass_of(cls, base_class: Type, mod_path: str, package: str = None): - """ - Resolve an implementation of a base path within a module. + """Resolve an implementation of a base path within a module. Args: base_class: the base class being implemented diff --git a/aries_cloudagent/utils/http.py b/aries_cloudagent/utils/http.py index d17fe234f2..ca40799db3 100644 --- a/aries_cloudagent/utils/http.py +++ b/aries_cloudagent/utils/http.py @@ -157,7 +157,7 @@ async def put_file( json: flag to parse the result as JSON """ - (data_key, file_path) = [k for k in file_data.items()][0] + (data_key, file_path) = list(file_data.items())[0] limit = max_attempts if retry else 1 if not session: diff --git a/aries_cloudagent/utils/jwe.py b/aries_cloudagent/utils/jwe.py index bb555178af..442681a6e6 100644 --- a/aries_cloudagent/utils/jwe.py +++ b/aries_cloudagent/utils/jwe.py @@ -139,7 +139,7 @@ def _deserialize(cls, parsed: Mapping[str, Any]) -> "JweEnvelope": raise ValidationError( "Invalid JWE: invalid JSON for protected headers" ) from None - unprotected = parsed.get("unprotected") or dict() + unprotected = parsed.get("unprotected") or {} if protected.keys() & unprotected.keys(): raise ValidationError("Invalid JWE: duplicate header") diff --git a/aries_cloudagent/utils/outofband.py b/aries_cloudagent/utils/outofband.py index a6598705d6..47743b601b 100644 --- a/aries_cloudagent/utils/outofband.py +++ b/aries_cloudagent/utils/outofband.py @@ -10,8 +10,7 @@ def serialize_outofband(message: AgentMessage, did: DIDInfo, endpoint: str) -> str: - """ - Serialize the agent message as an out-of-band message. + """Serialize the agent message as an out-of-band message. Returns: An OOB message in URL format. diff --git a/aries_cloudagent/utils/stats.py b/aries_cloudagent/utils/stats.py index e57d208cf7..fe81bc975f 100644 --- a/aries_cloudagent/utils/stats.py +++ b/aries_cloudagent/utils/stats.py @@ -181,8 +181,7 @@ async def wrapped(*args, **kwargs): return wrapped def __call__(self, fn, groups: Sequence[str] = None): - """ - Decorate a function or class method. + """Decorate a function or class method. Returns: a wrapped function or coroutine with automatic stats collection """ diff --git a/aries_cloudagent/utils/task_queue.py b/aries_cloudagent/utils/task_queue.py index b51c03a6ad..bc81b39a0c 100644 --- a/aries_cloudagent/utils/task_queue.py +++ b/aries_cloudagent/utils/task_queue.py @@ -66,8 +66,7 @@ def __init__( task_future: asyncio.Future = None, queued_time: float = None, ): - """ - Initialize the pending task. + """Initialize the pending task. Args: coro: The coroutine to be run @@ -127,8 +126,7 @@ class TaskQueue: def __init__( self, max_active: int = 0, timed: bool = False, trace_fn: Callable = None ): - """ - Initialize the task queue. + """Initialize the task queue. Args: max_active: The maximum number of tasks to automatically run @@ -183,8 +181,7 @@ def current_size(self) -> int: return len(self.active_tasks) + len(self.pending_tasks) def __bool__(self) -> bool: - """ - Support for the bool() builtin. + """Support for the bool() builtin. Return: True - the task queue exists even if there are no tasks @@ -243,8 +240,7 @@ async def _drain_loop(self): break def add_pending(self, pending: PendingTask): - """ - Add a task to the pending queue. + """Add a task to the pending queue. Args: pending: The `PendingTask` to add to the task queue @@ -261,8 +257,7 @@ def add_active( ident: str = None, timing: dict = None, ) -> asyncio.Task: - """ - Register an active async task with an optional completion callback. + """Register an active async task with an optional completion callback. Args: task: The asyncio task instance @@ -284,8 +279,7 @@ def run( ident: str = None, timing: dict = None, ) -> asyncio.Task: - """ - Start executing a coroutine as an async task, bypassing the pending queue. + """Start executing a coroutine as an async task, bypassing the pending queue. Args: coro: The coroutine to run @@ -304,7 +298,7 @@ def run( ident = coro_ident(coro) if self.timed: if not timing: - timing = dict() + timing = {} coro = coro_timed(coro, timing) task = self.loop.create_task(coro) return self.add_active(task, task_complete, ident, timing) @@ -312,8 +306,7 @@ def run( def put( self, coro: Coroutine, task_complete: Callable = None, ident: str = None ) -> PendingTask: - """ - Add a new task to the queue, delaying execution if busy. + """Add a new task to the queue, delaying execution if busy. Args: coro: The coroutine to run diff --git a/aries_cloudagent/utils/tests/test_stats.py b/aries_cloudagent/utils/tests/test_stats.py index 34da747459..e055192a49 100644 --- a/aries_cloudagent/utils/tests/test_stats.py +++ b/aries_cloudagent/utils/tests/test_stats.py @@ -1,6 +1,6 @@ from tempfile import NamedTemporaryFile -from asynctest import mock as async_mock, TestCase as AsyncTestCase +from asynctest import TestCase as AsyncTestCase from ..stats import Collector diff --git a/aries_cloudagent/utils/tests/test_task_queue.py b/aries_cloudagent/utils/tests/test_task_queue.py index 35097c3dcd..dc0cc559a0 100644 --- a/aries_cloudagent/utils/tests/test_task_queue.py +++ b/aries_cloudagent/utils/tests/test_task_queue.py @@ -206,7 +206,7 @@ def done(complete: CompletedTask): task = queue.run(retval(1), done) await task - queue.completed_task(task, done, None, dict()) + queue.completed_task(task, done, None, {}) assert completed == [1, 1] async def test_timed(self): diff --git a/aries_cloudagent/utils/tests/test_tracing.py b/aries_cloudagent/utils/tests/test_tracing.py index bbfa979d2a..c27d461dc4 100644 --- a/aries_cloudagent/utils/tests/test_tracing.py +++ b/aries_cloudagent/utils/tests/test_tracing.py @@ -1,7 +1,7 @@ import json import requests -from asynctest import mock as async_mock, TestCase as AsyncTestCase +from asynctest import TestCase as AsyncTestCase from ...protocols.out_of_band.v1_0.messages.invitation import InvitationMessage from ...protocols.issue_credential.v1_0.models.credential_exchange import ( @@ -9,7 +9,6 @@ ) from ...transport.inbound.message import InboundMessage from ...transport.outbound.message import OutboundMessage -from ...messaging.agent_message import AgentMessage from ...messaging.decorators.trace_decorator import TraceDecorator, TRACE_MESSAGE_TARGET from ...protocols.trustping.v1_0.messages.ping import Ping @@ -190,7 +189,7 @@ def test_post_msg_decorator_event(self): trace = message._trace assert trace is not None assert trace.target == TRACE_MESSAGE_TARGET - assert trace.full_thread == True + assert trace.full_thread is True trace_reports = trace.trace_reports assert len(trace_reports) == 1 trace_report = trace_reports[0] diff --git a/aries_cloudagent/utils/tracing.py b/aries_cloudagent/utils/tracing.py index 74ceff8e4a..ca13ac0a01 100644 --- a/aries_cloudagent/utils/tracing.py +++ b/aries_cloudagent/utils/tracing.py @@ -25,8 +25,7 @@ class AdminAPIMessageTracingSchema(OpenAPISchema): - """ - Request/result schema including agent message tracing. + """Request/result schema including agent message tracing. This is to be used as a superclass for aca-py admin input/output messages that need to support tracing. @@ -119,8 +118,7 @@ def trace_event( force_trace: bool = False, raise_errors: bool = False, ) -> float: - """ - Log a trace event to a configured target. + """Log a trace event to a configured target. Args: context: The application context, attributes of interest are: diff --git a/aries_cloudagent/vc/ld_proofs/crypto/tests/test_wallet_key_pair.py b/aries_cloudagent/vc/ld_proofs/crypto/tests/test_wallet_key_pair.py index 6c82afad01..580ce4254a 100644 --- a/aries_cloudagent/vc/ld_proofs/crypto/tests/test_wallet_key_pair.py +++ b/aries_cloudagent/vc/ld_proofs/crypto/tests/test_wallet_key_pair.py @@ -2,7 +2,6 @@ from aries_cloudagent.wallet.key_type import ED25519 -from .....wallet.key_pair import KeyType from ...error import LinkedDataProofException diff --git a/aries_cloudagent/vc/ld_proofs/ld_proofs.py b/aries_cloudagent/vc/ld_proofs/ld_proofs.py index 759d739a8f..c520d75e62 100644 --- a/aries_cloudagent/vc/ld_proofs/ld_proofs.py +++ b/aries_cloudagent/vc/ld_proofs/ld_proofs.py @@ -30,6 +30,7 @@ async def sign( Raises: LinkedDataProofException: When a jsonld url cannot be resolved, OR signing fails. + Returns: dict: Signed document. diff --git a/aries_cloudagent/vc/ld_proofs/suites/bbs_bls_signature_2020.py b/aries_cloudagent/vc/ld_proofs/suites/bbs_bls_signature_2020.py index 5fd8825995..af6255b653 100644 --- a/aries_cloudagent/vc/ld_proofs/suites/bbs_bls_signature_2020.py +++ b/aries_cloudagent/vc/ld_proofs/suites/bbs_bls_signature_2020.py @@ -76,7 +76,7 @@ async def create_proof( ) # Encode statements as bytes - verify_data = list(map(lambda item: item.encode("utf-8"), verify_data)) + verify_data = [item.encode("utf-8") for item in verify_data] # Sign statements proof = await self.sign(verify_data=verify_data, proof=proof) @@ -99,7 +99,7 @@ async def verify_proof( ) # Encode statements as bytes - verify_data = list(map(lambda item: item.encode("utf-8"), verify_data)) + verify_data = [item.encode("utf-8") for item in verify_data] # Fetch verification method verification_method = self._get_verification_method( diff --git a/aries_cloudagent/vc/ld_proofs/suites/bbs_bls_signature_proof_2020.py b/aries_cloudagent/vc/ld_proofs/suites/bbs_bls_signature_proof_2020.py index 4aced33c0a..88b00eb317 100644 --- a/aries_cloudagent/vc/ld_proofs/suites/bbs_bls_signature_proof_2020.py +++ b/aries_cloudagent/vc/ld_proofs/suites/bbs_bls_signature_proof_2020.py @@ -133,18 +133,14 @@ async def derive_proof( # Always reveal all the statements associated to the original proof # these are always the first statements in the normalized form - proof_reveal_indices = [indice for indice in range(number_of_proof_statements)] + proof_reveal_indices = list(range(number_of_proof_statements)) # Reveal the statements indicated from the reveal document - document_reveal_indices = list( - map( - lambda reveal_statement: transformed_input_document_statements.index( - reveal_statement - ) - + number_of_proof_statements, - reveal_document_statements, - ) - ) + document_reveal_indices = [ + transformed_input_document_statements.index(reveal_statement) + + number_of_proof_statements + for reveal_statement in reveal_document_statements + ] # Check there is not a mismatch if len(document_reveal_indices) != len(reveal_document_statements): diff --git a/aries_cloudagent/vc/ld_proofs/suites/tests/test_bbs_bls_signature_2020.py b/aries_cloudagent/vc/ld_proofs/suites/tests/test_bbs_bls_signature_2020.py index bb3bc4d523..ba477604e8 100644 --- a/aries_cloudagent/vc/ld_proofs/suites/tests/test_bbs_bls_signature_2020.py +++ b/aries_cloudagent/vc/ld_proofs/suites/tests/test_bbs_bls_signature_2020.py @@ -4,7 +4,6 @@ from aries_cloudagent.wallet.key_type import BLS12381G2 from .....did.did_key import DIDKey -from .....wallet.key_pair import KeyType from .....wallet.in_memory import InMemoryWallet from .....core.in_memory import InMemoryProfile from ....tests.document_loader import custom_document_loader diff --git a/aries_cloudagent/vc/ld_proofs/suites/tests/test_bbs_bls_signature_proof_2020.py b/aries_cloudagent/vc/ld_proofs/suites/tests/test_bbs_bls_signature_proof_2020.py index 67d027d770..df2080480d 100644 --- a/aries_cloudagent/vc/ld_proofs/suites/tests/test_bbs_bls_signature_proof_2020.py +++ b/aries_cloudagent/vc/ld_proofs/suites/tests/test_bbs_bls_signature_proof_2020.py @@ -4,7 +4,6 @@ from aries_cloudagent.wallet.key_type import BLS12381G2 from .....did.did_key import DIDKey -from .....wallet.key_pair import KeyType from .....wallet.in_memory import InMemoryWallet from .....core.in_memory import InMemoryProfile from ....tests.document_loader import custom_document_loader diff --git a/aries_cloudagent/vc/ld_proofs/suites/tests/test_ed25519_signature_2018.py b/aries_cloudagent/vc/ld_proofs/suites/tests/test_ed25519_signature_2018.py index 60bf0389f6..20e510df3e 100644 --- a/aries_cloudagent/vc/ld_proofs/suites/tests/test_ed25519_signature_2018.py +++ b/aries_cloudagent/vc/ld_proofs/suites/tests/test_ed25519_signature_2018.py @@ -4,7 +4,6 @@ from .....did.did_key import DIDKey -from .....wallet.key_pair import KeyType from .....wallet.in_memory import InMemoryWallet from .....core.in_memory import InMemoryProfile diff --git a/aries_cloudagent/vc/ld_proofs/validation_result.py b/aries_cloudagent/vc/ld_proofs/validation_result.py index 543a3be56e..40b8eaea8d 100644 --- a/aries_cloudagent/vc/ld_proofs/validation_result.py +++ b/aries_cloudagent/vc/ld_proofs/validation_result.py @@ -15,8 +15,7 @@ def __init__( self.controller = controller def __repr__(self) -> str: - """ - Return a human readable representation of this class. + """Return a human readable representation of this class. Returns: A human readable string for this class @@ -54,8 +53,7 @@ def __init__( self.purpose_result = purpose_result def __repr__(self) -> str: - """ - Return a human readable representation of this class. + """Return a human readable representation of this class. Returns: A human readable string for this class @@ -94,8 +92,7 @@ def __init__( self.errors = errors def __repr__(self) -> str: - """ - Return a human readable representation of this class. + """Return a human readable representation of this class. Returns: A human readable string for this class diff --git a/aries_cloudagent/vc/vc_ld/models/credential.py b/aries_cloudagent/vc/vc_ld/models/credential.py index 876104f244..101568a687 100644 --- a/aries_cloudagent/vc/vc_ld/models/credential.py +++ b/aries_cloudagent/vc/vc_ld/models/credential.py @@ -87,7 +87,7 @@ def add_context(self, context: Union[str, dict]): @property def context_urls(self) -> List[str]: """Getter for context urls.""" - return [context for context in self.context if type(context) is str] + return [context for context in self.context if isinstance(context, str)] @property def type(self) -> List[str]: @@ -127,7 +127,7 @@ def issuer_id(self) -> Optional[str]: """Getter for issuer id.""" if not self._issuer: return None - elif type(self._issuer) is str: + elif isinstance(self._issuer, str): return self._issuer return self._issuer.get("id") @@ -197,7 +197,7 @@ def credential_subject_ids(self) -> List[str]: """Getter for credential subject ids.""" if not self._credential_subject: return [] - elif type(self._credential_subject) is dict: + elif isinstance(self._credential_subject, dict): subject_id = self._credential_subject.get("id") return [subject_id] if subject_id else [] diff --git a/aries_cloudagent/vc/vc_ld/validation_result.py b/aries_cloudagent/vc/vc_ld/validation_result.py index 1f25a6220e..45d9e76f41 100644 --- a/aries_cloudagent/vc/vc_ld/validation_result.py +++ b/aries_cloudagent/vc/vc_ld/validation_result.py @@ -23,8 +23,7 @@ def __init__( self.errors = errors def __repr__(self) -> str: - """ - Return a human readable representation of this class. + """Return a human readable representation of this class. Returns: A human readable string for this class diff --git a/aries_cloudagent/vc/vc_ld/verify.py b/aries_cloudagent/vc/vc_ld/verify.py index d589dd23c5..7805133209 100644 --- a/aries_cloudagent/vc/vc_ld/verify.py +++ b/aries_cloudagent/vc/vc_ld/verify.py @@ -129,7 +129,7 @@ async def _verify_presentation( ] ) - verified = all([result.verified for result in credential_results]) + verified = all(result.verified for result in credential_results) return PresentationVerificationResult( verified=verified, diff --git a/aries_cloudagent/wallet/askar.py b/aries_cloudagent/wallet/askar.py index dac9a4cf5d..3f530a28bb 100644 --- a/aries_cloudagent/wallet/askar.py +++ b/aries_cloudagent/wallet/askar.py @@ -46,8 +46,7 @@ class AskarWallet(BaseWallet): """Aries-Askar wallet implementation.""" def __init__(self, session: AskarProfileSession): - """ - Initialize a new `AskarWallet` instance. + """Initialize a new `AskarWallet` instance. Args: session: The Askar profile session instance to use @@ -96,8 +95,7 @@ async def create_signing_key( return KeyInfo(verkey=verkey, metadata=metadata, key_type=key_type) async def get_signing_key(self, verkey: str) -> KeyInfo: - """ - Fetch info for a signing keypair. + """Fetch info for a signing keypair. Args: verkey: The verification key of the keypair @@ -121,8 +119,7 @@ async def get_signing_key(self, verkey: str) -> KeyInfo: return KeyInfo(verkey=verkey, metadata=metadata, key_type=ED25519) async def replace_signing_key_metadata(self, verkey: str, metadata: dict): - """ - Replace the metadata associated with a signing keypair. + """Replace the metadata associated with a signing keypair. Args: verkey: The verification key of the keypair @@ -153,8 +150,7 @@ async def create_local_did( did: str = None, metadata: dict = None, ) -> DIDInfo: - """ - Create and store a new local DID. + """Create and store a new local DID. Args: method: The method to use for the DID @@ -235,8 +231,7 @@ async def create_local_did( ) async def get_local_dids(self) -> Sequence[DIDInfo]: - """ - Get list of defined local DIDs. + """Get list of defined local DIDs. Returns: A list of locally stored DIDs as `DIDInfo` instances @@ -249,8 +244,7 @@ async def get_local_dids(self) -> Sequence[DIDInfo]: return ret async def get_local_did(self, did: str) -> DIDInfo: - """ - Find info for a local DID. + """Find info for a local DID. Args: did: The DID for which to get info @@ -275,8 +269,7 @@ async def get_local_did(self, did: str) -> DIDInfo: return self._load_did_entry(did_entry) async def get_local_did_for_verkey(self, verkey: str) -> DIDInfo: - """ - Resolve a local DID from a verkey. + """Resolve a local DID from a verkey. Args: verkey: The verkey for which to get the local DID @@ -300,8 +293,7 @@ async def get_local_did_for_verkey(self, verkey: str) -> DIDInfo: raise WalletNotFoundError("No DID defined for verkey: {}".format(verkey)) async def replace_local_did_metadata(self, did: str, metadata: dict): - """ - Replace metadata for a local DID. + """Replace metadata for a local DID. Args: did: The DID for which to replace metadata @@ -323,8 +315,7 @@ async def replace_local_did_metadata(self, did: str, metadata: dict): raise WalletError("Error updating DID metadata") from err async def get_public_did(self) -> DIDInfo: - """ - Retrieve the public DID. + """Retrieve the public DID. Returns: The currently public `DIDInfo`, if any @@ -374,8 +365,7 @@ async def get_public_did(self) -> DIDInfo: return public_info async def set_public_did(self, did: Union[str, DIDInfo]) -> DIDInfo: - """ - Assign the public DID. + """Assign the public DID. Returns: The updated `DIDInfo` @@ -435,8 +425,7 @@ async def set_did_endpoint( endorser_did: str = None, routing_keys: List[str] = None, ): - """ - Update the endpoint for a DID in the wallet, send to ledger if public or posted. + """Update the endpoint for a DID in the wallet, send to ledger if posted. Args: did: DID for which to set endpoint @@ -480,8 +469,7 @@ async def set_did_endpoint( await self.replace_local_did_metadata(did, metadata) async def rotate_did_keypair_start(self, did: str, next_seed: str = None) -> str: - """ - Begin key rotation for DID that wallet owns: generate new keypair. + """Begin key rotation for DID that wallet owns: generate new keypair. Args: did: signing DID @@ -532,8 +520,7 @@ async def rotate_did_keypair_start(self, did: str, next_seed: str = None) -> str return verkey async def rotate_did_keypair_apply(self, did: str) -> DIDInfo: - """ - Apply temporary keypair as main for DID that wallet owns. + """Apply temporary keypair as main for DID that wallet owns. Args: did: signing DID @@ -563,8 +550,7 @@ async def rotate_did_keypair_apply(self, did: str) -> DIDInfo: async def sign_message( self, message: Union[List[bytes], bytes], from_verkey: str ) -> bytes: - """ - Sign message(s) using the private key associated with a given verkey. + """Sign message(s) using the private key associated with a given verkey. Args: message: The message(s) to sign @@ -608,8 +594,7 @@ async def verify_message( from_verkey: str, key_type: KeyType, ) -> bool: - """ - Verify a signature against the public key of the signer. + """Verify a signature against the public key of the signer. Args: message: The message to verify @@ -654,8 +639,7 @@ async def verify_message( async def pack_message( self, message: str, to_verkeys: Sequence[str], from_verkey: str = None ) -> bytes: - """ - Pack a message for one or more recipients. + """Pack a message for one or more recipients. Args: message: The message to pack @@ -687,8 +671,7 @@ async def pack_message( raise WalletError("Exception when packing message") from err async def unpack_message(self, enc_message: bytes) -> Tuple[str, str, str]: - """ - Unpack a message. + """Unpack a message. Args: enc_message: The packed message bytes diff --git a/aries_cloudagent/wallet/base.py b/aries_cloudagent/wallet/base.py index 46bbc3eab9..65e871a692 100644 --- a/aries_cloudagent/wallet/base.py +++ b/aries_cloudagent/wallet/base.py @@ -33,8 +33,7 @@ async def create_signing_key( @abstractmethod async def get_signing_key(self, verkey: str) -> KeyInfo: - """ - Fetch info for a signing keypair. + """Fetch info for a signing keypair. Args: verkey: The verification key of the keypair @@ -46,8 +45,7 @@ async def get_signing_key(self, verkey: str) -> KeyInfo: @abstractmethod async def replace_signing_key_metadata(self, verkey: str, metadata: dict): - """ - Replace the metadata associated with a signing keypair. + """Replace the metadata associated with a signing keypair. Args: verkey: The verification key of the keypair @@ -57,8 +55,7 @@ async def replace_signing_key_metadata(self, verkey: str, metadata: dict): @abstractmethod async def rotate_did_keypair_start(self, did: str, next_seed: str = None) -> str: - """ - Begin key rotation for DID that wallet owns: generate new keypair. + """Begin key rotation for DID that wallet owns: generate new keypair. Args: did: signing DID @@ -74,8 +71,7 @@ async def rotate_did_keypair_start(self, did: str, next_seed: str = None) -> str @abstractmethod async def rotate_did_keypair_apply(self, did: str) -> None: - """ - Apply temporary keypair as main for DID that wallet owns. + """Apply temporary keypair as main for DID that wallet owns. Args: did: signing DID @@ -95,8 +91,7 @@ async def create_local_did( did: str = None, metadata: dict = None, ) -> DIDInfo: - """ - Create and store a new local DID. + """Create and store a new local DID. Args: method: The method to use for the DID @@ -118,8 +113,7 @@ async def create_public_did( did: str = None, metadata: dict = {}, ) -> DIDInfo: - """ - Create and store a new public DID. + """Create and store a new public DID. Args: seed: Optional seed to use for DID @@ -139,8 +133,7 @@ async def create_public_did( @abstractmethod async def get_public_did(self) -> DIDInfo: - """ - Retrieve the public DID. + """Retrieve the public DID. Returns: The currently public `DIDInfo`, if any @@ -149,8 +142,7 @@ async def get_public_did(self) -> DIDInfo: @abstractmethod async def set_public_did(self, did: Union[str, DIDInfo]) -> DIDInfo: - """ - Assign the public DID. + """Assign the public DID. Returns: The updated `DIDInfo` @@ -159,8 +151,7 @@ async def set_public_did(self, did: Union[str, DIDInfo]) -> DIDInfo: @abstractmethod async def get_local_dids(self) -> Sequence[DIDInfo]: - """ - Get list of defined local DIDs. + """Get list of defined local DIDs. Returns: A list of `DIDInfo` instances @@ -169,8 +160,7 @@ async def get_local_dids(self) -> Sequence[DIDInfo]: @abstractmethod async def get_local_did(self, did: str) -> DIDInfo: - """ - Find info for a local DID. + """Find info for a local DID. Args: did: The DID for which to get info @@ -182,8 +172,7 @@ async def get_local_did(self, did: str) -> DIDInfo: @abstractmethod async def get_local_did_for_verkey(self, verkey: str) -> DIDInfo: - """ - Resolve a local DID from a verkey. + """Resolve a local DID from a verkey. Args: verkey: Verkey for which to get DID info @@ -195,8 +184,7 @@ async def get_local_did_for_verkey(self, verkey: str) -> DIDInfo: @abstractmethod async def replace_local_did_metadata(self, did: str, metadata: dict): - """ - Replace the metadata associated with a local DID. + """Replace the metadata associated with a local DID. Prefer `set_did_endpoint()` to set endpoint in metadata. @@ -207,8 +195,7 @@ async def replace_local_did_metadata(self, did: str, metadata: dict): """ async def get_posted_dids(self) -> Sequence[DIDInfo]: - """ - Get list of defined posted DIDs. + """Get list of defined posted DIDs. Returns: A list of `DIDInfo` instances @@ -228,8 +215,7 @@ async def set_did_endpoint( endorser_did: str = None, routing_keys: List[str] = None, ): - """ - Update the endpoint for a DID in the wallet, send to ledger if public or posted. + """Update the endpoint for a DID in the wallet, send to ledger if posted. Args: did: DID for which to set endpoint @@ -255,8 +241,7 @@ async def set_did_endpoint( async def sign_message( self, message: Union[List[bytes], bytes], from_verkey: str ) -> bytes: - """ - Sign message(s) using the private key associated with a given verkey. + """Sign message(s) using the private key associated with a given verkey. Args: message: The message(s) to sign @@ -275,8 +260,7 @@ async def verify_message( from_verkey: str, key_type: KeyType, ) -> bool: - """ - Verify a signature against the public key of the signer. + """Verify a signature against the public key of the signer. Args: message: The message to verify @@ -293,8 +277,7 @@ async def verify_message( async def pack_message( self, message: str, to_verkeys: Sequence[str], from_verkey: str = None ) -> bytes: - """ - Pack a message for one or more recipients. + """Pack a message for one or more recipients. Args: message: The message to pack @@ -308,8 +291,7 @@ async def pack_message( @abstractmethod async def unpack_message(self, enc_message: bytes) -> Tuple[str, str, str]: - """ - Unpack a message. + """Unpack a message. Args: enc_message: The encrypted message diff --git a/aries_cloudagent/wallet/bbs.py b/aries_cloudagent/wallet/bbs.py index a204682a73..396e371442 100644 --- a/aries_cloudagent/wallet/bbs.py +++ b/aries_cloudagent/wallet/bbs.py @@ -54,8 +54,7 @@ def sign_messages_bls12381g2(messages: List[bytes], secret: bytes): def verify_signed_messages_bls12381g2( messages: List[bytes], signature: bytes, public_key: bytes ) -> bool: - """ - Verify an ed25519 signed message according to a public verification key. + """Verify an ed25519 signed message according to a public verification key. Args: signed: The signed messages @@ -84,8 +83,7 @@ def verify_signed_messages_bls12381g2( def create_bls12381g2_keypair(seed: bytes = None) -> Tuple[bytes, bytes]: - """ - Create a public and private bls12381g2 keypair from a seed value. + """Create a public and private bls12381g2 keypair from a seed value. Args: seed: Seed for keypair diff --git a/aries_cloudagent/wallet/crypto.py b/aries_cloudagent/wallet/crypto.py index f44e9cff77..b5e7f2d3b7 100644 --- a/aries_cloudagent/wallet/crypto.py +++ b/aries_cloudagent/wallet/crypto.py @@ -24,8 +24,7 @@ def create_keypair(key_type: KeyType, seed: bytes = None) -> Tuple[bytes, bytes]: - """ - Create a public and private keypair from a seed value. + """Create a public and private keypair from a seed value. Args: key_type: The type of key to generate @@ -49,8 +48,7 @@ def create_keypair(key_type: KeyType, seed: bytes = None) -> Tuple[bytes, bytes] def create_ed25519_keypair(seed: bytes = None) -> Tuple[bytes, bytes]: - """ - Create a public and private ed25519 keypair from a seed value. + """Create a public and private ed25519 keypair from a seed value. Args: seed: Seed for keypair @@ -66,8 +64,7 @@ def create_ed25519_keypair(seed: bytes = None) -> Tuple[bytes, bytes]: def seed_to_did(seed: str) -> str: - """ - Derive a DID from a seed value. + """Derive a DID from a seed value. Args: seed: The seed to derive @@ -83,8 +80,7 @@ def seed_to_did(seed: str) -> str: def did_is_self_certified(did: str, verkey: str) -> bool: - """ - Check if the DID is self certified. + """Check if the DID is self certified. Args: did: DID string @@ -107,8 +103,7 @@ def sign_pk_from_sk(secret: bytes) -> bytes: def validate_seed(seed: Union[str, bytes]) -> bytes: - """ - Convert a seed parameter to standard format and check length. + """Convert a seed parameter to standard format and check length. Args: seed: The seed to validate @@ -134,8 +129,7 @@ def validate_seed(seed: Union[str, bytes]) -> bytes: def sign_message( message: Union[List[bytes], bytes], secret: bytes, key_type: KeyType ) -> bytes: - """ - Sign message(s) using a private signing key. + """Sign message(s) using a private signing key. Args: message: The message(s) to sign @@ -185,8 +179,7 @@ def verify_signed_message( verkey: bytes, key_type: KeyType, ) -> bool: - """ - Verify a signed message according to a public verification key. + """Verify a signed message according to a public verification key. Args: message: The message(s) to verify @@ -222,8 +215,7 @@ def verify_signed_message( def verify_signed_message_ed25519( message: bytes, signature: bytes, verkey: bytes ) -> bool: - """ - Verify an ed25519 signed message according to a public verification key. + """Verify an ed25519 signed message according to a public verification key. Args: message: The message to verify @@ -247,8 +239,7 @@ def add_pack_recipients( to_verkeys: Sequence[bytes], from_secret: bytes = None, ): - """ - Assemble the recipients block of a packed message. + """Assemble the recipients block of a packed message. Args: wrapper: The envelope to add recipients to @@ -301,8 +292,7 @@ def ed25519_pk_to_curve25519(public_key: bytes) -> bytes: def encrypt_plaintext( message: str, add_data: bytes, key: bytes ) -> Tuple[bytes, bytes, bytes]: - """ - Encrypt the payload of a packed message. + """Encrypt the payload of a packed message. Args: message: Message to encrypt @@ -327,8 +317,7 @@ def encrypt_plaintext( def decrypt_plaintext( ciphertext: bytes, recips_bin: bytes, nonce: bytes, key: bytes ) -> str: - """ - Decrypt the payload of a packed message. + """Decrypt the payload of a packed message. Args: ciphertext: @@ -349,8 +338,7 @@ def decrypt_plaintext( def encode_pack_message( message: str, to_verkeys: Sequence[bytes], from_secret: bytes = None ) -> bytes: - """ - Assemble a packed message for a set of recipients, optionally including the sender. + """Assemble a packed message for a set of recipients, optionally including the sender. Args: message: The message to pack @@ -381,8 +369,7 @@ def encode_pack_message( def decode_pack_message( enc_message: bytes, find_key: Callable ) -> Tuple[str, Optional[str], str]: - """ - Decode a packed message. + """Decode a packed message. Disassemble and unencrypt a packed message, returning the message content, verification key of the sender (if available), and verification key of the @@ -422,8 +409,7 @@ def decode_pack_message( def decode_pack_message_outer(enc_message: bytes) -> Tuple[dict, dict, bool]: - """ - Decode the outer wrapper of a packed message and extract the recipients. + """Decode the outer wrapper of a packed message and extract the recipients. Args: enc_message: The encrypted message @@ -447,8 +433,7 @@ def decode_pack_message_outer(enc_message: bytes) -> Tuple[dict, dict, bool]: def decode_pack_message_payload(wrapper: JweEnvelope, payload_key: bytes) -> str: - """ - Decode the payload of a packed message once the CEK is known. + """Decode the payload of a packed message once the CEK is known. Args: wrapper: The decoded message wrapper @@ -463,8 +448,7 @@ def decode_pack_message_payload(wrapper: JweEnvelope, payload_key: bytes) -> str def extract_pack_recipients(recipients: Sequence[JweRecipient]) -> dict: - """ - Extract the pack message recipients into a dict indexed by verkey. + """Extract the pack message recipients into a dict indexed by verkey. Args: recipients: Recipients to locate @@ -500,8 +484,7 @@ def extract_pack_recipients(recipients: Sequence[JweRecipient]) -> dict: def extract_payload_key(sender_cek: dict, recip_secret: bytes) -> Tuple[bytes, str]: - """ - Extract the payload key from pack recipient details. + """Extract the payload key from pack recipient details. Returns: A tuple of the CEK and sender verkey """ diff --git a/aries_cloudagent/wallet/did_parameters_validation.py b/aries_cloudagent/wallet/did_parameters_validation.py index 04572c77bf..93f72194e2 100644 --- a/aries_cloudagent/wallet/did_parameters_validation.py +++ b/aries_cloudagent/wallet/did_parameters_validation.py @@ -39,8 +39,7 @@ def validate_or_derive_did( verkey: bytes, did: Optional[str], ) -> str: - """ - Validate compatibility of the provided did (if any) with the given DID method. + """Validate compatibility of the provided did (if any) with the given DID method. If no DID was provided, automatically derive one for methods that support it. """ diff --git a/aries_cloudagent/wallet/in_memory.py b/aries_cloudagent/wallet/in_memory.py index 03fc4fb8aa..2514ca805f 100644 --- a/aries_cloudagent/wallet/in_memory.py +++ b/aries_cloudagent/wallet/in_memory.py @@ -27,8 +27,7 @@ class InMemoryWallet(BaseWallet): """In-memory wallet implementation.""" def __init__(self, profile: InMemoryProfile): - """ - Initialize an `InMemoryWallet` instance. + """Initialize an `InMemoryWallet` instance. Args: profile: The in-memory profile used to store state @@ -42,8 +41,7 @@ async def create_signing_key( seed: str = None, metadata: dict = None, ) -> KeyInfo: - """ - Create a new public/private signing keypair. + """Create a new public/private signing keypair. Args: seed: Seed to use for signing key @@ -76,8 +74,7 @@ async def create_signing_key( ) async def get_signing_key(self, verkey: str) -> KeyInfo: - """ - Fetch info for a signing keypair. + """Fetch info for a signing keypair. Args: verkey: The verification key of the keypair @@ -99,8 +96,7 @@ async def get_signing_key(self, verkey: str) -> KeyInfo: ) async def replace_signing_key_metadata(self, verkey: str, metadata: dict): - """ - Replace the metadata associated with a signing keypair. + """Replace the metadata associated with a signing keypair. Args: verkey: The verification key of the keypair @@ -115,8 +111,7 @@ async def replace_signing_key_metadata(self, verkey: str, metadata: dict): self.profile.keys[verkey]["metadata"] = metadata.copy() if metadata else {} async def rotate_did_keypair_start(self, did: str, next_seed: str = None) -> str: - """ - Begin key rotation for DID that wallet owns: generate new keypair. + """Begin key rotation for DID that wallet owns: generate new keypair. Args: did: signing DID @@ -145,8 +140,7 @@ async def rotate_did_keypair_start(self, did: str, next_seed: str = None) -> str return key_info.verkey async def rotate_did_keypair_apply(self, did: str) -> None: - """ - Apply temporary keypair as main for DID that wallet owns. + """Apply temporary keypair as main for DID that wallet owns. Args: did: signing DID @@ -193,8 +187,7 @@ async def create_local_did( did: str = None, metadata: dict = None, ) -> DIDInfo: - """ - Create and store a new local DID. + """Create and store a new local DID. Args: method: The method to use for the DID @@ -244,8 +237,7 @@ async def create_local_did( ) def _get_did_info(self, did: str) -> DIDInfo: - """ - Convert internal DID record to DIDInfo. + """Convert internal DID record to DIDInfo. Args: did: The DID to get info for @@ -264,8 +256,7 @@ def _get_did_info(self, did: str) -> DIDInfo: ) async def get_local_dids(self) -> Sequence[DIDInfo]: - """ - Get list of defined local DIDs. + """Get list of defined local DIDs. Returns: A list of locally stored DIDs as `DIDInfo` instances @@ -275,8 +266,7 @@ async def get_local_dids(self) -> Sequence[DIDInfo]: return ret async def get_local_did(self, did: str) -> DIDInfo: - """ - Find info for a local DID. + """Find info for a local DID. Args: did: The DID for which to get info @@ -293,8 +283,7 @@ async def get_local_did(self, did: str) -> DIDInfo: return self._get_did_info(did) async def get_local_did_for_verkey(self, verkey: str) -> DIDInfo: - """ - Resolve a local DID from a verkey. + """Resolve a local DID from a verkey. Args: verkey: The verkey for which to get the local DID @@ -312,8 +301,7 @@ async def get_local_did_for_verkey(self, verkey: str) -> DIDInfo: raise WalletNotFoundError("Verkey not found: {}".format(verkey)) async def replace_local_did_metadata(self, did: str, metadata: dict): - """ - Replace metadata for a local DID. + """Replace metadata for a local DID. Args: did: The DID for which to replace metadata @@ -328,8 +316,7 @@ async def replace_local_did_metadata(self, did: str, metadata: dict): self.profile.local_dids[did]["metadata"] = metadata.copy() if metadata else {} def _get_private_key(self, verkey: str) -> bytes: - """ - Resolve private key for a wallet DID. + """Resolve private key for a wallet DID. Args: verkey: The verkey to lookup @@ -352,8 +339,7 @@ def _get_private_key(self, verkey: str) -> bytes: raise WalletError("Private key not found for verkey: {}".format(verkey)) async def get_public_did(self) -> DIDInfo: - """ - Retrieve the public DID. + """Retrieve the public DID. Returns: The currently public `DIDInfo`, if any @@ -368,8 +354,7 @@ async def get_public_did(self) -> DIDInfo: return None async def set_public_did(self, did: Union[str, DIDInfo]) -> DIDInfo: - """ - Assign the public DID. + """Assign the public DID. Returns: The updated `DIDInfo` @@ -400,8 +385,7 @@ async def set_public_did(self, did: Union[str, DIDInfo]) -> DIDInfo: async def sign_message( self, message: Union[List[bytes], bytes], from_verkey: str ) -> bytes: - """ - Sign message(s) using the private key associated with a given verkey. + """Sign message(s) using the private key associated with a given verkey. Args: message: Message(s) bytes to sign @@ -436,8 +420,7 @@ async def verify_message( from_verkey: str, key_type: KeyType, ) -> bool: - """ - Verify a signature against the public key of the signer. + """Verify a signature against the public key of the signer. Args: message: Message(s) to verify @@ -468,8 +451,7 @@ async def verify_message( async def pack_message( self, message: str, to_verkeys: Sequence[str], from_verkey: str = None ) -> bytes: - """ - Pack a message for one or more recipients. + """Pack a message for one or more recipients. Args: message: The message to pack @@ -494,8 +476,7 @@ async def pack_message( return result async def unpack_message(self, enc_message: bytes) -> Tuple[str, str, str]: - """ - Unpack a message. + """Unpack a message. Args: enc_message: The packed message bytes diff --git a/aries_cloudagent/wallet/indy.py b/aries_cloudagent/wallet/indy.py index 7a99858044..3e570f4d62 100644 --- a/aries_cloudagent/wallet/indy.py +++ b/aries_cloudagent/wallet/indy.py @@ -138,8 +138,7 @@ async def __create_keypair_signing_key( async def create_signing_key( self, key_type: KeyType, seed: str = None, metadata: dict = None ) -> KeyInfo: - """ - Create a new public/private signing keypair. + """Create a new public/private signing keypair. Args: seed: Seed for key @@ -205,8 +204,7 @@ async def __get_keypair_signing_key(self, verkey: str) -> KeyInfo: raise WalletDuplicateError(f"Multiple keys exist for verkey: {verkey}") async def get_signing_key(self, verkey: str) -> KeyInfo: - """ - Fetch info for a signing keypair. + """Fetch info for a signing keypair. Args: verkey: The verification key of the keypair @@ -233,8 +231,7 @@ async def get_signing_key(self, verkey: str) -> KeyInfo: return await self.__get_keypair_signing_key(verkey) async def replace_signing_key_metadata(self, verkey: str, metadata: dict): - """ - Replace the metadata associated with a signing keypair. + """Replace the metadata associated with a signing keypair. Args: verkey: The verification key of the keypair @@ -262,8 +259,7 @@ async def replace_signing_key_metadata(self, verkey: str, metadata: dict): ) async def rotate_did_keypair_start(self, did: str, next_seed: str = None) -> str: - """ - Begin key rotation for DID that wallet owns: generate new keypair. + """Begin key rotation for DID that wallet owns: generate new keypair. Args: did: signing DID @@ -302,8 +298,7 @@ async def rotate_did_keypair_start(self, did: str, next_seed: str = None) -> str return verkey async def rotate_did_keypair_apply(self, did: str) -> DIDInfo: - """ - Apply temporary keypair as main for DID that wallet owns. + """Apply temporary keypair as main for DID that wallet owns. Args: did: signing DID @@ -424,8 +419,7 @@ async def create_local_did( did: str = None, metadata: dict = None, ) -> DIDInfo: - """ - Create and store a new local DID. + """Create and store a new local DID. Args: method: The method to use for the DID @@ -465,8 +459,7 @@ async def create_local_did( ) async def get_local_dids(self) -> Sequence[DIDInfo]: - """ - Get list of defined local DIDs. + """Get list of defined local DIDs. Returns: A list of locally stored DIDs as `DIDInfo` instances @@ -540,8 +533,7 @@ async def __get_keypair_local_did( return self.__did_info_from_key_pair_info(key_pair) async def get_local_did(self, did: str) -> DIDInfo: - """ - Find info for a local DID. + """Find info for a local DID. Args: did: The DID for which to get info @@ -570,8 +562,7 @@ async def get_local_did(self, did: str) -> DIDInfo: return await self.__get_keypair_local_did(method, key_type, did) async def get_local_did_for_verkey(self, verkey: str) -> DIDInfo: - """ - Resolve a local DID from a verkey. + """Resolve a local DID from a verkey. Args: verkey: The verkey for which to get the local DID @@ -591,8 +582,7 @@ async def get_local_did_for_verkey(self, verkey: str) -> DIDInfo: raise WalletNotFoundError("No DID defined for verkey: {}".format(verkey)) async def replace_local_did_metadata(self, did: str, metadata: dict): - """ - Replace metadata for a local DID. + """Replace metadata for a local DID. Args: did: The DID for which to replace metadata @@ -621,8 +611,7 @@ async def replace_local_did_metadata(self, did: str, metadata: dict): ) async def get_public_did(self) -> DIDInfo: - """ - Retrieve the public DID. + """Retrieve the public DID. Returns: The currently public `DIDInfo`, if any @@ -673,8 +662,7 @@ async def get_public_did(self) -> DIDInfo: return public_info async def set_public_did(self, did: Union[str, DIDInfo]) -> DIDInfo: - """ - Assign the public DID. + """Assign the public DID. Returns: The updated `DIDInfo` @@ -717,8 +705,7 @@ async def set_did_endpoint( endorser_did: str = None, routing_keys: List[str] = None, ): - """ - Update the endpoint for a DID in the wallet, send to ledger if public or posted. + """Update the endpoint for a DID in the wallet, send to ledger if posted. Args: did: DID for which to set endpoint @@ -763,8 +750,7 @@ async def set_did_endpoint( await self.replace_local_did_metadata(did, metadata) async def sign_message(self, message: bytes, from_verkey: str) -> bytes: - """ - Sign a message using the private key associated with a given verkey. + """Sign a message using the private key associated with a given verkey. Args: message: Message bytes to sign @@ -816,8 +802,7 @@ async def verify_message( from_verkey: str, key_type: KeyType, ) -> bool: - """ - Verify a signature against the public key of the signer. + """Verify a signature against the public key of the signer. Args: message: Message to verify @@ -867,8 +852,7 @@ async def verify_message( async def pack_message( self, message: str, to_verkeys: Sequence[str], from_verkey: str = None ) -> bytes: - """ - Pack a message for one or more recipients. + """Pack a message for one or more recipients. Args: message: The message to pack @@ -897,8 +881,7 @@ async def pack_message( return result async def unpack_message(self, enc_message: bytes) -> Tuple[str, str, str]: - """ - Unpack a message. + """Unpack a message. Args: enc_message: The packed message bytes diff --git a/aries_cloudagent/wallet/key_pair.py b/aries_cloudagent/wallet/key_pair.py index c5c4a25d42..2a718b8cf5 100644 --- a/aries_cloudagent/wallet/key_pair.py +++ b/aries_cloudagent/wallet/key_pair.py @@ -67,7 +67,7 @@ async def get_key_pair(self, verkey: str) -> dict: StorageDuplicateError: If more than one key pair is found for this verkey StorageNotFoundError: If no key pair is found for this verkey - Returns + Returns: dict: The key pair data """ @@ -88,8 +88,7 @@ async def find_key_pairs(self, tag_query: Optional[Mapping] = None) -> List[dict return [json.loads(record.value) for record in records] async def delete_key_pair(self, verkey: str): - """ - Remove a previously-stored key pair record. + """Remove a previously-stored key pair record. Raises: StorageNotFoundError: If the record is not found @@ -101,8 +100,7 @@ async def delete_key_pair(self, verkey: str): await self._store.delete_record(record) async def update_key_pair_metadata(self, verkey: str, metadata: dict): - """ - Update the metadata of a key pair record by verkey. + """Update the metadata of a key pair record by verkey. Raises: StorageNotFoundError: If the record is not found. diff --git a/aries_cloudagent/wallet/models/tests/test_wallet_record.py b/aries_cloudagent/wallet/models/tests/test_wallet_record.py index 46488044fe..39ea44b224 100644 --- a/aries_cloudagent/wallet/models/tests/test_wallet_record.py +++ b/aries_cloudagent/wallet/models/tests/test_wallet_record.py @@ -89,7 +89,7 @@ async def test_update_settings(self): assert wallet_record.settings.get("wallet.type") == "indy" - async def test_update_settings(self): + async def test_update_settings_x(self): wallet_record = WalletRecord() settings = { "wallet.id": "my-wallet-id", diff --git a/aries_cloudagent/wallet/routes.py b/aries_cloudagent/wallet/routes.py index 64f0e77a07..20dd8727c1 100644 --- a/aries_cloudagent/wallet/routes.py +++ b/aries_cloudagent/wallet/routes.py @@ -369,8 +369,7 @@ def format_did_info(info: DIDInfo): @querystring_schema(DIDListQueryStringSchema()) @response_schema(DIDListSchema, 200, description="") async def wallet_did_list(request: web.BaseRequest): - """ - Request handler for searching wallet DIDs. + """Request handler for searching wallet DIDs. Args: request: aiohttp request object @@ -477,8 +476,7 @@ async def wallet_did_list(request: web.BaseRequest): @request_schema(DIDCreateSchema()) @response_schema(DIDResultSchema, 200, description="") async def wallet_create_did(request: web.BaseRequest): - """ - Request handler for creating a new local DID in the wallet. + """Request handler for creating a new local DID in the wallet. Args: request: aiohttp request object @@ -550,8 +548,7 @@ async def wallet_create_did(request: web.BaseRequest): @docs(tags=["wallet"], summary="Fetch the current public DID") @response_schema(DIDResultSchema, 200, description="") async def wallet_get_public_did(request: web.BaseRequest): - """ - Request handler for fetching the current public DID. + """Request handler for fetching the current public DID. Args: request: aiohttp request object @@ -581,8 +578,7 @@ async def wallet_get_public_did(request: web.BaseRequest): @querystring_schema(MediationIDSchema()) @response_schema(DIDResultSchema, 200, description="") async def wallet_set_public_did(request: web.BaseRequest): - """ - Request handler for setting the current public DID. + """Request handler for setting the current public DID. Args: request: aiohttp request object @@ -796,8 +792,7 @@ async def promote_wallet_public_did( @querystring_schema(AttribConnIdMatchInfoSchema()) @response_schema(WalletModuleResponseSchema(), description="") async def wallet_set_did_endpoint(request: web.BaseRequest): - """ - Request handler for setting an endpoint for a DID. + """Request handler for setting an endpoint for a DID. Args: request: aiohttp request object @@ -916,8 +911,7 @@ async def wallet_set_did_endpoint(request: web.BaseRequest): @request_schema(JWSCreateSchema) @response_schema(WalletModuleResponseSchema(), description="") async def wallet_jwt_sign(request: web.BaseRequest): - """ - Request handler for jws creation using did. + """Request handler for jws creation using did. Args: "headers": { ... }, @@ -951,8 +945,7 @@ async def wallet_jwt_sign(request: web.BaseRequest): @request_schema(JWSVerifySchema()) @response_schema(JWSVerifyResponseSchema(), 200, description="") async def wallet_jwt_verify(request: web.BaseRequest): - """ - Request handler for jws validation using did. + """Request handler for jws validation using did. Args: "jwt": { ... } @@ -981,8 +974,7 @@ async def wallet_jwt_verify(request: web.BaseRequest): @querystring_schema(DIDQueryStringSchema()) @response_schema(DIDEndpointSchema, 200, description="") async def wallet_get_did_endpoint(request: web.BaseRequest): - """ - Request handler for getting the current DID endpoint from the wallet. + """Request handler for getting the current DID endpoint from the wallet. Args: request: aiohttp request object @@ -1015,8 +1007,7 @@ async def wallet_get_did_endpoint(request: web.BaseRequest): @querystring_schema(DIDQueryStringSchema()) @response_schema(WalletModuleResponseSchema(), description="") async def wallet_rotate_did_keypair(request: web.BaseRequest): - """ - Request handler for rotating local DID keypair. + """Request handler for rotating local DID keypair. Args: request: aiohttp request object diff --git a/aries_cloudagent/wallet/tests/test_did_method.py b/aries_cloudagent/wallet/tests/test_did_method.py index a952844383..8368855475 100644 --- a/aries_cloudagent/wallet/tests/test_did_method.py +++ b/aries_cloudagent/wallet/tests/test_did_method.py @@ -32,7 +32,7 @@ def test_from_multicodec_name(self): assert ( key_types.from_multicodec_name(BLS12381G1G2_MULTICODEC_NAME) == BLS12381G1G2 ) - assert key_types.from_multicodec_name("non-existing") == None + assert key_types.from_multicodec_name("non-existing") is None def test_from_key_type(self): key_types = KeyTypes() @@ -41,7 +41,7 @@ def test_from_key_type(self): assert key_types.from_key_type(BLS12381G1_KEY_NAME) == BLS12381G1 assert key_types.from_key_type(BLS12381G2_KEY_NAME) == BLS12381G2 assert key_types.from_key_type(BLS12381G1G2_KEY_NAME) == BLS12381G1G2 - assert key_types.from_key_type("non-existing") == None + assert key_types.from_key_type("non-existing") is None def test_from_multicodec_prefix(self): key_types = KeyTypes() @@ -52,7 +52,7 @@ def test_from_multicodec_prefix(self): assert ( key_types.from_multicodec_prefix(BLS12381G1G2_PREFIX_BYTES) == BLS12381G1G2 ) - assert key_types.from_multicodec_prefix(b"\xef\x01") == None + assert key_types.from_multicodec_prefix(b"\xef\x01") is None def test_from_prefixed_bytes(self): key_types = KeyTypes() @@ -90,7 +90,7 @@ def test_from_prefixed_bytes(self): key_types.from_prefixed_bytes( b"".join([b"\xef\x01", b"other-random-bytes"]) ) - == None + is None ) def test_properties(self): diff --git a/aries_cloudagent/wallet/tests/test_did_posture.py b/aries_cloudagent/wallet/tests/test_did_posture.py index 387db2642f..85aa498d15 100644 --- a/aries_cloudagent/wallet/tests/test_did_posture.py +++ b/aries_cloudagent/wallet/tests/test_did_posture.py @@ -19,7 +19,7 @@ async def test_did_posture(self): ) assert DIDPosture.WALLET_ONLY is DIDPosture.get({}) - postures = [posture for posture in DIDPosture] + postures = list(DIDPosture) postures.sort(key=lambda p: p.ordinal) assert postures == [ DIDPosture.PUBLIC, diff --git a/aries_cloudagent/wallet/tests/test_in_memory_wallet.py b/aries_cloudagent/wallet/tests/test_in_memory_wallet.py index 2558f60914..4b7c6f0d3f 100644 --- a/aries_cloudagent/wallet/tests/test_in_memory_wallet.py +++ b/aries_cloudagent/wallet/tests/test_in_memory_wallet.py @@ -341,7 +341,7 @@ async def test_create_public_did(self, wallet: InMemoryWallet): assert info_check.metadata.get("posted") posted = await wallet.get_posted_dids() - assert len(posted) == 2 and set(p.did for p in posted) == { + assert len(posted) == 2 and {p.did for p in posted} == { info_public.did, info_replace.did, } diff --git a/aries_cloudagent/wallet/tests/test_jwt.py b/aries_cloudagent/wallet/tests/test_jwt.py index 3cc18b11e3..289c65901f 100644 --- a/aries_cloudagent/wallet/tests/test_jwt.py +++ b/aries_cloudagent/wallet/tests/test_jwt.py @@ -1,4 +1,3 @@ -from unittest import TestCase import pytest from aries_cloudagent.resolver.did_resolver import DIDResolver from aries_cloudagent.resolver.tests.test_did_resolver import MockResolver diff --git a/aries_cloudagent/wallet/tests/test_key_type.py b/aries_cloudagent/wallet/tests/test_key_type.py index 67730cbc55..6535c851d0 100644 --- a/aries_cloudagent/wallet/tests/test_key_type.py +++ b/aries_cloudagent/wallet/tests/test_key_type.py @@ -45,5 +45,5 @@ def test_properties(self): assert method.supported_key_types == SOV_SUPPORTED_KEY_TYPES assert method.supports_rotation is True - assert method.supports_key_type(ED25519) == True - assert method.supports_key_type(BLS12381G2) == False + assert method.supports_key_type(ED25519) is True + assert method.supports_key_type(BLS12381G2) is False diff --git a/aries_cloudagent/wallet/tests/test_routes.py b/aries_cloudagent/wallet/tests/test_routes.py index 74a755cc09..71ea617792 100644 --- a/aries_cloudagent/wallet/tests/test_routes.py +++ b/aries_cloudagent/wallet/tests/test_routes.py @@ -1,5 +1,4 @@ import mock as async_mock -import pytest from aiohttp.web import HTTPForbidden from unittest import IsolatedAsyncioTestCase diff --git a/aries_cloudagent/wallet/util.py b/aries_cloudagent/wallet/util.py index 942744bca8..1d629325a8 100644 --- a/aries_cloudagent/wallet/util.py +++ b/aries_cloudagent/wallet/util.py @@ -12,8 +12,7 @@ def random_seed() -> bytes: - """ - Generate a random seed value. + """Generate a random seed value. Returns: A new random seed diff --git a/poetry.lock b/poetry.lock index b34f70efe8..090dcc83dd 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,4 +1,4 @@ -# This file is automatically @generated by Poetry 1.5.1 and should not be changed by hand. +# This file is automatically @generated by Poetry 1.6.1 and should not be changed by hand. [[package]] name = "aiohttp" @@ -270,7 +270,7 @@ test = ["flake8 (>=3.9.2,<3.10.0)", "pycodestyle (>=2.7.0,<2.8.0)", "uvloop (>=0 name = "asynctest" version = "0.13.0" description = "Enhance the standard unittest package with features for testing asyncio libraries" -optional = true +optional = false python-versions = ">=3.5" files = [ {file = "asynctest-0.13.0-py3-none-any.whl", hash = "sha256:5da6118a7e6d6b54d83a8f7197769d046922a44d2a99c21382f0a6e4fadae676"}, @@ -590,7 +590,7 @@ yaml = ["PyYAML"] name = "coverage" version = "7.3.0" description = "Code coverage measurement for Python" -optional = true +optional = false python-versions = ">=3.8" files = [ {file = "coverage-7.3.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:db76a1bcb51f02b2007adacbed4c88b6dee75342c37b05d1822815eed19edee5"}, @@ -883,7 +883,7 @@ test = ["hypothesis (>=4.43.0,<5.0.0)", "pytest (==5.4.1)", "pytest-xdist", "tox name = "exceptiongroup" version = "1.1.3" description = "Backport of PEP 654 (exception groups)" -optional = true +optional = false python-versions = ">=3.7" files = [ {file = "exceptiongroup-1.1.3-py3-none-any.whl", hash = "sha256:343280667a4585d195ca1cf9cef84a4e178c4b6cf2274caef9859782b567d5e3"}, @@ -908,51 +908,6 @@ files = [ docs = ["furo (>=2023.5.20)", "sphinx (>=7.0.1)", "sphinx-autodoc-typehints (>=1.23,!=1.23.4)"] testing = ["covdefaults (>=2.3)", "coverage (>=7.2.7)", "diff-cover (>=7.5)", "pytest (>=7.3.1)", "pytest-cov (>=4.1)", "pytest-mock (>=3.10)", "pytest-timeout (>=2.1)"] -[[package]] -name = "flake8" -version = "4.0.1" -description = "the modular source code checker: pep8 pyflakes and co" -optional = false -python-versions = ">=3.6" -files = [ - {file = "flake8-4.0.1-py2.py3-none-any.whl", hash = "sha256:479b1304f72536a55948cb40a32dce8bb0ffe3501e26eaf292c7e60eb5e0428d"}, - {file = "flake8-4.0.1.tar.gz", hash = "sha256:806e034dda44114815e23c16ef92f95c91e4c71100ff52813adf7132a6ad870d"}, -] - -[package.dependencies] -mccabe = ">=0.6.0,<0.7.0" -pycodestyle = ">=2.8.0,<2.9.0" -pyflakes = ">=2.4.0,<2.5.0" - -[[package]] -name = "flake8-docstrings" -version = "1.7.0" -description = "Extension for flake8 which uses pydocstyle to check docstrings" -optional = false -python-versions = ">=3.7" -files = [ - {file = "flake8_docstrings-1.7.0-py2.py3-none-any.whl", hash = "sha256:51f2344026da083fc084166a9353f5082b01f72901df422f74b4d953ae88ac75"}, - {file = "flake8_docstrings-1.7.0.tar.gz", hash = "sha256:4c8cc748dc16e6869728699e5d0d685da9a10b0ea718e090b1ba088e67a941af"}, -] - -[package.dependencies] -flake8 = ">=3" -pydocstyle = ">=2.1" - -[[package]] -name = "flake8-rst" -version = "0.7.2" -description = "flake8 for code in rst files and docstrings" -optional = false -python-versions = "*" -files = [ - {file = "flake8-rst-0.7.2.tar.gz", hash = "sha256:9d7c42ef63da78cde1dc16d712b9eb1e0d2e4374483f7cbf4e8bc975af4d9b3f"}, - {file = "flake8_rst-0.7.2-py3-none-any.whl", hash = "sha256:0b69230be2990ad25e21bb2d4300fbf72c3eb21af85f6ca54a13d7845dc18a6b"}, -] - -[package.dependencies] -flake8 = ">=3.5.0" - [[package]] name = "frozendict" version = "2.3.8" @@ -1145,7 +1100,7 @@ files = [ name = "iniconfig" version = "2.0.0" description = "brain-dead simple config-ini parsing" -optional = true +optional = false python-versions = ">=3.7" files = [ {file = "iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"}, @@ -1425,22 +1380,11 @@ docs = ["alabaster (==0.7.13)", "autodocsumm (==0.2.11)", "sphinx (==7.0.1)", "s lint = ["flake8 (==6.0.0)", "flake8-bugbear (==23.7.10)", "mypy (==1.4.1)", "pre-commit (>=2.4,<4.0)"] tests = ["pytest", "pytz", "simplejson"] -[[package]] -name = "mccabe" -version = "0.6.1" -description = "McCabe checker, plugin for flake8" -optional = false -python-versions = "*" -files = [ - {file = "mccabe-0.6.1-py2.py3-none-any.whl", hash = "sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42"}, - {file = "mccabe-0.6.1.tar.gz", hash = "sha256:dd8d182285a0fe56bace7f45b5e7d1a6ebcbf524e8f3bd87eb0f125271b8831f"}, -] - [[package]] name = "mock" version = "4.0.3" description = "Rolling backport of unittest.mock for all Pythons" -optional = true +optional = false python-versions = ">=3.6" files = [ {file = "mock-4.0.3-py3-none-any.whl", hash = "sha256:122fcb64ee37cfad5b3f48d7a7d51875d7031aaf3d8be7c42e2bee25044eee62"}, @@ -1780,7 +1724,7 @@ test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest (>=7.4)", "pytest-co name = "pluggy" version = "1.2.0" description = "plugin and hook calling mechanisms for python" -optional = true +optional = false python-versions = ">=3.7" files = [ {file = "pluggy-1.2.0-py3-none-any.whl", hash = "sha256:c2fd55a7d7a3863cba1a013e4e2414658b1d07b6bc57b3919e0c63c9abb99849"}, @@ -1889,17 +1833,6 @@ files = [ {file = "ptvsd-4.3.2.zip", hash = "sha256:3b05c06018fdbce5943c50fb0baac695b5c11326f9e21a5266c854306bda28ab"}, ] -[[package]] -name = "pycodestyle" -version = "2.8.0" -description = "Python style guide checker" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -files = [ - {file = "pycodestyle-2.8.0-py2.py3-none-any.whl", hash = "sha256:720f8b39dde8b293825e7ff02c475f3077124006db4f440dcbc9a20b76548a20"}, - {file = "pycodestyle-2.8.0.tar.gz", hash = "sha256:eddd5847ef438ea1c7870ca7eb78a9d47ce0cdb4851a5523949f2601d0cbbe7f"}, -] - [[package]] name = "pycparser" version = "2.21" @@ -2008,34 +1941,6 @@ inflection = ">=0.5.1,<0.6.0" pydantic = ">=1.8.1,<2.0.0" typing-extensions = ">=4.0.0,<4.1.0" -[[package]] -name = "pydocstyle" -version = "6.3.0" -description = "Python docstring style checker" -optional = false -python-versions = ">=3.6" -files = [ - {file = "pydocstyle-6.3.0-py3-none-any.whl", hash = "sha256:118762d452a49d6b05e194ef344a55822987a462831ade91ec5c06fd2169d019"}, - {file = "pydocstyle-6.3.0.tar.gz", hash = "sha256:7ce43f0c0ac87b07494eb9c0b462c0b73e6ff276807f204d6b53edc72b7e44e1"}, -] - -[package.dependencies] -snowballstemmer = ">=2.2.0" - -[package.extras] -toml = ["tomli (>=1.2.3)"] - -[[package]] -name = "pyflakes" -version = "2.4.0" -description = "passive checker of Python programs" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "pyflakes-2.4.0-py2.py3-none-any.whl", hash = "sha256:3bb3a3f256f4b7968c9c788781e4ff07dce46bdf12339dcda61053375426ee2e"}, - {file = "pyflakes-2.4.0.tar.gz", hash = "sha256:05a85c2872edf37a4ed30b0cce2f6093e1d0581f8c19d7393122da7e25b2b24c"}, -] - [[package]] name = "pygments" version = "2.16.1" @@ -2118,7 +2023,7 @@ tests = ["hypothesis (>=3.27.0)", "pytest (>=3.2.1,!=3.3.0)"] name = "pytest" version = "7.4.0" description = "pytest: simple powerful testing with Python" -optional = true +optional = false python-versions = ">=3.7" files = [ {file = "pytest-7.4.0-py3-none-any.whl", hash = "sha256:78bf16451a2eb8c7a2ea98e32dc119fd2aa758f1d5d66dbf0a59d69a3969df32"}, @@ -2140,7 +2045,7 @@ testing = ["argcomplete", "attrs (>=19.2.0)", "hypothesis (>=3.56)", "mock", "no name = "pytest-asyncio" version = "0.14.0" description = "Pytest support for asyncio." -optional = true +optional = false python-versions = ">= 3.5" files = [ {file = "pytest-asyncio-0.14.0.tar.gz", hash = "sha256:9882c0c6b24429449f5f969a5158b528f39bde47dc32e85b9f0403965017e700"}, @@ -2157,7 +2062,7 @@ testing = ["async-generator (>=1.3)", "coverage", "hypothesis (>=5.7.1)"] name = "pytest-cov" version = "2.10.1" description = "Pytest plugin for measuring coverage." -optional = true +optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" files = [ {file = "pytest-cov-2.10.1.tar.gz", hash = "sha256:47bd0ce14056fdd79f93e1713f88fad7bdcc583dcd7783da86ef2f085a0bb88e"}, @@ -2172,19 +2077,18 @@ pytest = ">=4.6" testing = ["fields", "hunter", "process-tests (==2.0.2)", "pytest-xdist", "six", "virtualenv"] [[package]] -name = "pytest-flake8" -version = "1.1.1" -description = "pytest plugin to check FLAKE8 requirements" -optional = true -python-versions = "*" +name = "pytest-ruff" +version = "0.1.1" +description = "pytest plugin to check ruff requirements." +optional = false +python-versions = ">=3.7,<4.0" files = [ - {file = "pytest-flake8-1.1.1.tar.gz", hash = "sha256:ba4f243de3cb4c2486ed9e70752c80dd4b636f7ccb27d4eba763c35ed0cd316e"}, - {file = "pytest_flake8-1.1.1-py2.py3-none-any.whl", hash = "sha256:e0661a786f8cbf976c185f706fdaf5d6df0b1667c3bcff8e823ba263618627e7"}, + {file = "pytest_ruff-0.1.1-py3-none-any.whl", hash = "sha256:db33c8d32d730d61d372c1ac4615b1036c47a14c781cbc0ae71811c4cadadc47"}, + {file = "pytest_ruff-0.1.1.tar.gz", hash = "sha256:f599768ff3834d6b1d6d26b25a030a5b1dcc9cf187239bd9621a7f25f7d8fe46"}, ] [package.dependencies] -flake8 = ">=4.0" -pytest = ">=7.0" +ruff = ">=0.0.242" [[package]] name = "python-dateutil" @@ -2373,6 +2277,32 @@ doc = ["Sphinx (>=1.6.5,<2)", "sphinx-rtd-theme (>=0.1.9)"] lint = ["flake8 (==3.4.1)"] test = ["hypothesis (==3.56.5)", "pytest (==3.3.2)", "tox (>=2.9.1,<3)"] +[[package]] +name = "ruff" +version = "0.0.285" +description = "An extremely fast Python linter, written in Rust." +optional = false +python-versions = ">=3.7" +files = [ + {file = "ruff-0.0.285-py3-none-macosx_10_7_x86_64.whl", hash = "sha256:72a3a0936369b986b0e959f9090206ed3c18f9e5e439ea5b8e6867c6707aded5"}, + {file = "ruff-0.0.285-py3-none-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl", hash = "sha256:0d9ab6ad16742eb78919e0fba09f914f042409df40ad63423c34bb20d350162a"}, + {file = "ruff-0.0.285-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6c48926156288b8ac005eb1db5e77c15e8a37309ae49d9fb6771d5cf5f777590"}, + {file = "ruff-0.0.285-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:1d2a60c102e7a5e147b58fc2cbea12a563c565383effc527c987ea2086a05742"}, + {file = "ruff-0.0.285-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b02aae62f922d088bb01943e1dbd861688ada13d735b78b8348a7d90121fd292"}, + {file = "ruff-0.0.285-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:f572c4296d8c7ddd22c3204de4031965be524fdd1fdaaef273945932912b28c5"}, + {file = "ruff-0.0.285-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:80effdf4fe69763d69eb4ab9443e186fd09e668b59fe70ba4b49f4c077d15a1b"}, + {file = "ruff-0.0.285-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5977ce304da35c263f5e082901bd7ac0bd2be845a8fcfd1a29e4d6680cddb307"}, + {file = "ruff-0.0.285-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:72a087712d474fa17b915d7cb9ef807e1256182b12ddfafb105eb00aeee48d1a"}, + {file = "ruff-0.0.285-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:7ce67736cd8dfe97162d1e7adfc2d9a1bac0efb9aaaff32e4042c7cde079f54b"}, + {file = "ruff-0.0.285-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:5473a4c6cac34f583bff08c5f63b8def5599a0ea4dc96c0302fbd2cc0b3ecbad"}, + {file = "ruff-0.0.285-py3-none-musllinux_1_2_i686.whl", hash = "sha256:e6b1c961d608d373a032f047a20bf3c55ad05f56c32e7b96dcca0830a2a72348"}, + {file = "ruff-0.0.285-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:2933cc9631f453305399c7b8fb72b113ad76b49ae1d7103cc4afd3a423bed164"}, + {file = "ruff-0.0.285-py3-none-win32.whl", hash = "sha256:770c5eb6376de024111443022cda534fb28980a9dd3b4abc83992a8770167ba6"}, + {file = "ruff-0.0.285-py3-none-win_amd64.whl", hash = "sha256:a8c6ad6b9cd77489bf6d1510950cbbe47a843aa234adff0960bae64bd06c3b6d"}, + {file = "ruff-0.0.285-py3-none-win_arm64.whl", hash = "sha256:de44fbc6c3b25fccee473ddf851416fd4e246fc6027b2197c395b1b3b3897921"}, + {file = "ruff-0.0.285.tar.gz", hash = "sha256:45866048d1dcdcc80855998cb26c4b2b05881f9e043d2e3bfe1aa36d9a2e8f28"}, +] + [[package]] name = "setuptools" version = "68.1.2" @@ -2605,7 +2535,7 @@ test = ["Sphinx", "pytest", "sqlalchemy", "whoosh"] name = "tomli" version = "2.0.1" description = "A lil' TOML parser" -optional = true +optional = false python-versions = ">=3.7" files = [ {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"}, @@ -2846,9 +2776,8 @@ multidict = ">=4.0" askar = ["aries-askar", "indy-credx", "indy-vdr"] bbs = ["ursa-bbs-signatures"] indy = ["python3-indy"] -test = ["asynctest", "mock", "pytest", "pytest-asyncio", "pytest-cov", "pytest-flake8"] [metadata] lock-version = "2.0" python-versions = "^3.9" -content-hash = "e416cad4056b84f383973bfae34570cddf638cb92bc27494a80cd8a50be28b4f" +content-hash = "61b6b1c547647c9ea6a369aa236059f4de525b65dc1780430c3a20ff852d51a9" diff --git a/pyproject.toml b/pyproject.toml index 2decb9f2e0..7c5bc24d29 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -64,13 +64,9 @@ ursa-bbs-signatures= { version = "~1.0.1", optional = true } python3-indy= { version = "^1.11.1", optional = true } [tool.poetry.group.dev.dependencies] -flake8="4.0.1" -# flake8-rst-docstrings=0.0.8 -flake8-docstrings="~1.7.0" -flake8-rst="0.7.2" pre-commit="~3.3.3" +ruff="^0.0.285" -pydocstyle="~6.3.0" sphinx="1.8.4" sphinx-rtd-theme=">=0.4.3" @@ -84,7 +80,7 @@ asynctest= "0.13.0" pytest= "~7.4.0" pytest-asyncio= "0.14.0" pytest-cov= "2.10.1" -pytest-flake8= "1.1.1" +pytest-ruff="^0.1.1" mock= "~4.0" [tool.poetry.extras] @@ -103,6 +99,65 @@ indy = [ [tool.poetry.scripts] aca-py = "aries_cloudagent.__main__:script_main" +[tool.ruff] +select = ["E", "F", "C", "D"] + +ignore = [ + # Google Python Doc Style + "D203", "D204", "D213", "D215", "D400", "D401", "D404", "D406", "D407", + "D408", "D409", "D413", + "D202", # Allow blank line after docstring + "D104", # Don't require docstring in public package + # Things that we should fix, but are too much work right now + "D417", "C901", +] + +line-length = 90 + +[tool.ruff.per-file-ignores] +"**/{tests}/*" = ["F841", "D", "E501"] + +[tool.pytest.ini_options] +testpaths = "aries_cloudagent" +addopts = """ + --quiet --junitxml=./test-reports/junit.xml + --cov-config .coveragerc --cov=aries_cloudagent --cov-report term --cov-report xml + --ruff +""" +markers = [ + "askar: Tests specifically relating to Aries-Askar support", + "indy: Tests specifically relating to Hyperledger Indy SDK support", + "indy_credx: Tests specifically relating to Indy-Credx support", + "indy_vdr: Tests specifically relating to Indy-VDR support", + "ursa_bbs_signatures: Tests specificaly relating to BBS Signatures support", + "postgres: Tests relating to the postgres storage plugin for Indy", +] +junit_family = "xunit1" +asyncio_mode = "auto" + +[tool.coverage.run] + +omit = [ + "*/tests/*", + "demo/*", + "docker/*", + "docs/*", + "scripts/*", +] +data_file = "test-reports/.coverage" + +[tool.coverage.report] +exclude_lines = [ + "pragma: no cover", + "@abstract" +] +precision = 2 +skip_covered = true +show_missing = true + +[tool.coverage.xml] +output = "test-reports/coverage.xml" + [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index f96dbb91be..0000000000 --- a/setup.cfg +++ /dev/null @@ -1,43 +0,0 @@ -[tool:pytest] -testpaths = aries_cloudagent -addopts = - --quiet --junitxml=./test-reports/junit.xml - --cov-config .coveragerc --cov=aries_cloudagent --cov-report term --cov-report xml - --flake8 -markers = - askar: Tests specifically relating to Aries-Askar support - indy: Tests specifically relating to Hyperledger Indy SDK support - indy_credx: Tests specifically relating to Indy-Credx support - indy_vdr: Tests specifically relating to Indy-VDR support - ursa_bbs_signatures: Tests specificaly relating to BBS Signatures support - postgres: Tests relating to the postgres storage plugin for Indy -junit_family = xunit1 -asyncio_mode = auto - -[flake8] -# https://github.com/ambv/black#line-length -max-line-length = 90 -exclude = - */tests/** -extend_ignore = D202, W503 -per_file_ignores = */__init__.py:D104 - -[coverage:run] -omit = - */tests/* - demo/* - docker/* - docs/* - scripts/* -data_file = test-reports/.coverage - -[coverage:report] -exclude_lines = - pragma: no cover - @abstract -precision = 2 -skip_covered = True -show_missing = True - -[coverage:xml] -output = test-reports/coverage.xml