I am doing a test with FastAPI about the register of one user in the app. While app is running i can register a user perfectly but when i try to make a test with pytest about the same method i have problems, it doesn't recognise the get_collection
this is the method of the test
import pytest
from httpx import AsyncClient
from fastapi import status
from fastapi_project.main import app
@pytest.mark.asyncio
async def test_successful_user_create():
async with AsyncClient(app=app) as ac:
body = {
'username': 'test',
'email': 'test@test.com',
'hashed_password': 'password_test'
}
res = await ac.post("http://127.0.0.1:8000/register", data=body)
assert res.status_code == status.HTTP_201_CREATED
this is the error
My register method
@router.post("/register")
async def register(
username: str = Form(..., max_length=50),
email: EmailStr = Form(...),
hashed_password: str = Form(..., max_length=50)
):
form_dict = {'username': username, 'email': email, 'hashed_password': hashed_password,
'scope': ['client'], 'enable': False, 'token': secrets.token_urlsafe(16), 'comments': []}
created_user = await auth_db.create_user(form_dict)
if created_user:
return JSONResponse(status_code=status.HTTP_201_CREATED,
content='user is created correctly and check the email')
else:
return JSONResponse(status_code=status.HTTP_409_CONFLICT,
content='user is not created correctly')
the create_user method
async def create_user(self, form_data: dict):
users_collection = db.appDB.get_collection('users')
x = await users_collection.insert_one(form_data)
if x:
return x
and the mongodb configuration
from motor.motor_asyncio import AsyncIOMotorClient
class DataBase:
client: AsyncIOMotorClient = None
appDB = None
db = DataBase()
async def connect_to_mongo():
db.client = AsyncIOMotorClient(URL)
db.appDB = db.client.app # database name
async def close_mongo_connection():
db.client.close()
And those 2 methods have been added in main.py
app.add_event_handler("startup", connect_to_mongo)
app.add_event_handler("shutdown", close_mongo_connection)