Skip to content

Bug: When integrating with FastAPI, Depends cannot be overridden #2922

Description

@Horrih

Describe the bug
Hello,
First of all thank you for your work on faststream, its integration works really well despite the project's young age.

This ticket looks like a duplicate of #2372 but I don't have the rights to reopen it.
I saw this comment #2372 (comment) but could not make it work

Fastapi dependencies work fine, but cannot be overridden.

This is most probably a skill issue on my part, I'd be really grateful for any tip about this issue.

How to reproduce
Here is a minimalist example I tried, I also tried using FastDepends overriding mechanisms but could not make it work

import pytest
import typing
import fastapi
import faststream
from pydantic import BaseModel
from faststream.confluent.fastapi import KafkaRouter
from faststream.confluent import TestKafkaBroker


class ProcessDataCommand(BaseModel):
    user_id: int


router = KafkaRouter("localhost:9092")
app = fastapi.FastAPI()


def my_dependency():
    return "PROD_VERSION"


@router.subscriber("process-data-topic")
async def process_data_handler(
    msg: ProcessDataCommand,
    value: typing.Annotated[
        str,
        fastapi.Depends(my_dependency), # Is not overridden
        faststream.Depends(my_dependency),  # Could not override it either
    ],
):
    print(f"Received message for user {msg.user_id} with my_dependency={value}")


app.include_router(router)


@pytest.mark.asyncio
async def test_process_data_handler_with_mocked_db():
    app.dependency_overrides[my_dependency] = lambda: "TEST_VERSION"
    async with TestKafkaBroker(router.broker) as tester:
        await tester.publish({"user_id": 42}, topic="process-data-topic")
  1. ...

Expected behavior
I expect to be able to override a dependency for testing, either through fastapi's app.dependency_overrides, or FastDepends provider.scope() or equivalent.

Observed behavior
The above snippet always shows the prod message string, not the overridden test one

Screenshots
If applicable, attach screenshots to help illustrate the problem.

Environment
Linux RHEL9 , using uv with "faststream[confluent]>=0.7.1",

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions