Skip to content

Commit

Permalink
Fix ruff edges
Browse files Browse the repository at this point in the history
  • Loading branch information
mephenor committed Sep 29, 2023
1 parent 2a446d3 commit 7074898
Show file tree
Hide file tree
Showing 40 changed files with 220 additions and 368 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ repos:
- id: debug-statements
- id: debug-statements
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.290
rev: v0.0.291
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
Expand Down
4 changes: 2 additions & 2 deletions examples/stream_calc/sc_tests/integration/test_event_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@

import pytest
from kafka import KafkaConsumer, KafkaProducer
from stream_calc.config import Config
from stream_calc.main import main
from testcontainers.kafka import KafkaContainer

from hexkit.custom_types import JsonObject
from stream_calc.config import Config
from stream_calc.main import main

DEFAULT_CONFIG = Config()

Expand Down
1 change: 1 addition & 0 deletions examples/stream_calc/sc_tests/unit/test_calc.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from unittest.mock import AsyncMock

import pytest

from stream_calc.core.calc import StreamCalculator


Expand Down
4 changes: 2 additions & 2 deletions examples/stream_calc/sc_tests/unit/test_eventpub.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@
"""Testing the `translators.eventpub` module."""

import pytest

from hexkit.providers.testing.eventpub import InMemEventPublisher
from stream_calc.translators.eventpub import (
EventResultEmitter,
EventResultEmitterConfig,
)

from hexkit.providers.testing.eventpub import InMemEventPublisher


@pytest.mark.asyncio
async def test_emit_result():
Expand Down
4 changes: 2 additions & 2 deletions examples/stream_calc/sc_tests/unit/test_eventsub.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@
from unittest.mock import AsyncMock

import pytest

from hexkit.custom_types import JsonObject
from stream_calc.translators.eventsub import (
EventProblemReceiver,
EventProblemReceiverConfig,
)

from hexkit.custom_types import JsonObject


@pytest.mark.asyncio
@pytest.mark.parametrize(
Expand Down
3 changes: 1 addition & 2 deletions examples/stream_calc/stream_calc/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@

"""Config parameters."""

from hexkit.providers.akafka import KafkaConfig
from stream_calc.translators.eventpub import EventResultEmitterConfig
from stream_calc.translators.eventsub import EventProblemReceiverConfig

from hexkit.providers.akafka import KafkaConfig

try: # workaround for https://github.com/pydantic/pydantic/issues/5821
from typing_extensions import Literal
except ImportError:
Expand Down
5 changes: 2 additions & 3 deletions examples/stream_calc/stream_calc/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,13 @@
"""Module hosting the dependency injection container."""

# pylint: disable=wrong-import-order
from hexkit.inject import ContainerBase, get_configurator, get_constructor
from hexkit.providers.akafka import KafkaEventPublisher, KafkaEventSubscriber
from stream_calc.config import Config
from stream_calc.core.calc import StreamCalculator
from stream_calc.translators.eventpub import EventResultEmitter
from stream_calc.translators.eventsub import EventProblemReceiver

from hexkit.inject import ContainerBase, get_configurator, get_constructor
from hexkit.providers.akafka import KafkaEventPublisher, KafkaEventSubscriber


class Container(ContainerBase):
"""DI Container"""
Expand Down
4 changes: 2 additions & 2 deletions examples/stream_calc/stream_calc/translators/eventpub.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
"""Translators that target the event publishing protocol."""

from pydantic import BaseSettings
from stream_calc.ports.result_emitter import CalcResultEmitterPort

from hexkit.custom_types import JsonObject
from hexkit.protocols.eventpub import EventPublisherProtocol
from stream_calc.ports.result_emitter import CalcResultEmitterPort


class EventResultEmitterConfig(BaseSettings):
Expand All @@ -39,7 +39,7 @@ def __init__(
self,
*,
config: EventResultEmitterConfig,
event_publisher: EventPublisherProtocol
event_publisher: EventPublisherProtocol,
) -> None:
"""Configure with provider for the the EventPublisherProto"""

Expand Down
2 changes: 1 addition & 1 deletion examples/stream_calc/stream_calc/translators/eventsub.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
"""Translators that target the event publishing protocol."""

from pydantic import BaseSettings
from stream_calc.ports.problem_receiver import ArithProblemHandlerPort

from hexkit.custom_types import Ascii, JsonObject
from hexkit.protocols.eventsub import EventSubscriberProtocol
from stream_calc.ports.problem_receiver import ArithProblemHandlerPort


class EventProblemReceiverConfig(BaseSettings):
Expand Down
19 changes: 8 additions & 11 deletions src/hexkit/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import os
from pathlib import Path
from typing import Any, Callable, Dict, Final, Optional
from typing import Any, Callable, Final, Optional

import yaml
from pydantic import BaseSettings
Expand Down Expand Up @@ -77,7 +77,7 @@ def get_default_config_yaml(prefix: str) -> Optional[Path]:

def yaml_settings_factory(
config_yaml: Optional[Path] = None,
) -> Callable[[BaseSettings], Dict[str, Any]]:
) -> Callable[[BaseSettings], dict[str, Any]]:
"""
A factory of source methods for pydantic's BaseSettings Config that load
settings from a yaml file.
Expand All @@ -89,12 +89,12 @@ def yaml_settings_factory(

def yaml_settings( # pylint: disable=unused-argument
settings: BaseSettings,
) -> Dict[str, Any]:
"""source method for loading pydantic BaseSettings from a yaml file"""
) -> dict[str, Any]:
"""Source method for loading pydantic BaseSettings from a yaml file"""
if config_yaml is None:
return {}

with open(config_yaml, "r", encoding="utf8") as yaml_file:
with open(config_yaml, encoding="utf8") as yaml_file:
return yaml.safe_load(yaml_file)

return yaml_settings
Expand Down Expand Up @@ -136,7 +136,6 @@ def decorator(settings) -> Callable:
settings (BaseSettings):
A pydantic BaseSettings class to be modified.
"""

# check if settings inherits from pydantic BaseSettings:
if not issubclass(settings, BaseSettings):
raise TypeError(
Expand All @@ -153,13 +152,11 @@ def constructor_wrapper(
config_yaml (str, optional):
Path to a config yaml. Overwrites the default location.
"""

# get default path if config_yaml not specified:
if config_yaml is None:
config_yaml = get_default_config_yaml(prefix)
else:
if not config_yaml.is_file():
raise ConfigYamlDoesNotExist(path=config_yaml)
elif not config_yaml.is_file():
raise ConfigYamlDoesNotExist(path=config_yaml)

class ModSettings(settings):
"""Modifies the orginal Settings class provided by the user"""
Expand All @@ -181,7 +178,7 @@ def customise_sources(
env_settings,
file_secret_settings,
):
"""add custom yaml source"""
"""Add custom yaml source"""
return (
init_settings,
env_settings,
Expand Down
26 changes: 12 additions & 14 deletions src/hexkit/inject.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ class NotConstructableError(TypeError):

class AsyncInitShutdownError(TypeError):
"""Thrown when a container has sync `init_resource` or `shutdown_resource` methods
but coroutines are needed."""
but coroutines are needed.
"""


def assert_async_constructable(
Expand All @@ -68,7 +69,6 @@ def assert_async_constructable(
not check whether `construct` really returns an awaitable or an async context
manager.
"""

if not callable(getattr(constructable, "construct", None)):
raise NotConstructableError(
"Async(Context)Constructable class must have a callable `construct` attribute."
Expand All @@ -77,7 +77,8 @@ def assert_async_constructable(

class AsyncConstructor(dependency_injector.providers.Resource):
"""Maps an Async(Context)Constructable onto the Resource class from the
`dependency_injector` framework."""
`dependency_injector` framework.
"""

@staticmethod
def constructable_to_resource(
Expand All @@ -87,7 +88,6 @@ def constructable_to_resource(
Converts an Async(Context)Constructable to an async generator that is compatible
with the Resource definition of the `dependency_injector` framework.
"""

assert_async_constructable(constructable)

async def resource(*args: Any, **kwargs: Any) -> AsyncIterator[Any]:
Expand Down Expand Up @@ -120,7 +120,6 @@ def __init__(
**kwargs: dependency_injector.providers.Injection,
):
"""Initialize `dependency_injector`'s Resource with an AbstractAsyncContextManager."""

if provides is None:
super().__init__()
else:
Expand All @@ -130,8 +129,8 @@ def __init__(

def get_constructor(provides: type, *args, **kwargs):
"""Automatically selects and applies the right constructor for the class given to
`provides`."""

`provides`.
"""
constructor_cls: type

try:
Expand All @@ -148,11 +147,11 @@ def get_constructor(provides: type, *args, **kwargs):

class CMDynamicContainer(dependency_injector.containers.DynamicContainer):
"""Adds a async context manager interface to the DynamicContainer base class from
the `dependency_injector` framework."""
the `dependency_injector` framework.
"""

async def __aenter__(self):
"""Init/setup resources."""

init_future = self.init_resources()

if not inspect.isawaitable(init_future):
Expand All @@ -165,7 +164,6 @@ async def __aenter__(self):

async def __aexit__(self, exc_type, exc_value, exc_trace):
"""Shutdown/teardown resources"""

shutdown_future = self.shutdown_resources()

if not inspect.isawaitable(shutdown_future):
Expand Down Expand Up @@ -206,11 +204,11 @@ async def __aexit__(self, exc_type, exc_value, exc_trace):

class Configurator(dependency_injector.providers.Factory, Generic[PydanticConfig]):
"""A configuration constructor that holds configuration parameters using a pydantic
model."""
model.
"""

def load_config(self, config: PydanticConfig):
"""Loading config parameters form an pydantic config instance."""

self.override(dependency_injector.providers.Callable(lambda: config))


Expand All @@ -220,6 +218,6 @@ def get_configurator(
"""Initializes a configuration provider.
This helper function is necessary because the __init__ of Providers used by the
dependency_injector framework need to always use the same signature."""

dependency_injector framework need to always use the same signature.
"""
return Configurator[PydanticConfig](pydantic_cls)
31 changes: 18 additions & 13 deletions src/hexkit/protocols/dao.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
#

"""Protocol for creating Data Access Objects to perform CRUD (plus find) interactions
with the database."""
with the database.
"""

# ruff: noqa: PLR0913

import typing
from abc import ABC, abstractmethod
Expand Down Expand Up @@ -72,7 +75,8 @@ class InvalidFindMappingError(FindError):

class MultipleHitsFoundError(FindError):
"""Raised when a DAO find operation did result in multiple hits while only a
single hit was expected."""
single hit was expected.
"""

def __init__(self, *, mapping: Mapping[str, str]):
message = (
Expand All @@ -84,7 +88,8 @@ def __init__(self, *, mapping: Mapping[str, str]):

class NoHitsFoundError(FindError):
"""Raised when a DAO find operation did result in no hits while a
single hit was expected."""
single hit was expected.
"""

def __init__(self, *, mapping: Mapping[str, str]):
message = (
Expand Down Expand Up @@ -259,7 +264,6 @@ async def uuid4_id_generator() -> AsyncGenerator[str, None]:
This is an AsyncGenerator to be compliant with the id_generator requirements of the
DaoFactoryProtocol.
"""

while True:
yield str(uuid4())

Expand All @@ -274,16 +278,17 @@ class IdFieldNotFoundError(ValueError):

class CreationModelInvalidError(ValueError):
"""Raised when the DtoCreationModel was invalid in relation to the main
DTO model."""
DTO model.
"""

class IndexFieldsInvalidError(ValueError):
"""Raised when providing an invalid list of fields to index."""

@classmethod
def _validate_dto_model_id(cls, *, dto_model: type[Dto], id_field: str) -> None:
"""Checks whether the dto_model contains the expected id_field.
Raises IdFieldNotFoundError otherwise."""

Raises IdFieldNotFoundError otherwise.
"""
if id_field not in dto_model.schema()["properties"]:
raise cls.IdFieldNotFoundError()

Expand All @@ -296,8 +301,8 @@ def _validate_dto_creation_model(
id_field: str,
) -> None:
"""Checks that the dto_creation_model has the same fields as the dto_model
except missing the ID. Raises CreationModelInvalidError otherwise."""

except missing the ID. Raises CreationModelInvalidError otherwise.
"""
if dto_creation_model is None:
return

Expand All @@ -318,8 +323,8 @@ def _validate_fields_to_index(
fields_to_index: Optional[Collection[str]],
) -> None:
"""Checks that all provided fields are present in the dto_model.
Raises IndexFieldsInvalidError otherwise."""

Raises IndexFieldsInvalidError otherwise.
"""
if fields_to_index is None:
return

Expand Down Expand Up @@ -403,7 +408,6 @@ async def get_dao(
self.IdFieldNotFoundError:
Raised when the dto_model did not contain the expected id_field.
"""

self._validate_dto_model_id(dto_model=dto_model, id_field=id_field)

self._validate_dto_creation_model(
Expand Down Expand Up @@ -470,5 +474,6 @@ async def _get_dao(
id_generator: AsyncGenerator[str, None],
) -> Union[DaoSurrogateId[Dto, DtoCreation], DaoNaturalId[Dto]]:
"""*To be implemented by the provider. Input validation is done outside of this
method.*"""
method.*
"""
...
Loading

0 comments on commit 7074898

Please sign in to comment.