1

我正在使用 FastAPI 对应用程序中一个用户的注册进行测试。当应用程序正在运行时,我可以完美地注册用户但是当我尝试使用 pytest 对相同的方法进行测试时,我遇到了问题,它无法识别get_collection

这是测试的方法

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

这是错误

在此处输入图像描述

在此处输入图像描述

我的注册方法

@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')

create_user方法_

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

和mongodb配置

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()

这两种方法已添加到 main.py

app.add_event_handler("startup", connect_to_mongo)
app.add_event_handler("shutdown", close_mongo_connection)
4

0 回答 0