Closed timesbyusman closed 2 months ago
Since you're setting asyncio_default_fixture_scope = "session"
, your _setupdb fixture runs in a session-scoped event loop, whereas your test runs in a function-scoped loop (the default).
Can you try decorating test_login_access_token
with @pytest.mark.asyncio(loop_scope="session")
? This should make the test run in the session-wide loop.
(see also How to run all tests in the session in the same event loop)
@seifertm I already tried it but it didn't worked.
I don't see anything obviously wrong with your code.
You could try to add the --setup-show
option to pytest and check if the event loop fixtures are set up in the correct order.
If that doesn't help, I'd appreciate if you could reduce the code even further and make it self-contained, so that I can debug it locally.
@seifertm I tried --setup-show
for both tests, api and crud. But I can't see any difference in the event loop they both are using
test from crud
test from api
here's a contained version of the api for which I am trying to write tests
from typing import Optional
from fastapi import FastAPI, APIRouter, Depends, Form, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
app = FastAPI()
router = APIRouter(prefix="/auth", tags=["Auth"])
# Mock data and functions
users_db = {
"user@example.com": {
"email": "user@example.com",
"password": "hashedpassword",
"is_active": True,
"roles": ["user"],
"tenant_id": 1
}
}
def authenticate(email: str, password: str):
user = users_db.get(email)
return user if user and user["password"] == password else None
def get_tokens(user_id: int, roles: list, tenant_id: int):
return "access_token", "refresh_token", 3600
def save_refresh_token(token: str, user_id: int, expiry: int):
pass # Just a placeholder
def validate_redirect_url(url: str):
pass # Just a placeholder
class Tokens(BaseModel):
access_token: str
refresh_token: str
token_type: str
redirect_url: Optional[str] = None
@router.post("/login")
async def login_access_token(
form_data: Depends(OAuth2PasswordRequestForm),
redirect_url: Optional[str] = Form(None)
) -> Tokens:
user = authenticate(email=form_data.username, password=form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect email or password")
if not user["is_active"]:
raise HTTPException(status_code=400, detail="Inactive user")
roles = user["roles"]
access_token, refresh_token, expiry = get_tokens(user_id=1, roles=roles, tenant_id=user["tenant_id"])
save_refresh_token(token=refresh_token, user_id=1, expiry=expiry)
if redirect_url:
validate_redirect_url(redirect_url)
return Tokens(
access_token=access_token,
refresh_token=refresh_token,
token_type="bearer",
redirect_url=redirect_url
)
app.include_router(router)
I want to help get to the bottom of this. I really do. But I cannot get started looking into the underlying issue with the present information. For example, conftest.py references some database credentials like USER
and PWD
. _testapi.py uses some unknown settings module, and so forth.
Even if I managed to figure out all the details to get to a running pytest call, it's very likely that I end up with a different configuration and won't be able to reproduce your problem.
In order to help, I need a Minimal, Reproducible Example that I can simply copy and paste to analyze the error you're seeing.
I cannot help without a reproducer. Therefore, I'm closing this issue for the time being.
I am new to pytest and developed async apis along with async database operations. I wrote tests for my crud operations and Yesterday I got error related to 706
fortunately I got the pre-release version (pytest-asyncio v0.24.0a0) and it worked for me. Now I am working on writing tests for async apis. The Problem I am facing is when I pass the db session to async api to be used it gives error
sqlalchemy.exc.ProgrammingError: (psycopg.errors.UndefinedTable) relation "users" does not exist LINE 2: FROM users
I debugged the test before sending request using async client to verify if the tables exist in the database and they did.
I have checked all over the internet but didn't find any solution
my conftest.py looks like this.
NOTE: await init_db(session) is being used to initialize data in the empty test database.
test_api.py
Complete Error log
pyproject.toml