Home > Back-end >  How to test fastapi with oracle, sql alchemy?
How to test fastapi with oracle, sql alchemy?

Time:02-01

I have a fastapi application where I use sqlalchemy and stored procedures. Now I want to test my endpoints like in the documentation


import pytest
from fastapi.testclient import TestClient
from fastapi import FastAPI

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from ..dependencies import get_db
import cx_Oracle

host = 'xxxx'
port = 1111
sid = 'FUU'
user = 'bar'
password = 'fuubar'
sid = cx_Oracle.makedsn(host, port, sid=sid)

database_url = 'oracle://{user}:{password}@{sid}'.format(
    user=user,
    password=password,
    sid=sid,
)
engine = create_engine(database_url, connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

app = FastAPI()
init_router(app)

@pytest.fixture()
def session():
    db = TestingSessionLocal()
    try:
        yield db
    finally:
        db.close()

@pytest.fixture()
def client(session):
    # Dependency override
    def override_get_db():
        try:
            yield session
        finally:
            session.close()

    app.dependency_overrides[get_db] = override_get_db

    yield TestClient(app)

def test_index(client):
    res = client.get("/")
    assert res.text
    assert res.status_code == 200

def test_search_course_by_verid_exist():
    response = client.get(
        'search', params={"search_query": "1111", "semester": "S2022"})
    # course exist
    assert response.status_code == 200




I've tried it with creating a new app and/or importing it via getting the app from the main.py

from ..main import app

The method is in my courses router.

@router.get("/search", status_code=status.HTTP_200_OK)
async def search_course(
    response: Response,
    search_query: Union[str, None] = None,
    semester: Union[int, None] = None,
    db: Session = Depends(get_db),
):
.....

return response

The index test already failes by returning assert 400 == 200. For the 2nd (test_search_course_by_verid_exist) I'll get

AttributeError: 'function' object has no attribute 'get'

My main has some middleware settings like

app.add_middleware(
    SessionMiddleware, secret_key="fastAPI"
)  # , max_age=300 this should match Login action timeout  in token-settings of a realm
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=settings.ALLOWED_HOSTS,
)

# MIDDLEWARE
@app.middleware("http")
async def check_route(request: Request, call_next):
....

I'm clueless what I'm missing or if things are just different with cx_Oracle

I've tried changing the testclient from fastapi to the starlette one. I've tried not overriding the db and just import the original db settings (which are basically the same). But nothing works.

CodePudding user response:

I'm not sure if this is the proper way to test FastAPI application, https://fastapi.tiangolo.com/tutorial/testing/

Why you didn't declare client as :

client = TestClient(app)

?

CodePudding user response:

Idk if this was the root problem. But naming my fixtures solved the problem and the db connection is working.

conftest.py

@pytest.fixture(name="db_session", scope="session")
def db_session(app: FastAPI) -> Generator[TestingSessionLocal, Any, None]:

Also created the app fixture

@pytest.fixture(name="app", scope="session")
def app() -> Generator[FastAPI, Any, None]:
   """
   Create a fresh database on each test case.
   """
   _app = start_application()
  yield _app

CodePudding user response:

My answer will not according to your need one but i want to know can we use fastapi for login purposes? Like i have a website on other purpose but i want to integrate logins form 2nd website and use it on 1st website for special purposes. I know its not relevant to your question but i know you have some knowledge about that. So if you know please make me knock.

Thanks.

  • Related