question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Dependency overrides not work in my case

See original GitHub issue

depends_demo.zip

I am getting an error when using dependency_overrides https://fastapi.tiangolo.com/advanced/testing-dependencies/

I have sample project (in attachment) with the following structure:

service.py

from pydantic import BaseModel
class Service(BaseModel):
    key: int
    name: str

handler.py

from service import Service

class ServiceHandler:
    async def get_all(self):
        return [Service(**x) for x in
                [{'key': 1, 'name': 'One'},
                 {'key': 2, 'name': 'Two'}]]

factory.py

from fastapi import Depends
from handler import ServiceHandler

async def get_service_handler(handler=Depends(ServiceHandler)):
    return handler

main.py

from fastapi import FastAPI, APIRouter, Depends
import factory

router = APIRouter()
@router.get("/services/", tags=["services"])
async def get_services(handler=Depends(factory.get_service_handler)):
    return await handler.get_all()

app = FastAPI()
app.include_router(router)

and pytest+pytest-mock unit test for route:

unit_tests/test.py

import...
@pytest.fixture(scope="session", autouse=True)
def client():
    return TestClient(app)

def test_get_services(client, mocker):
    handler = ServiceHandler()
    mocker.patch.object(handler, 'get_all')
    handler.get_all.return_value = [Service(_id=None, key=1, name='Test')]
    app.dependency_overrides[factory.get_service_handler] = handler

    response = client.get("/services")

    assert response.status_code == 200
    # expected = [{'_id': None, 'key': 1, 'name': 'Test'}]
    expected = [{'_id': None, 'key': 1, 'name': 'One'}, {'_id': None, 'key': 2, 'name': 'Two'}]
    assert response.json() == expected

    app.dependency_overrides = {}

When I ran it with: pytest unit_tests/test.py I got an exception: FAILED unit_tests/test.py::test_get_services - TypeError: <handler.ServiceHandler object at 0x7fd03d813b50> is not a callable object

I tried to add call to handler.py as follows

...
class ServiceHandler:
    def __call__(self):
        pass
...

and another exception happened: FAILED unit_tests/test.py::test_get_services - AttributeError: 'NoneType' object has no attribute 'get_all'

After all, if I start the server: hypercorn main:app --reload http://127.0.0.1:8000/services/ everything works well in any way.

If I comment out the line in test.py:

...
app.dependency_overrides[factory.get_service_handler] = handler
...

then the test will work, so I guess the cause of the problem is in dependency_overrides.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

8reactions
Mausecommented, Nov 25, 2020

Try:

app.dependency_overrides[factory.get_service_handler] = lambda: handler

Instead

0reactions
github-actions[bot]commented, Nov 23, 2022

Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.

Read more comments on GitHub >

github_iconTop Results From Across the Web

python - dependency_overrides does not override dependency
Key is to understand that dependency_overrides is just a dictionary. In order to override something, you need to specify a key that matches ......
Read more >
Dependency Overrides: Special Circumstances
The decision to override a student's dependency is made on a case-by-case basis and is reserved for extenuating circumstances.
Read more >
Testing Dependencies with Overrides - FastAPI
To override a dependency for testing, you put as a key the original dependency (a function), and as the value, your dependency override...
Read more >
Dependency Overrides - Finaid
The US Department of Education has given guidance regarding situations that do and do not qualify as unusual circumstances that merit a dependency...
Read more >
Filling Out the FAFSA: Dependency Override - NerdWallet
Although your FAFSA will be submitted, if you have not answered "yes" to the questions that determine independent student status (explained in ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found