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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion benchmarks/bench.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async def measure(
) -> AsyncGenerator[MeasureResult, None]:
async with case.start() as start_time:
while (elapsed_time := (time.time() - start_time)) < measure_time:
yield MeasureResult(case.EVENTS_PROCESSED, elapsed_time)
yield MeasureResult(case.EVENTS_PROCESSED, elapsed_time) # ruff: ignore[yield-in-context-manager-in-async-generator]
await asyncio.sleep(1.0)

yield MeasureResult(case.EVENTS_PROCESSED, time.time() - start_time)
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/confluent_cases/test_confluent.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def setup_method(self) -> None:
async def start(self) -> AsyncGenerator[float, None]:
stop_event = asyncio.Event()

def acked(err, msg) -> None: # noqa: ANN001
def acked(err, msg) -> None: # ruff: ignore[missing-type-function-argument]
if err is not None:
print(f"Failed to deliver message: {msg!s}: {err!s}")

Expand Down
7 changes: 4 additions & 3 deletions benchmarks/nats_cases/test_nats.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@ async def message_handler(msg: Any) -> None:
"children": [{"name": "Mike", "age": 8, "fullname": "LongString" * 8}],
}).encode("utf-8"),
)
yield start_time

await nc.close()
try:
yield start_time
finally:
await nc.close()

async def test_consume_message(self) -> None:
async with self.start():
Expand Down
6 changes: 4 additions & 2 deletions benchmarks/rabbit_cases/test_aiopika.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@ async def handler(msg: aio_pika.IncomingMessage) -> None:
routing_key="in",
)

yield start_time
await connection.close()
try:
yield start_time
finally:
await connection.close()

async def test_consume_message(self) -> None:
async with self.start():
Expand Down
2 changes: 1 addition & 1 deletion faststream/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

warnings.filterwarnings("default", category=ImportWarning, module="faststream")

from faststream._internal.cli.main import cli # noqa: E402
from faststream._internal.cli.main import cli # ruff: ignore[module-import-not-at-top-of-file]

if __name__ == "__main__":
cli(prog_name="faststream")
2 changes: 1 addition & 1 deletion faststream/_internal/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def with_info_plain_validator_function( # type: ignore[misc]


if sys.version_info >= (3, 11):
ExceptionGroup = ExceptionGroup # noqa: F821,PLW0127
ExceptionGroup = ExceptionGroup # ruff: ignore[undefined-name, self-assigning-variable]
else:
from exceptiongroup import ExceptionGroup

Expand Down
10 changes: 5 additions & 5 deletions faststream/_internal/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def __init__(
def context(self) -> "ContextRepo":
return self.config.context

def _init_setupable_( # noqa: PLW3201
def _init_setupable_( # ruff: ignore[bad-dunder-method-name]
self,
*brokers: "BrokerUsecase[Any, Any, Any]",
specification: Optional["SpecificationFactory"] = None,
Expand Down Expand Up @@ -249,7 +249,7 @@ async def _start_hooks_context(
for func in self._on_startup_calling:
await func(**run_extra_options)

yield
yield # ruff: ignore[fallible-context-manager]

for func in self._after_startup_calling:
await func()
Expand All @@ -265,7 +265,7 @@ async def _startup_logging(
"FastStream app starting...",
)

yield
yield # ruff: ignore[fallible-context-manager]

self._log(
log_level,
Expand All @@ -292,7 +292,7 @@ async def _shutdown_hooks_context(self) -> AsyncGenerator[None, None]:
for func in self._on_shutdown_calling:
await func()

yield
yield # ruff: ignore[fallible-context-manager]

for func in self._after_shutdown_calling:
await func()
Expand All @@ -305,7 +305,7 @@ async def _shutdown_logging(
"""Separated startup logging."""
self._log(log_level, "FastStream app shutting down...")

yield
yield # ruff: ignore[fallible-context-manager]

self._log(log_level, "FastStream app shut down gracefully.")

Expand Down
4 changes: 2 additions & 2 deletions faststream/_internal/cli/docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
from faststream._internal.cli.utils.imports import import_from_string
from faststream.exceptions import INSTALL_WATCHFILES, INSTALL_YAML, SCHEMA_NOT_SUPPORTED
from faststream.specification.asyncapi.site import serve_app
from faststream.specification.asyncapi.v2_6_0.schema import ( # noqa: TID253
from faststream.specification.asyncapi.v2_6_0.schema import ( # ruff: ignore[banned-module-level-imports]
ApplicationSchema as SchemaV2_6,
)
from faststream.specification.asyncapi.v3_0_0.schema import ( # noqa: TID253
from faststream.specification.asyncapi.v3_0_0.schema import ( # ruff: ignore[banned-module-level-imports]
ApplicationSchema as SchemaV3,
)

Expand Down
2 changes: 1 addition & 1 deletion faststream/_internal/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def run(
"--log-config",
help=(
"Set file to configure logging. Support "
f"{', '.join(f'`{x.value}`' for x in LogFiles)} extensions." # noqa: B008
f"{', '.join(f'`{x.value}`' for x in LogFiles)} extensions." # ruff: ignore[function-call-in-default-argument]
),
show_default=False,
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def init_processes(self) -> None:
self.config._run_extra_options["worker_id"] = i
extra: dict[str, Any] = {"sockets": self.sockets}
if _UVICORN_TAKES_TARGET:
extra["target"] = self.target
extra["target"] = self.target # type: ignore[attr-defined]
process = Process(self.config, **extra)
process.start()
self.processes.append(process)
Expand Down
2 changes: 1 addition & 1 deletion faststream/_internal/configs/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def insert_middleware(self, middleware: "BrokerMiddleware[Any]") -> None:
ConfigType = Union["ConfigComposition[Any]", "BrokerConfigType_co", BrokerConfig]


class ConfigComposition(Generic[BrokerConfigType_co]): # noqa: PLR0904
class ConfigComposition(Generic[BrokerConfigType_co]): # ruff: ignore[too-many-public-methods]
def __init__(self, config: BrokerConfigType_co) -> None:
self.configs: tuple[ConfigType[BrokerConfigType_co], ...] = (config,)

Expand Down
2 changes: 1 addition & 1 deletion faststream/_internal/context/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def resolve(self, argument: str) -> Any:
for context in self._contexts:
try:
return context.resolve(argument)
except ContextError: # noqa: PERF203
except ContextError: # ruff: ignore[try-except-in-loop]
pass

raise ContextError(self.context, first)
Expand Down
2 changes: 1 addition & 1 deletion faststream/_internal/context/context_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def use(self, /, **kwargs: Any) -> dict[str, Any]:
"""
name = f"{self.prefix}{self.name or self.param_name}"

if EMPTY != ( # noqa: SIM300
if EMPTY != ( # ruff: ignore[yoda-conditions]
v := resolve_context_by_name(
name=name,
default=self.default,
Expand Down
2 changes: 1 addition & 1 deletion faststream/_internal/context/resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def resolve_context_by_name(
value = context.resolve(name)

except (KeyError, AttributeError):
if EMPTY != default: # noqa: SIM300
if EMPTY != default: # ruff: ignore[yoda-conditions]
value = default

elif initial is not None:
Expand Down
2 changes: 1 addition & 1 deletion faststream/_internal/endpoint/publisher/specification.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from typing import TYPE_CHECKING, Any

from fast_depends.core import build_call_model
from fast_depends.pydantic._compat import create_model, get_config_base # noqa: PLC2701
from fast_depends.pydantic._compat import create_model, get_config_base # ruff: ignore[import-private-name]
from typing_extensions import TypeVar as TypeVar313

from faststream._internal.configs import BrokerConfig, PublisherSpecificationConfig
Expand Down
6 changes: 3 additions & 3 deletions faststream/_internal/endpoint/subscriber/call_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def _setup(

@property
def name(self) -> str:
"""Returns the name of the original call."""
"""The name of the original call."""
if self.handler is None:
return ""

Expand All @@ -104,7 +104,7 @@ def name(self) -> str:

@property
def description(self) -> str | None:
"""Returns the description of original call."""
"""The description of original call."""
if self.handler is None:
return None

Expand Down Expand Up @@ -168,7 +168,7 @@ def add_call(self, call: "HandlerItem[MsgType]") -> None:

@property
def name(self) -> str | None:
"""Returns the name of the handler call."""
"""The name of the handler call."""
if not self.data:
return None

Expand Down
4 changes: 2 additions & 2 deletions faststream/_internal/endpoint/subscriber/usecase.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ async def consume(self, msg: MsgType) -> Any:
if app := self._outer_config.context.get("app"):
app.exit()

except Exception: # nosec B110 # noqa: S110
except Exception: # nosec B110 # ruff: ignore[try-except-pass]
# All other exceptions were logged by CriticalLogMiddleware
pass

Expand Down Expand Up @@ -499,7 +499,7 @@ def __aiter__(self) -> AsyncIterator["StreamMessage[MsgType]"]:
# which the `async for` protocol does not accept.
raise NotImplementedError

def get_log_context( # noqa: PLR6301
def get_log_context( # ruff: ignore[no-self-use]
self,
message: Optional["StreamMessage[MsgType]"],
) -> dict[str, str]:
Expand Down
4 changes: 2 additions & 2 deletions faststream/_internal/endpoint/subscriber/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,12 @@ def release(self) -> None:

@property
def qsize(self) -> int:
"""Return the size of the queue."""
"""The size of the queue."""
return self.queue.qsize()

@property
def empty(self) -> bool:
"""Return whether the queue is empty."""
"""Whether the queue is empty."""
return self.queue.empty()

async def wait_release(self, timeout: float | None = None) -> None:
Expand Down
4 changes: 2 additions & 2 deletions faststream/_internal/fastapi/_compat.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any

from fastapi import __version__ as FASTAPI_VERSION # noqa: N812
from fastapi import __version__ as FASTAPI_VERSION # ruff: ignore[lowercase-imported-as-non-lowercase]
from fastapi.dependencies.utils import solve_dependencies
from starlette.background import BackgroundTasks
from typing_extensions import Never
Expand Down Expand Up @@ -73,7 +73,7 @@ def raise_fastapi_validation_error(errors: list[Any], body: dict[str, Any]) -> N
ROUTER_VALIDATION_ERROR_MODEL = create_model("StreamRoute")

def raise_fastapi_validation_error(errors: list[Any], body: dict[str, Any]) -> Never:
raise RequestValidationError(errors, ROUTER_VALIDATION_ERROR_MODEL) # type: ignore[misc]
raise RequestValidationError(errors, ROUTER_VALIDATION_ERROR_MODEL) # type: ignore[call-arg]


if FASTAPI_v102_3:
Expand Down
2 changes: 1 addition & 1 deletion faststream/_internal/fastapi/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from faststream._internal.context.resolve import resolve_context_by_name


def Context( # noqa: N802
def Context( # ruff: ignore[invalid-function-name]
name: str,
*,
default: Any = EMPTY,
Expand Down
4 changes: 2 additions & 2 deletions faststream/_internal/fastapi/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from fastapi.utils import generate_unique_id
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.routing import BaseRoute, _DefaultLifespan # noqa: PLC2701
from starlette.routing import BaseRoute, _DefaultLifespan # ruff: ignore[import-private-name]
from typing_extensions import override

from faststream._internal.application import StartAbleApplication
Expand Down Expand Up @@ -398,7 +398,7 @@ def download_app_json_schema() -> Response:
return Response(
# `json_dumps` may be orjson, which takes no `indent`:
# the downloaded schema stays readable
content=json.dumps( # noqa: TID251
content=json.dumps( # ruff: ignore[banned-api]
self.schema.to_specification().to_jsonable(),
indent=2,
),
Expand Down
2 changes: 1 addition & 1 deletion faststream/_internal/logger/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def __init__(
self.use_colors = sys.stdout.isatty()
super().__init__(fmt=fmt, datefmt=datefmt, style=style)

def formatMessage(self, record: logging.LogRecord) -> str: # noqa: N802
def formatMessage(self, record: logging.LogRecord) -> str: # ruff: ignore[invalid-function-name]
"""Formats the log message.

Args:
Expand Down
6 changes: 3 additions & 3 deletions faststream/_internal/middlewares.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def __init__(
async def on_receive(self) -> None:
"""Hook to call on message receive."""

async def after_processed( # noqa: PLR6301
async def after_processed( # ruff: ignore[no-self-use]
self,
exc_type: type[BaseException] | None = None,
exc_val: BaseException | None = None,
Expand All @@ -53,15 +53,15 @@ async def __aexit__(
"""Exit the asynchronous context manager."""
return await self.after_processed(exc_type, exc_val, exc_tb)

async def consume_scope( # noqa: PLR6301
async def consume_scope( # ruff: ignore[no-self-use]
self,
call_next: "AsyncFuncAny",
msg: "StreamMessage[Any]",
) -> Any:
"""Asynchronously consumes a message and returns an asynchronous iterator of decoded messages."""
return await call_next(msg)

async def publish_scope( # noqa: PLR6301
async def publish_scope( # ruff: ignore[no-self-use]
self,
call_next: Callable[[PublishCommandType], Awaitable[Any]],
cmd: PublishCommandType,
Expand Down
4 changes: 2 additions & 2 deletions faststream/_internal/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,10 @@ async def decode_batch(
class DefaultCodec:
__slots__ = ()

async def decode(self, msg: "StreamMessage[Any]") -> "DecodedMessage": # noqa: PLR6301
async def decode(self, msg: "StreamMessage[Any]") -> "DecodedMessage": # ruff: ignore[no-self-use]
return decode_message(msg)

async def encode( # noqa: PLR6301
async def encode( # ruff: ignore[no-self-use]
self,
msg: "SendableMessage",
serializer: "SerializerProto | None" = None,
Expand Down
2 changes: 1 addition & 1 deletion faststream/_internal/proto.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing_extensions import Self


class NameRequired: # noqa: PLW1641 - each subclass decides whether it is hashable
class NameRequired: # ruff: ignore[eq-without-hash] - each subclass decides whether it is hashable
"""Required name option object."""

__slots__ = ("name",)
Expand Down
15 changes: 9 additions & 6 deletions faststream/_internal/testing/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@ def change_producer(
producer: Any,
) -> Generator[None, None, None]:
old_producer, config.producer = config.producer, producer
yield
config.producer = old_producer
try:
yield
finally:
config.producer = old_producer


class TestBroker(Generic[Broker, EnterType]):
Expand Down Expand Up @@ -134,10 +136,11 @@ async def _create_ctx(self) -> AsyncGenerator[list[Broker], None]:
await stack.enter_async_context(self._do_start(broker))
)

yield started_brokers

for sub, was_running in saved_running.items():
sub.running = was_running
try:
yield started_brokers
finally:
for sub, was_running in saved_running.items():
sub.running = was_running

@asynccontextmanager
async def _do_start(self, broker: Broker) -> AsyncGenerator[Broker, None]:
Expand Down
2 changes: 1 addition & 1 deletion faststream/_internal/utils/nuid.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class NUID:
)

def __init__(self) -> None:
self._prand = Random(randbelow(max_int)) # nosec B311 # noqa: S311
self._prand = Random(randbelow(max_int)) # nosec B311 # ruff: ignore[suspicious-non-cryptographic-random-usage]
self._seq = self._prand.randint(0, MAX_SEQ)
self._inc = MIN_INC + self._prand.randint(BASE + 1, INC)
self._prefix = bytearray()
Expand Down
2 changes: 1 addition & 1 deletion faststream/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ async def run(
async with anyio.create_task_group() as tg:
_ = tg.start_soon(self._startup, log_level, run_extra_options)

while not self._should_exit: # noqa: ASYNC110 (requested by creator)
while not self._should_exit: # ruff: ignore[async-busy-wait] (requested by creator)
await anyio.sleep(sleep_time)

await self._shutdown(log_level)
Expand Down
Loading
Loading