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.

app.dependency_overrides[get_db] = override_get_db is not working

See original GitHub issue

The problem

Hi, I have followed the tutorials on the fastapi website where I have found everything easy and clear. However, there is one thing I cannot make work and it looks like a lot of people are having this issue. Still, I have tried all the solutions there are on the internet and could not make it work.

I’m trying to run pytest in my fastapi app but even if I follow the tutorial line by line it doesn’t work. The fake database gets created but still, the real one is being used by the tests (which is a huge problem).

The point is if I set a breakpoint inside of the function override_get_db, it never gets there, it is being totally ignored, the rest of the lines are reached by the debugger, so I guess this is the problem. Can anyone who has had the same issue and solved it help, please?

This is my code:

import json

from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from starlette import status

from database import get_db, Base
from main import app

TEST_DATABASE_URL = "sqlite:///./test.db"
test_engine = create_engine(
   TEST_DATABASE_URL, connect_args={"check_same_thread": False}
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=test_engine)
Base.metadata.create_all(bind=test_engine)


def override_get_db():
     try:
         db = TestingSessionLocal()
         yield db
     finally:
         db.close()

app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)

def test_get_course():
    response = client.post(
        app.url_path_for('create_course'),
        json={"name": "q1", "level": "q1", "description": "desc", "background_color": "bg"},
    )

    response_data = json.loads(response.content)

    response = client.get(app.url_path_for('get_course', **{"course_id": 1}))
    response_data = json.loads(response.content)
    assert response.status_code == status.HTTP_200_OK
    print(response_data)
    #assert response.json() == {'FastApi': 'UOE PRO'}

I’m using Python 3.8.3 and these are the versions I have installed in my virtual environment:

fastapi==0.65.1
SQLAlchemy==1.4.15
psycopg2-binary==2.8.6
uvicorn==0.13.4
pydantic==1.8.2
starlette==0.14.2
passlib==1.7.4
bcrypt==3.2.0
python-jose==3.2.0
pytest==6.2.4
requests==2.25.1

Thank you so much!

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:2
  • Comments:7

github_iconTop GitHub Comments

1reaction
pausanchezvcommented, Nov 15, 2021

@pausanchezv In order to get help with your issue, you might want to follow some best practices and be precise and helpful to your volunteers with your request. Some hopefully helpful remarks on your post:

You claim to follow the tutorial:

even if I follow the tutorial line by line it doesn’t work

First of all, you might be more specific about your sources (these lines you’re talking about in the quote), e.g. by providing one or more relevant links to the tutorial pages you’re referring to, let’s say:

People might be much more eager to help out if you reduce the trouble it takes to figure out what page you’re actually on.

Secondly, your claim doesn’t seem to be true at all - the sample code you provided has been modified in comparison to the original example:

  • you have additional imports such as from starlette import status
  • some imports appear to be modified: you’re importing get_db from .database whereas it comes from .main in the original example (so your version should not run at all if we assume that the other files weren’t touched)
  • some names are changed
  • the test code is changed

Even though most of those changes might be not related to your issue, some might. The obvious modifications you’ve done to the test file at least provoke questions concerning further changes that you might have done to other files that are part of the tutorial example - we really can’t tell!

As for me, I braindeadly copied the tutorial example, ran pytest (with an empty sql_app.db), the test passed, and the record created during the test session was there in test.db. In one word: all as expected, couldn’t reproduce your issue.

I’d recommend to you to start the same way without your modifications and try again.

Or, alternatively, provide us with some more information about changes you made and the commands you’re using to execute your tests (the tutorial does not explicitly provide these commands, so perhaps the mistake can be found there?).

Hope this helps!

BTW: For syntax highlighting, add a language declaration to your code snippet, like

```python
import this

which will be rendered as

```python
import this

I found a workaroud like three months ago, but I’ll take into account how to comment an issue in the future. Thanks.

1reaction
Ecalootacommented, Nov 14, 2021

@oligond Thank you for the above, this all makes sense and I’ve gotten it to work. Thanks again!

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to force a specific version of dependency? - Stack Overflow
For binary compatible conflicts, sbt provides dependency overrides. They are configured with the dependencyOverrides setting, which is a set of ModuleIDs.
Read more >
dependencyOverrides ignored · Issue #95 · rtimush/sbt-updates
When invoking dependencyUpdates , I see dependency updates based on version ranges instead of version overrides. Example: // plugins.sbt ...
Read more >
playframework/playframework - Gitter
Application based on PlayFramework 2.6. We have Controller class which lets user download files from block storage. /GET API function to downlaod the...
Read more >
I couldn't pub get a package from gitlab repository that ...
It looks like you are trying to override the package dependency in dependency overrides. If yes, you should provide the absolute/relative path of...
Read more >
Flutter Riverpod 2.0: The Ultimate Guide - Code With Andrea
Dependency Overrides with Riverpod. Sometimes we want to create a Provider to store a value or object that is not immediately available. For ......
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